Sunday, September 30, 2012

Start Hating If-Else statements for quality code

The article I am starting can be quiet debatable and might not make any sense to many of you but, still I want to share my opinion on our dearest “IF” statement. Peep into your past, when you wrote your initial few computer programs (may be at the high school level), you must have used “husband-wife” statements or the IF-ELSE statements [Wow this name (husband-wife) came to my mind as I am writing this article. I am calling this husband-wife because they are always opposite to each other if husband is true wife is false J. Ok! Pardon my silly imagination]. So I was stressing on… that you might have used if-else constructs a lot of times and you must be using that till now- when you are writing professional software’s, which are going to be used across the globe. So what about using “if-else”? Well in my opinion- casual use of “if-else” is bad for your code health.
Wait a minute did I say something bad about “if-else” - because they are kind of foremost important tools for every programmer. “If-Else” is so natural to programmers that it is the first solution every programmer thinks of. Recollect what’s the first thing in your mind when any Quality Analyst guy comes at your desk and says “Mr. Programmer this works well in such & such condition but when under this condition it bombs…”- As you are talking to this quality analyst you keep thinking that it would not bomb if I place an “If” check there. J. Well I agree “If-Else” are extremely important that is why I said casual use of “if-else” is bad for code health.  Let’s figure out below what I mean by casual use and why “if-else” is bad.
If-Else is more prone to be hacked: - This is the worst fear I have when I write any if-else statement- It is very hack prone (I am not referring to any hacking or computer security stuff here; by hack I mean when someone intercept your code lines and add their own code lines to extend the functionality); Difficult to explain, but let me try explaining it with a scenario. Imagine you are writing an application for fruit and vegetable vendors. There you have a condition if fruit is seasonal do some stuff. I am sure your code would have nice flavors of OOPS, proper design. But if you are careless about your use of if-else one of your routine would look like
if (IsSeasonalFruit(fruit))
{
   // Do something
}
else
{
   // Do something else
}
 This condition would work nice and perfect. But imagine after sometime few extra conditions needs to be added. Suppose if the condition is, if the fruit is green- do more extra stuff. Then other requirements pop up- “if the fruit is not green and seasonal and isImported”….
if (IsSeasonalFruit(fruit))
{
   // Do this
     if (fruit.color = "Green" && IsSeasonalFruit(fruit) )
   {
      // Do something for seasonal, green color, imported fruit
   }
}
else
{
       // Do this and…
     if (fruit.color = "Green")
     {
        // Do something for non seasonal green color fruit
     }
       else
     {
           // Do something for non seasonal other colors fruits
     }
}
 Can you imagine how messy your if-else would look like?
This probably is a simple scenario but imagine real life software’s having such routines and the worst case would be, as the life of application grows these hacks are contributed by multiple programmers. I have seen many such routines and I admit that I also contributed to these hacks, making the routines almost unreadable. I am not saying that if-else is completely avoidable (since they cater to our business requirements) but they should be written in such a way that hacking those would be a blunder on programmer’s part. One good example where it is safe to place an “if” check is when you use it for technical checks (like a check of object being null). You should question yourself that, can this if statement be hacked tomorrow if a new condition comes in? If your answer is yes you are doing something wrong.
Use of If-Else may give bad code smell at some places: - Sometimes the use of If-Else can emit foul smell from the code, as in it would give you a hint that your application is not correctly designed (may be it lacking basic OOPS). Imagine a simple bank application where the bank would apply different rate of interest based on various account types. Sounds simple? We would have a method ApplyInterest() and then would check if the account type is savings or current and then would give the interest accordingly. Below is the code snippet.
private void ApplyInterest(string accountType)
{
   if (accountType == "savings")
   {
     interest = 0.1;
   }
   else //if accountType ="current" supposing we have only 2 types of accounts
   {
     interest = 0.06;
   }
}
 
