Monday, December 26, 2011

Tuple: Return multiple values from function

How do you return multiple values from function?

Option 1: use out parameters. But this will just bloat your function signature if the list is long
Option 2: Encapsulate all return values as properties of class and just return the object of that class. But what if that class is not reusable. Will you be just adding the dumb classes to increase assembly size and abusing the OOPs.

Here comes the solution "Tuple" in .NET 4.

By using Tuple type you can return upto 8 items at a time. These items could be value type or reference type.



Actually if you use the instance approach, you can pass a tuple inside Tuple. That means you can return a tuple of any number of items.







There are few points to note though
1. tuple items are read only (there is no set accessor for items). That makes its items immutable.
2. The items can be accessed by using "Item" property. For e.g. to access 2nd item, you have to call myTuple.Item2.

let's take an scenario where you need this kind of structure

 public static Tuple<string,string,string,string> GetAny4ItemsOnMyDesk()
        {
            //Instance approach
            return new Tuple<stringstringstringstring>("Laptop""Phone""Notebook""Pen");
 
            //By using static method
            //return Tuple.Create("Laptop", "Phone", "Notebook", "Pen");
 
        }

This is clear in the above example that you will not like to create a dumb class to contain "unrelated" things. Actually Tuple stucture can be used to contain "miscellaneous but related" items.

Now lets print my desk items from Main

static void Main(string[] args)
        {
            var ItemsOnMyDesk = GetAny4ItemsOnMyDesk();
            StringBuilder sb = new StringBuilder();
            sb.Append("Item 1: " + ItemsOnMyDesk.Item1);
            sb.AppendLine();
            sb.Append("Item 2: " + ItemsOnMyDesk.Item2);
            sb.AppendLine();
            sb.Append("Item 3: " + ItemsOnMyDesk.Item3);
            sb.AppendLine();
            sb.Append("Item 4: " + ItemsOnMyDesk.Item4);
            sb.AppendLine();
            Console.WriteLine(sb.ToString());
          
            Console.ReadLine();
 
        }

This will print my 4 items on my desk.

You can use other data structures like keyvaluepair, collection, array etc to serve same purpose. tuple is like anonymous class generated on compile time so its object resides on heap only which gives you struct kind of datastructure out of the box.
Tuple type is widely used in functional language like "Haskell" and dynamic language like "Python. Since it is of finite size and immutable structure, it is faster than list and performs better than keyvaluepair struct when passed to a function (though data retrieval is faster in keyvaluepair).

Thanks for reading.


Friday, July 22, 2011

How to return private collection


Did you ever try returning a private array like following?


    public class TestPrivateArrays
    {
        private string[] names;
 
        public string[] Names { 
            get
            {
                return names;
            } 
        }
}
            //initialize collection in constructor
            names = new string[] { "Abhishek""Tiwari" };


And you thought, no one from the external world can modify it? Wrong. Since client still has direct reference of each items of collection/Array, he has full liberty to modify it.


     TestPrivateArrays tpa = new TestPrivateArrays();
     tpa.Names[0] = "Modified"//my private array gets modified here


So question is whether you can stop your client modifying your array. Answer is yes, you just need to know how to return your collection items as readonly.

1. Return clone of Array


    public class TestPrivateArrays
    {
        private string[] names;
 
        public string[] Names { 
            get
            {
                return (string[])names.Clone();
            } 
        }
}


You can see, even if client tries to modify the array item, he won't be able to do so. since he is actually modifying a copy of that array but whenever he tries to get the array item, he will get the original one i.e. the unmodified one.



2. Return readonly collection


If you are using .NET generics for e.g. list. You can return the collection as readonly in the following manner.


        private List<string> listNames;
 
        public IList<string> ListNames
        {
            get
            {
                return listNames.AsReadOnly();
            }
        }
            //initialize collection in constructor
            listNames = new List<string> { "Abhishek""Tiwari" };


Now if user tries to modify the collection, he will get a runtime error saying that collection is readonly (see following).



3. Use some inbuilt readonly collection


you can find a datastructure called ReadOnlyCollection under System.Collections.ObjectModel which is strong typed and templatized. You can use that in following manner.


        private System.Collections.ObjectModel.ReadOnlyCollection<string> colNames;
        public System.Collections.ObjectModel.ReadOnlyCollection<string> ColNames
        {
            get
            {
                return colNames;
            }
        }
            //initialize collection in constructor
            colNames = new System.Collections.ObjectModel.ReadOnlyCollection<string>(new List<string> { "Abhishek""Tiwari" });


Note that if user tries to modify this collection, he will get compile time error (remember in case of list, it was runtime error because when you modify the list, it evaluates its isReadOnly property at runtime).

Thanks for reading the post.

Thursday, July 21, 2011

"toString" method in JavaScript


Every object in JavaScript has 'toString' method by default. This method returns the representation of that object in string format. If you have ever called alert on an object in mistake, you would have come across this message in alert box  '[object, Object]'. Actually when you put alert on object itself, it is assumed that you want to see the internal representation of the object and its 'toString' method is invoked which returns the default string for any object as mentioned before.
So what if  you want to make your object representation more meaningful or let say you want to debug your code and just put alert here and there and wants to see what your object looks like at different point of time. Here comes overriding 'toString' method. C#/VB.NET developers, remember yourself overriding toString method of base class "Object". This is exactly similar to that.
Let me take an example as following


function Employee(name, age, company) {
    this.employeeName = name;
    this.age = age;
    this.company = company;
 
    this.toString = function () {
        return "Employee " + this.employeeName + " of age " + this.age + 
" working in " + this.company;
    }
}
What I am doing here is basically forming a meaningful string from my Employee object properties. Now let me put an alert on employee object.

    <script language="javascript" type="text/javascript">
          window.onload = function () {
            var e = new Employee("Abhishek""30""abcSoftware");
            alert(e);
        }
    script>

