Thursday, August 27, 2015

Open Closed Principle in .NET

Last week, I discussed Single responsibility principle here. In today's blog post, I will be discussing the second principle out of the 5 SOLID principles i.e. Open-Closed principle(OCP). 

Open Closed Principle

According to this principle, a class should be open for extension but closed for modification.
We all know that the only thing that is constant in this world, and more so in software, is change. The requirements change all the time and many times we keep adding new functionality on top of the existing ones. This principle guides us that instead of modifying existing classes, we can extend the existing classes to add new functionality. This makes our code easy to reuse and maintain.

Let's understand this with an example:

Suppose we have a class like this:

public class Product

{

        public decimal Price { get; set; }

        public DiscountType DiscountType { get; set; }

}

where DiscountType is an enum with 2 enumerators:

public enum DiscountType

{

    None = 0,

    Sale = 1

}

And suppose, you have a PriceCalculator class like this:

public class PriceCalculator

{

    public decimal GetTotalPrice(Product[] products)

    {

        decimal sum = 0;

        foreach (var product in products)

        {

            if (product.DiscountType == DiscountType.None)

                sum += product.Price;

            if (product.DiscountType == DiscountType.Sale)

                sum += product.Price*(decimal) 0.9;

        }

        return sum;

    }

}


Now the code works fine and return you the Total Price of the product. For all regular price items, you return the full price. For sale items you provide 10% discount.
Now, the client comes in and says I want to add another type of discount here, say super sale with 20% discount. We can cater to client requirements by adding another enumerator to the DiscountType enum and add another if condition in the PriceCalculator. Now, next time the client comes in and asks for mega Sale and so on. Looking at the price calculator method, you can imagine that this can get pretty ugly and difficult to maintain. So instead of adding to the enum and if conditions in GetTotalPrice(), we can close our PriceCalculator class for modification and extend the existing classes like this:

First, we will need to abstract out our Product class like this:

    public interface IProduct

    {

        decimal Price { get; set; }



        decimal TotalPrice();

    }

Then, we can add specific classes for Regular Product and Sale Product:

public class RegularProduct : IProduct

{

    public decimal Price { get; set; }

    public decimal TotalPrice()

    {

        return Price;

    }

}




 public class SaleProduct : IProduct

 {

      public decimal Price { get; set; }

      public decimal TotalPrice()

      {

          return Price*(decimal) 0.9;

      }

 }

Now, the PriceCalculator class will look like this:

public class PriceCalculator

{

        public decimal GetTotalPrice(IProduct[] products)

        {

         return products.Sum(product => product.TotalPrice());

        }

}

So, we don't need to change this GetTotalPrice() any more. We can keep adding any new product types as the requirements come up by implementing IProduct.

So for adding superSale item, we can simply add SuperSaleProduct which implements IProduct and our GetTotalPrice() will remain unchanged. And similarly, if the amount of discount needs to be changed for existing SaleProduct then also we don't need to change the existing GetTotalPrice().

Conclusion

So we saw how Open-Closed principle can help us write code that is easy to extend and maintain. 
The closure in changes for any class is mostly theoretical. This is a simplified example to illustrate what the principle is and how we can adhere to it. In real world, it might not be so simple or practical to use it all the time. But when we have such a scenario and we can simplify our code using this principle, we should follow it. 

For future updates to my weekly blog, please subscribe to my blog via the "Subscribe To Weekly Post" feature at the right and follow me on Twitter. Until then Happy Coding :)


Thursday, August 20, 2015

Single Reponsibility Principle in .NET

Recently, I was reading about SOLID principles and how they can help us write better code. SOLID principles help make our code more supple so it can easily change with change in requirements. It helps us in writing our code more towards object oriented design rather than procedural code. It also helps make our code less rigid as well as less fragile and easy to reuse. I will be discussing all these principles one by one continuing in subsequent posts.

In today's blog post, I will be discussing one of the SOLID principles which can help in better design and implementation of the system, i.e. Single Responsibility Principle (SRP).

Single Responsibility Principle (SRP)

According to this principle, a class should have only one reason to change. If the class is doing too much then there might be multiple reasons for it's changes.
In other words, each class should do only one thing and do it well. It helps in separations of concerns. Let's look at an example to understand this:

For example you have a method like this:

public class Employee

{

      /*

        other properties and methods 

      */

      public ActionResult Details(int? id)

        {

            Log.Debug("Reading Employee " + employeeId);

            if (id == null)

            {

             return new 
             HttpStatusCodeResult(HttpStatusCode.BadRequest);

            }

            Employee employee = db.Employees.Find(id);

            if (employee == null)

            {

                Log.Debug("Employee not Found" + employeeId);

                return HttpNotFound();

            }

            Log.Debug("Returning Employee " + employeeId);

            return View(employee);

        }

      //....

}

By looking at this code, you can clearly see that this method is doing more than intended. For retrieving the employee, it's doing all the logging as well. If in future, we need to change logging mechanism, then we will have to revisit the code, as well as if we change the way employees are retrieved, then also we need to change this code. So there are multiple reasons for this class to change.

So, one way to solve this problem is to have a separate logger like this:


public class EmployeeLogger

    {

        public void Reading(int id)

        {

            Log.Debug("Retrieving Employee " + id);

        }

        public void Returning(int id)

        {

            Log.Debug("Returning Employee " + id);

        }

        public void NotFound(int id)

        {

            Log.Debug("No Employee found " + id);

        }

    }


Now, the Employee class might look like:


public class Employee

{

      private EmployeeLogger _logger = new EmployeeLogger(); 

      /*

        other properties and methods 

      */

public ActionResult Details(int? id)