The code snippet though works correctly but gives a hint of bad OOPS structure in the code. A good form of above code would have been…
public interface IInterestCalc
{
   void ApplyInterests();
}
public class AccountSavings : IInterestCalc
{
   private double interest;
   public void ApplyInterests()
   {
     this.interest = 0.1;
   }
}
public class AccountCurrent : IInterestCalc
{
   private double interest;
   public void ApplyInterests()
   {
      this.interest = 0.06;
   }
}
static void Main(string[] args)
{ 
   IInterestCalc interest = GetAccountType(accountType);
   interest.ApplyInterests();
}
private static IInterestCalc GetAccountType(string accountType)
{
   if (accountType == "Current")
   {
      return new AccountCurrent();
   }
   if (accountType == "Savings")
   {
      return new AccountSavings();
   }
   return null;
}
The above code just tells you how you can refrain from writing nested “if-else”, it is not about any other concept of OOPS or something. The good thing about above code is it would not allow user to put unnecessary hacks (in ApplyInterest() method). Even if another type of account comes in, user is forced to create another class and implement that interface. This all saves him from making his code unmanageable because he would not be writing conditions in the core business routines.
If-Else is such important in code that they cannot be avoided but their intelligent use is must. We should always give a thought before writing these. Most of such practices come from experience but few rules should be taken into consideration before using any “if-else”: -
a) It is good to have if-else with the use of null and other such technical constructs.
b) Avoid those into the core methods of business layer.
c) If you think that your piece of if-else can be intercepted by other piece of code, try refactoring your code.
So I would like to end this up with the saying: “Use the power of If-Else wisely rather than being casual towards its use”.

Monday, May 21, 2012

Cloud/Windows Azure- BootStrapper


In this article I would talk about the very basics of setting up an environment for developing a cloud application using Microsoft’s VS 2010 environment. I would also talk about few terminologies which are used in the world of cloud computing. This is a very basic discussion for developing cloud applications, probably I would go over to their details in upcoming posts.
Windows Azure which has become quite popular over the years is the robust and flexible cloud platform provided by Microsoft. Using azure we can build, deploy and manage our applications developed in any language, over vast and robust datacentres provided and managed by Microsoft. It is therefore actually important to understand what actually is “The Cloud thing” before we can understand Windows Azure.
The Cloud Buzz I was in a lot of dilemma to understand this “cloud”, struggling through many questions in mind why this is becoming so popular all of sudden? What exactly it is? I realized later this is really not a new concept if we look back into the earlier days of computing, there were large “job processing centres” where people use to come with their jobs for processing. These jobs were then submitted to huge mainframes and jobs were processed. In the same way big companies like Amazon, Microsoft had developed their large datacentres and offered those to people for their storage and computational needs. This whole concept in this new technology era is termed as “CLOUD”. With the advancement in internet and technology this Cloud is brought closer to the users. You can actually think of cloud as a huge cluster of servers and you can use those clusters for computing/storage or both. Based on above concept let me frame a definition for cloud, there are many definitions to it but I think of cloud as “A computational and storage platform which is scalable and can be used by many people at the same time depending on their demand, thus providing the organizations with a cost effective solution.” To understand the “bolds” in the above definition let me compare this with a traditional server based approach. When I say a server based approach it means for a xyz company their huge server(s) are residing on a nice datacentre.  Imagine there is a huge demand by millions of users across the globe and you would realize that your server(s) residing on the datacentre are not able to cope up with those requests. What you will do? Upgrade the hardware for the server, if you are falling short of data storage you would upgrade the database server, increase the RAM, memory (This whole up gradation in a datacentre environment can be painful in itself). Now that you have prepared yourself for such outbreaks, you realize that it’s a low month from a user perspective so your worthy upgraded hardware is sitting idle most of the time. Do you want such a scenario? Cloud computing and storage provides you an optimal solution to such scenarios. Clouds are scalable that means they can grow and shrink on demand. Since the cloud clusters can be used by many people at a time so their immense hardware and maintenance would not be a burden on a single user/company.

Cloud Models:  The whole cloud concept is based on 3 models
   1)  IaaS: With Infrastructure as a service the cloud provider provides a whole infrastructure like the DBMS, OS, Webserver firewalls setup etc.

             2) PaaS: With platform as a service you can create and setup your own platform on the cloud provider (Microsoft in this case). So for example you are going to add tables and data to SQL Azure on the cloud.
3) SaaS: You setup your application and its data on the cloud network. So your software is provided as a service on the cloud network.

To complete the theory related to cloud lets classify clouds into two main groups
      1)  Public cloud: This type of cloud is available to all the public and people can use this cloud network for computational and storage needs. Examples of such cloud service are: Microsoft, Amazon, and Apple. The concept behind this public cloud is it managed and maintained by individual providers so they are considered to be cost effective.
      2) Private cloud: This type of cloud is managed by individual organizations/companies and are supposed to be more secure but less economical.

Back to Windows Azure Too much of theory about cloud has already spoiled the article so let’s fly into the cloud provided by Microsoft i.e. “Azure”. As already discussed azure is the cloud platform provided by Microsoft. Let us have a look at the basic architecture of an Azure based application which we can develop using VS 2010.