When I run this code, on my window onload I get following popup.



As I said before, I can use this method for debugging purposes or in general conveying a better representation of my object (for e.g. if you are writing a JS library, you would like your users to get a meaningful message while putting an alert on your objects, won't you?)
Note: If you put alert on function name itself for e.g. alert(Employee), it would be 'toString' method of function type that will be called and it will print your entire function in the alert box. Try that.
Thanks for reading.

Javascript intellisense in Visual Studio 2010


Web developers always found difficult to write code when it comes to writing in any scripting language. There are many reasons contributing to it like lack of debugging features, intellisense support, no early catch on errors etc. If you know what editors like Visual Studio gives you for other contemporary strongly typed language (C#, VB.NET etc) you will find difference of an era.

I am an ardent user of Visual Studio and would like to share with you that there are many good features  that have been bundled with VS 2010 to support intellisense and debugging for JavaScript. If you know them all, you will surely thank Visual Studio team for making your life easy like never before.

Let me explain some of the intellisense support here.

Type inference in JavaScript


JavaScript is a dynamic language and does not support explicit type declarations, due to which, earlier there used to be a generic pop up showing properties for all types. VS2010 can now infer the type as soon as the assignment happens and shows only relevant properties. See the below example, it is showing the properties applicable to a number.





As you know, being a loose typed language, I can change type of any variable at any time. so what if at some point of time i assign a string to my variable "num".


You can see, now VS intellisense shows me properties only relevant to a string. Great, isn't it!!
Kindly note that it does not matter that you are writing inline scripting or inside an external file. Same intellisense works beautifully at all the places.


You can see above, it now shows the properties of a DOM element only.

Intellisense to Functions


Why you have always been asked to decorate your methods with comments during your code review, it is not just to let others understand more about your functions right there but also to give descriptive knowledge to the consumer of your methods about how that method can be called, what purpose that method serve, information about parameters and returning object etc.
By default, VS can show you the name of the function and input parameter if it is put correctly in the scope.

Let say I have written a method "FOO" in my test.js

I included my test.js correctly in my aspx page and now call the method

You can see, without looking at the external file, I know what parameters "foo" expects and can correctly call it.

Wonder, if you could also add some intellisense hint to your method? check this now.

put a summary block under your function as following. this is written exactly the same way, you write it on top of your C#,VB.NET method. so don't need to remember the template, just copy it from any of your C#/VB code page.


and now let me call the method once again and let the magic continue



Getting intellisense amongst external JS files


Do you feel jittery when you need to call a function but don't know how to exact type it and the function is hidden somewhere under the plethora of JS files you are referring in your page (Javascript is case sensitive) or what if you want to make sure you don't write the function with the same name written elsewhere, or just for the sake of simplicity of coding you want everything under the scope (variable, functions etc) visible infront of you before writing even a single line of code as it happens when you write code in C# (you can see every public/protected/internal/private class/methods in the intellisense as per the scope).

There can be many reasons, you always desired intellisense to be available not just inline but also spanning it across external files as well under the scope. Let me tell you it is fairly possible with VS 2010.

Let say I created a new js file and want to reference my test.js (having function FOO, as explained above). What you need to do, just go drag your test.js into your new javascript file. VS automatically add the reference in following manner


Now you have complete access to everything written in test.js to your new file. You can add as many references as you want in  your new file. VS interpreter will automatically discover that file and present you the full intellisense support.





Hope the article would have given you some insight on inbuilt intellisense support of JavaScript in VS. You can explore more on it and be able to write faster code with lesser number of errors.

Happy coding and thanks for reading!


Credit goes to Scott Gu. Reference article: http://weblogs.asp.net/scottgu/archive/2007/06/21/vs-2008-javascript-intellisense.aspx

Wednesday, April 20, 2011

Beware of Constants


Let say I have a third party library having code as following

namespace Test
{
    public class TestClass
    {
        public const string NAME = "Abhishek Tiwari";
    }
}

My application uses this library and prints this name on console in following manner

internal class Program   
{        
      private static void Main(string[] args)        
       {             
          Console.WriteLine(Test.TestClass.NAME);             
          Console.ReadLine();         
       }    
}

After sometime my library provider company is owned by some other company and changes the const value to something public const string NAME = "I am no more Abhishek Tiwari";

Now as being a loyal customer to that company, you get  the new version of the library and replace the old version by it and now click on your executable again.

Whack!!! You still see "Abhishek Tiwari" written on the console. 

So what happened in the background is mystery for you but before you bang your head here and there in confusion, let me solve this puzzle for you. 

Actually when you last built your project, your compiler has put the hard-coded values in place of consts everywhere in your IL so those consts values no more refer to any part of the code whatsoever. If you look into the IL, you will find something like

//My IL (compiled code)
internal class Program   
{        
      private static void Main(string[] args)        
       {             
          Console.WriteLine("Abhishek Tiwari");             
          Console.ReadLine();         
       }    
}

So even if now I have updated the third party without rebuilding my code (since it is essentially not required) my IL will remain same, and in my IL const "NAME" which was linked to third party is vanished, leaving hard coded const value behind.


Get working code from TestConst

I hope if you are a third party provider, you will keep this in mind to avoid any shock. I am not sure what is the best possible solution for this (will keep you posted, if I come across any) but for now you can change your "const" type by "static readonly" so that your library consumer can always see the modifications.



** Thanks to Shailendra (Author in aspnettechstuffs) for sharing this valuable information with me.