        {

            _logger.Reading(employeeId);

            if (id == null)

            {

             return new 
             HttpStatusCodeResult(HttpStatusCode.BadRequest);

            }

            Employee employee = db.Employees.Find(id);

            if (employee == null)

            {

                _logger.NotFound(employeeId);

                return HttpNotFound();

            }

            _logger.Returning(employeeId);

            return View(employee);

        }

//... 

}

So now the logging responsibility belongs to EmployeeLogger class. If in future, we need to change the way employee logging is supposed to be done, we can change only the EmployeeLogger and don't need to make changes to the Employee Details method.
Currently, you might think that we have written a lot more code for a very small benefit. But, as the code base grows larger and the requirements change, you will see the benefit of it in the long run. Also, this provides us as a good base for better design and other SOLID principles to apply upon, as we will see in subsequent posts.

Conclusion

The SRP is one of the easiest to understand out of the SOLID principles but it's hard to get it right. Following the principle at each and every time might be an overkill but in general we should try to adhere to it as and when needed. The understanding of when to apply the principle and to what extent comes with experience and practice.

For future updates to my weekly blog, please subscribe to my blog via the "Subscribe To Weekly Post" feature at the right and follow me on Twitter. Until then Happy Coding :)


Thursday, August 13, 2015

Command Query Separation

Recently, I was reading about some basic encapsulation concepts and I came across command query separation. So this week I will be talking about what command query separation is and how it is useful.

Command Query Separation (CQS)

The term Command Query Separation was introduced by Bertrand Meyer in his book on object oriented design. The command query separation pattern is not only limited to object oriented design but can also be applied to functional programming or anywhere else.
According to CQS, any operations in the system should be either command or query but not both.

Command: Any operation that has observable side effect on the system. 
Query: Any operation that returns data and does not mutate observable state.

For example, in one of your class, you have

public void SaveName(int employeeId, string name)

This is saving Employee name into the system. Note the return type void. So this is changing the system state and returning nothing. So it's a command.


Another example, suppose you have

public string GetEmployeeName(int employeeId)

This should return the Employee name from the system and should not change the state of the system in any way. Note the return type is string (not void). So it should be query operation. The query operation should be idempotent i.e. no matter how many times you invoke a query, it should return the same response for a given system state.

Why Useful

This makes the code easier to read and helps us in separating the concerns. Imagine if you have some Get method which also changes the system state. The consumer of your code might get different response on calling the same GET operation. Such a system is non-intuitive and prone to errors and difficult to maintain. 

Similarly, if you have some Save method like this:

public string SaveName(int employeeId, string name)

The Save method here is returning a string as well as changing the state of the system. This is against the command query separation principle. Any operation can either return something or change the system state but not both.

By looking at the method signature, we don't know what the string return is. Whether the string returns the Employee name or error message or employeeId casted as string or something else. The consumer of the method will have to look into the method definition to find this out. Imagine if it's a complicated method. So now the consumer will have to either go through all of it or test it by passing different types of values or read through the whole documentation, if any. Any of these is not very favorable and makes us feel that the code sucks.

Having clear separation makes our code more readable, more intuitive and easy to follow. Furthermore, it helps in the maintainability of the code as well. When reading the system state, the consumer should be carefree that he/she is not changing the system state in any way.

Conclusion

CQS gives you a good foundation on which you can build good quality software.
As everything is life, the answer to when to use this principle is: "it depends". This is a generic principle to keep in mind when writing code. Nothing prevents you from disobeying the principle but if it can be followed, we should adhere to it.

However, we might have some exceptions where we can't follow the principle verbatim. For example, if you have an email system, where reading an email marks the email as Read. So here the Query operation could be changing the system state and marking the email as Read. So personally I would prefer to follow the principle when I can but I should be ready to break it when needed.

For future updates to my weekly blog, please subscribe to my blog via the "Subscribe By Email" feature at the right and follow me on Twitter. Until then Happy Coding :)



Thursday, August 6, 2015

Secure Cookie in ASP.NET Application

In a previous blog post, I discusses about the HttpOnly flag in cookies here. In today's blog post, we will be discussing what the secure flag is on a cookie and why we should keep it set.

Secure Flag on Cookie

There is a boolean flag on the cookie called Secure which decides whether to send the cookie on an HTTP request or not. If the flag is set on the cookie, the cookie will not be sent on a regular Http request; it will be transmitted only on Https request.

Imagine if you have a web application which implements Https to be more secure. Once you login, the Authentication cookie (named as .AspNet.ApplicationCookie in my .NET Application) gets set. This cookie gets sent with each subsequent request to inform the server the identity of the logged in user.

If a man in the middle tries to view those requests, they will not be able to see anything as they are encrypted (Https). However, out of multiple requests, if there is even a single request on Http (for example for some resource like Javascript, image, css, etc), the attacker can see all the cookies (including authentication cookie).


Authentication Cookie in .NET

The attacker might be able to convince the user to successfully issue an Http Request through other means (social engineering). Such an Http request poses a serious security vulnerability as authentication cookie is exposed.
Using this authentication cookie, attacker can hijack the victim's session without victim ever even knowing about it.

How To Prevent

In an ASP.NET application, we can set the Secure flag by adding this to web.config:

<httpCookies requireSSL=true/>

This will set the Secure flag on all the cookies.
Or if we want to set it at per cookie level, we can set the HttpCookie.Secure property to true.

Conclusion

So we saw what the secure flag is on a cookie and why we should always set it in our application for cookies carrying sensitive information. This flag does not make the cookie secure from all types of attacks, however, this adds another layer of protection to keep our cookies more secure.
For future updates to my weekly blog, please subscribe to my blog via the "Subscribe By Email" feature at the right and follow me on Twitter. Until then Happy Coding :)