Fabric controller: This is the kernel of a windows azure OS. I call this as the kernel because it monitors, maintains and provisions machines to host applications that we deploy on the cloud. It also manages the various devices through different service like the hardware load balancer.
Azure Networking: This comprises of the complete web of network which azure maintains.
RED Dog Front end interface: This layer communicates with the Fabric controller.
SQL Azure: This is the highly scalable cloud database management system which is based on SQL technologies.
Windows Azure storage: For cloud storage purposes windows azure provide three types of azure storage.
   a)BLOBS: Binary large objects such as video streams, images can be stored in BLOBS. Each BLOB has a capacity of 1TB. With BLOBS we have a concept of containers where a single container can have multiple BLOBS and we access these BLOBS through containers.
   b)Tables: Tables have the same concept of sql tables but they are represented differently in a windows azure environment. The rows are based on the concept of entities with each entity having a property column. Each entity in the table has a PartitionKey and RowKey they together make each row as unique. They are highly scalable and can hold large amount of data.
   c)Queues; They are used for reliable message delivery on the cloud.

Having talked about Windows Azure let’s look at the VS 2010 environment for creating a windows azure application. As stated earlier this article would explain you the environment and terminologies involved in creating an Azure application.
Just open your VS 2010 with “administrator privileges” (right click on VS 2010 and click on Run As-> Administrator).





Click on the Windows Azure Project (If you don’t have the Azure SDK installed VS 2010 would show “Install Windows Azure tools/SDK”. You need to have IIS7 or later to install this SDK).
When you click on the “Windows Azure Project” you will see the following box which is very important for understanding how a Windows Azure application is created.


In windows Azure we have the concept of “Role”. I can consider a Role as a VM/DLL on a cloud platform. It is this Role which makes the cloud application scalable. We see different types of role in the dialog box:
  a)ASP.Net Web Role which is the web UI on the cloud.
  b)ASP.Net Web Role MVC3 Role which is the MVC3 app on cloud.
The other important role is the Background processing service which is the worker role. Worker role can contain arbitrary .net code and it can communicate with the web role. Usually it has code which works in background or used for background processing.
So we can select one web role and one worker role for now.



When we click OK we get a nice populated solution explorer in our VS 2010. Let's dissect this.


The highlighted project (WindowsAzureProject1) is the actual cloud project. It contains the cloud service configuration and definition files (.csfg,.csdef). The definition files tells us which project is associated with the webrole, workerrole what are the service end points. You can view its XML to figure out its properties.
for understanding how a Windows Azure application is created.


Similarly we have service configuration files which have the different connection strings it specifies the connection string, the number of instances for each role. You must have also noticed that there are two service configuration files one for the local development and one for cloud. (When we say local the VS 2010 provides us a virtual cloud environment through the use of emulator).  Just look at the configuration file below. The number of instance for each role is the most important concept in developing cloud application.





Microsoft enters into an SLA that they can provide 99.95% reliability if there are at least two instances of each role. It is this property which makes the cloud application reliable, scalable. We can change the instance count to 2 but it requires VS 2010 SP1 which I don’t have now L. Let’s try running the application with 1 instance. We get the asp.net page up and running mine says “My first cloud app!”J. Notice in task manager that VS 2010 has started a cloud emulator.






Right click on this emulator and click “show compute Emulator UI”.


You will be presented with the following explorer.


Since there is just one web and worker role it is showing for webrole (0) the console trace being spited out.
If you click on the show storage emulator you will see the following screen. It is not useful to us for now since we have not stored anything on cloud. My next articles would gradually move to advance cloud development and would go into details of many more concepts.


I realize that this blog is less of practical stuff but we have to clear many concepts before we can dig deep into writing cloud applications. Still this has just toched the base of cloud application development.





Tuesday, February 28, 2012

