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