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.



Tuesday, April 19, 2011

Design By Contracts


Putting validations all over the places in your code is just like convoluting your code. You must have wondered sometime how good it would be if I could decorate my class with another class at runtime with all the validations.  There are certainly options available with latest .NET framework for e.g. you can use injection to add behavior to your classes at runtime. You may use Unity or any other container to do so. If you are design freak, you must have understood that by all means any implementation to provide change in runtime behavior can be done by using "Decorator pattern" only. I will discuss about this in some other article but what I am going to share with you in this article is how to use Code Contracts. 

Code contract is something which is already present in the framework 4 under the namespace System.Diagnostic.Contracts and heavily used by .NET internal code for e.g. if you expand ICollection, IComparable etc interfaces you will find them using contracts. 
Unfortunately code contracts feature comes by default with Visual Studio Premium and Ultimate edition but if you are using lower version like Professional one, you can still download the external library and make a use of them.
Ok so enough background now let’s jump into the implementation part.

As I said earlier, if you are not using VS 2010 Premium or Ultimate edition, you can download the Code Contract extension from Code Contract Extension

Fair enough, now I am taking a use case where I am providing user a Math divide functionality and I want to make sure that user does not divide the number by zero.

One way I can do it this

 public class MathFunctions
    {
        public double Divide(double number, double divider)
        {
            Debug.Assert((divider == 0), "cannot divide by zero");
            return number / divider;
        }
    }

This will make sure that as soon as my client passes zero, he gets an exception. I can implement divide function as

 if(divider!=0)
    return number / divider;
 throw new ArgumentException();

But this is essentially not part of my business logic and henceforth should not be part of my function. Now I need a way to inject the validation at runtime. Let's see how we can do the same using contracts.

Refer System.Diagnostics;System.Diagnostics.Contracts; namespaces in your code.

I now define an interface which will contain the required method signatures. I will decorate this interface with contract so that my compiler could inject the contract into all concrete implementers of my interface.

  [System.Diagnostics.Contracts.ContractClass(typeof(ITestContractCodeContract))]
    public interface ITestContract
    {
         double Divide(double number, double divider);
    }

You see I am telling compiler that my interface carries a contract which is explicitly implemented in class ITestContractCodecontract. Now time to write the contract class.

[System.Diagnostics.Contracts.ContractClassFor(typeof(ITestContract))]
    public class ITestContractCodeContract : ITestContract
    {
        public double Divide(double number, double divider)
        {
            Contract.Requires<ArgumentException>((divider > 0.0), "You cannot divide by zero");
            Contract.Ensures((number != 1), "abc");
            return default(double);
        }
    }

Again I am decorating this class to tell compiler that this class carries contract for my interface. There are many methods which you would like to look in Contract class (see my references below) but since mostly you would like to write some precondition and postcondition, I am using Requires and Ensures methods of Contract class in my example. Requires provide you a precondition and Ensures provide you a postcondition contract.

Now what my contract class means to runtime, it says that any class implementing my interface divide function if and when called, should first validate (before going into divide function implementation) that divider is not zero and if contract is not broken it should run through the concrete implementation of divide and as soon as it comes out of that function it should make sure my postcondition contract (number not equal to 1) is not breaking.

let me write one concrete implementation of my interface

public class ActualTestContract : ITestContract
    {
        
        public double Divide(double number, double divider)
        {
            //Debug.Assert((divider == 0), "cannot divide by zero");
            if(divider!=0)
                return number / divider;
            throw new ArgumentException();
        }

    }

Now let me call my concrete class and check what happens

internal class Program
    {
        private static void Main()
        {
            ITestContract test = new ActualTestContract();
            double division = test.Divide(1, 0);
            Console.WriteLine("division value is " + division);

            Console.Read();
        }
    }

You see my call actually breaks both pre and post condition but so far if you are copying the above mentioned code in a project and trying to run, you won't get any exception. Actually there is a config setting in your Project -> Properties ->Code contract tab (you will get it only if you have installed the extension) -> check runtime contract checking

If you do so, you will get assertions for both pre and post condition. Please note that if you are using VS2010 premium or ultimate edition, you will get these assertions failing on compile time, since it uses static code analyzer which is able to look into your code contract implementation and evaluate it on compile time it would be able to catch exceptions like NullReference, ArgumetOutOfRange etc.

There might be a case when you want some validations to be applied to your class level. You can do so by writing a method in your class and putting an attribute "ContractInVariantMethod" for e.g.

 [ContractInvariantMethod]
        private void ObjectInvariant()
        {
            Contract.Invariant((this.definition != string.Empty), "You have to have definition properly defined in the class");
        }

The code will be evaluated as soon as instance of this class is visible to any client. It says that no matter what, my instance cannot have empty definition (assume definition is a property inside my class). 

If you want to understand more of Contracts Refer following links

I am attaching herewith my implementation code for you to debug and get a real feel of Code contracts.

Hope this article has helped you understanding the power of decoration and how you can keep your code clean by separating out the aspects (validation, logging, exceptions etc).

Thanks for reading..



kick it on DotNetKicks.com