Delegates & Events (C#)


Delegates and events are one of the coolest features provided in C#. Both delegates and events are associated with each other, that’s why they are always talked together. For example, if we are using events we should have delegates to support them. In fact delegates & events in conjunction provides a way to implement one of the nicest pattern-the observer pattern (the publisher-subscriber pattern or pub-sub pattern).

            Delegate as the word “literally” means- “a thing which has been assigned to represent something”. In C# we declare a delegate to represent a method. Delegates in C# are always compared with function pointers in C++, C, which in fact is true. Technically delegate is something which holds the address of a method, or address of multiple methods.  Let’s look at an example and understand as to how we declare a delegate:-

private delegate void MyDelegate();
private delegate string MyDelegate(string str);

 The above declaration means that the delegate (MyDelegate) can hold the address of any function which returns nothing (void) and accepts no parameter. Similarly the second declaration means that the delegate can hold the address of any method which accepts one string parameter and returns string. Let’s use the second delegate in a program to understand how we can use delegate to call method(s).

class Program
    {
        private delegate string MyDelegate(string str);
        static void Main(string[] args)
        {
            MyDelegate myDelg = new MyDelegate(MyDelegateMethod1);
            Console.WriteLine(myDelg("Test 1"));
           
            myDelg += MyDelegateMethod2;
            Console.WriteLine(myDelg("Test 2"));

            // Would give a compile time error as the signature of  MyDelegateMethod3 does not match with delegate definition

            //myDelg += MyDelegateMethod3;
            Console.ReadLine();
        }

        private static string MyDelegateMethod1(string strParam)
        {
            return "This is from first method-"+strParam;
        }

        private static string MyDelegateMethod2(string strParam)
        {
            return "This is from second method-"+strParam;
        }

        private static string MyDelegateMethod3(string strParam,string strParam2)
        {
            return "This is from third method-" + strParam;
        }
    }

From the above program it is clear how we can use call multiple methods from a single delegate, this is called a multicast delegate. Notice that when we try to assign the address of MyDelegateMethod3, it gives a compilation error highlighting the fact that delegates are type safe. Also notice how we are invoking the methods and passing the parameters to it (by the use of brackets myDelg("Test 1")).

Behind the scene Delegates are not any kind of magic, when you declare a delegate, the compiler actually generates an anonymous class which is derived from System.MulticastDelegate which in turn is derived from the base System.Delegate. In fact it would be correct to say that when you declare a delegate you are actually declaring a class (though the compiler internally declares the class for you). That is one of the reason why you can declare a delegate anywhere you can declare a class i.e. inside a namespace, inside another class. Try declaring a delegate in a method, you would not be able to do that, think of the reason for that.

Generic Delegates Instead of declaring a delegate every time with different parameters and return types, C# provides Action<T> and Func<T> delegates. The Action<T> delegate can be used to reference a method with void return type. Similarly the Func<T> delegate can be used to reference a method with a return type. Both of these Action and Func delegates can accept up to 16 parameters. Let’s look at an example which would make both of them clear.


class Program
    {
        static void Main(string[] args)
        {
            Action delegAction = delegActionNoParams;
            delegAction();

            Action<string> delegAction1 = delegActionWithOneParam;
            delegAction1("Parameter1");

            Action<string, string, string> delegAction2 = delegActionWithMultipleParams;
            delegAction2("Parameter1", "Parameter2", "Parameter3");

            Func<string> delegFunc = delegFuncNoParams;
            Console.WriteLine(delegFunc());

            Func<string, string, int> delegFunc1 = delegFuncMultipleParams;

            // Would have return value 9 from the method.
            int returnValue = delegFunc1(string.Empty, string.Empty);
            Console.ReadLine();
        }

        private static void delegActionNoParams()
        {
            Console.WriteLine("Call to delegate with no params and no return types");
        }

        private static void delegActionWithOneParam(string param1)
        {
            Console.WriteLine("Call to delegate with param={0} and no return types",param1);
        }

        private static void delegActionWithMultipleParams(string param1,string param2,string param3)
        {
            Console.WriteLine("Call to delegate with params={0},{1},{2} and no return types",param1,param2,param3);
        }

        private static string delegFuncNoParams()
        {
            return "Func delegate with no params";
        }

        private static int delegFuncMultipleParams(string param1,string param2)
        {
            return 9;
        }
    }

The program above is self explanatory. It gives us a clear idea as to how we can make appropriate use of Action and Func delegates and avoid unnecessary “delegates” declaration. Imagine how many delegates you would have to declare for the above program if you were not using Action and Func. Also Action and Func comes in very handy when we have to dynamically invoke methods, you can realize its strength by imagining such a scenario.

            Lambda expression can be of great help with delegates. Below is the example which simplifies the code involving delegates:-

 static void Main(string[] args)
        {
            Func<string, string, string> lambdaDeleg = (str1, str2) => string.Format("This is an example of lambda delegate with two paramters={0} and {1}", str1, str2);
            Console.WriteLine(lambdaDeleg("Parameter1","Parameter2"));
            Console.ReadLine();
        }

The above code demonstrates the use of lambda expression with delegates. Notice how we can specify the parameters and the method body with the lambda(=>).

                       Events

    Having learned delegates lets try making real use of them. Delegates are used a lot to support events. Let’s dig deep into what actually are events. Literally it means “happening of something”. Since our OOPS is based on real world so events are also accommodated in our programming scenario- it means occurrence into an application. As I mentioned before that Delegates & Events together provides a very famous pattern-the observer pattern or the publisher-subscriber pattern. (We will talk about this pattern in our next article). Have you ever used events or delegates before? - A definite yes. In fact you have been using those, quiet a lot. For example you are displaying a message box on click of a button. Here the “button click” is the event and the method body where you write the code to show the message box, is the supporting delegate for the event. Let’s simply jump to a real world example where we would make use of events.

            You often might have come across various web pages where they have a “Notify Me” link. This notification can be related to new product availability or something else. Imagine we have to implement such a scenario where a departmental store would want to notify the shoppers through emails that a new stock has arrived. Events-delegates are very efficient tools for such a scenario. Below is the complete code which implements the idea discussed above. Let’s take the snippets one by one and understand them.

public class NewProductEventArgs:EventArgs
    {
        public string NewProduct { get; set; }
        public NewProductEventArgs(string productName)
        {
            this.NewProduct = productName;
        }
    }
This class serves as placeholder for the argument that events can have. An event can have no arguments as well but usually we define this class to contain objects related to our business requirements. (We will find out its use in next class)

public class DepartmentStore
    {
        public event EventHandler<NewProductEventArgs> NewProductArrived;
        public void NewProduct(string productName)
        {
            if (NewProductArrived != null)
            {
                NewProductArrived(this, new NewProductEventArgs(productName));
            }
        }
    }
This class declares an event NewProductArrived. Notice how this event is declared. The EventHandler is a generic delegate which represents the method that will handle the event. The generic parameter for this is the class which we have created above (NewProductEventArgs). The delegate “EventHandler” requires its generic parameter to be derived from EventArgs that is why we have declare the class as public class NewProductEventArgs:EventArgs. When we use the delegate “EventHandler” it requires that the function definition for this should have first parameter as object and second parameter of type derived from EventArgs.
We have then created the method NewProduct. This method would act as our publisher which would notify the subscribers (subscriber class coming below) that an event has occurred. Notice how we check NewProductArrived event for null. If no subscriber has subscribed for NewProductArrived event this would be null.  The call inside the if check is very important. Using NewProductArrived with brackets would invoke all the handlers which are methods subscribed to this event. (Remember we had learned in Delegates that delegate name with brackets invokes the methods?).

 private string ShopperName { get; set; }
        public Shopper(string shopperName)
        {
            this.ShopperName = shopperName;
        }
        public void RecieveNewProductNotification(object sender, NewProductEventArgs e)
        {
            Console.WriteLine("Shopper {0} thanks for subscribing to our notifications. New product {1} has arrived.", this.ShopperName, e.NewProduct);
        }
This class is the subscriber for the publisher mentioned above. The subscription is done in the form of the method RecieveNewProductNotification. Since the signature of this method fulfills the requirement of delegate EventHandler( object and NewProductEventArgs as paramters) so it acts as a delegate method for EventHandler.

static void Main(string[] args)
        {

           DepartmentStore departmentStore = new DepartmentStore();
           Shopper shopper1 = new Shopper("John");

           departmentStore.NewProductArrived += shopper1.RecieveNewProductNotification;
            departmentStore.NewProduct("Dishwasher");

            Shopper shopper2 = new Shopper("Mary");

            departmentStore.NewProductArrived += shopper2.RecieveNewProductNotification;
            departmentStore.NewProduct("Washing Machine");

            departmentStore.NewProductArrived -= shopper1.RecieveNewProductNotification;

            departmentStore.NewProduct("Furniture");

            Console.ReadLine();
        }
The main method shows how we publish the events. What I am doing with += and -= is subscribing and unsubscribing to the events.  The NewProduct() method in the DepartmentStore class fires or publishes the event NewProductArrived. All the subscribers are subscribed to the event with the lines departmentStore.NewProductArrived += shopper2.RecieveNewProductNotification;

Below is the output of the code (All of the above code should be simple to execute in a console application and is self explanatory).










The output above is interesting. Since the shopper John was already subscribed to the event so he was informed for the arrival of washing machine as well. But when he was unsubscribed with -= he was not informed about the Furniture. (Look carefully in the main method for the cause of the output).
            Events and delegates are powerful concepts provided in C# and are very handy when different “objects” of a system are interested in various “happenings” in the system.
Feel free to add more to this or rectify this. Happy coding!