Tuesday 18 October 2016

SOLID Principles


SOLID Principles -  Learn it before learning any design patterns. Every Software engineer should know


          Friends have asked me to blog about critical design patterns. So before starting any one of the design patterns, I thought let me start with underlying basics of every design patterns. 

To Become a good Software engineer you show know  SOLID principles. These should have been taught in our universities. But we learn this after we have coded for a while and when we want to move to the next level. 

These principles should be ingrained in every software engineer who writes code. 

Solid Principles should be considered even while creating a new class, to make sure all the SOLID principles are satisfied. 

These principles should be considered even while creating the Methods/Properties.  

In this discussion, we will go through the principal based on class but the principle should be applicable for all classes/Methods/modules or any software entity or the Whole Architecture. 

I am no expert, I get better in understanding them each and every day. I am still a learner of these principles and I wish I was told earlier in college, about SOLID principles.

S – Single responsibility

 

"S" in "SOLID" stands for Single Responsibility principle.

          Single Responsibility is a very important principle that needs to be considered when creating a class. This principle will alone make your code more maintainable.

Whenever you create a class, you should make sure it does only one job and does not do any other work. 

It should be as dumb and lean as possible. 

When you think the class has more than so called fuzzy logic inside then it is a symptom, your class is doing more. 

Violation of this principle, can also be identified when the class is more than 70-80 lines of code. 

Make sure the class is as dumb as possible, whenever your class knows little bit information about another class then there is code smell of breaking single responsibility.

Shortcuts and Code smell.

  • Create a new class when your class is more than 80 lines of code (I know it is tough, keep it as ideal, but u will come through when you have this low limit – 400 lines is max). 
  • Create a new class and move the logic that is fuzzy from the current class, meaning the class should be as dumb as possible. 
  • Create a new class when you write a logic that is needed for only one type of situation meaning if you are writing an “if statement” inside a class to handle particular fuzzy case then you are probably violating single responsibility.

O – Open closed principle

 

"O" in "SOLID" stands for Open Closed principle.

          Class should be open for extension but be closed for modification, Conformance to this principle is what yields the greatest benefits claimed for object oriented technology; i.e. re-usability and maintainability. 

Whenever you create a new class which implements an interface then follow this has your benchmark. 

Consider this scenario, the Class you have created is shipped as dll and you want to extend/update a existing functionality. Now think how you  should have defined your shipped class or implemented the class, such that you can still extend the functionality but cannot modify already shipped dll.

So You ALWAYS KEEP IN MIND a CLASS WILL/MUST/SHOULD BE CLOSED (not even when packed and shipped as dll) EVEN IF IT POSSIBLE FOR YOU TO CHANGE.

Once you ingrained the above concept in your brain then you can always define class which follows this principle. 

Note you can never define anything that can never be changed, that is complete closure, so closure cannot be complete it can only be strategic.  So try to keep your changes local. For strategic closure refer here (page no.6) 

Short cuts & Code Smells
  • Make all variables private in the class, keep the variables local to avoid public variables, if you need to data for different methods in the same class then pass it as parameters and avoid private members as well.
  • Avoid any dynamic run-time conversion, whenever a new class is implemented, make sure the class's base class implementation is not changed due to addition of new child class. If the parent class is not changed due to the child class addition that type of dynamic can be used.
  • Never use a global variable
  • Always use interface/abstract class and never use the concrete class for instance, a layer of abstraction helps a lot in Open/Closed principle. Law of  All problems in computer science can be solved by another level of indirection.

 

 Liskov Principle

 

"L" in "SOLID" stands for Liskov substitution principle.


   Principle is coined by Barbara Liskov. This principle is more of a rule that should  be tried(reality very tough, can go close though) not to be violated rather than being followed.


“If S is a subtype of T, then objects of type T in a program may be replaced with objects of type S without altering any of the desirable properties of that program”.


Above abstract definition sounding so complex & weird principle to understood. You can understand it by understanding the below example.

If the Person knows to drive a car then he can drive Honda and if he know how to drive Honda he is supposed to know how to drive a car.


          Let us consider class CAR example which we can use to understand the principle. Let us define CAR as base class which has “Steering” attribute and a Drive () method. Now derive Honda from the CAR class. Read it again, if you don’t understand it. 

  Let us not complicate further since I am planning to write a new blog on its own by explaining the behaviour subtyping and how contra-variance and co-variance plays a role in the subtyping. Just understand we should be able to substitute a parent object with child object and vice versa.

Understand the Shortcut & code smell as of now, that is more than enough to understand the L of SOLID Principle.

Above example has a Drive method when the person applies the drive method he should be able to drive both the basic car and also the Toyota car.  Now consider Audi car which has Electronic Auto-Gear Shift.



In the above example we are inheriting the Toyota and Audi car where the Toyota is manual shift gear car and Audi is auto shift gear car, then when I try to replace Toyota instance with Audi we might get an exception, so the behaviour changes.

If we remove the “throw new NotImplementedException()” code and leave with no implementation,  still the rev might not have changed in the car based on the gear shift, so it violates the functionality of the car.

 In this case we might need to classify a new class as high end, this principle might cannot be fully followed in real world computer science, so going to close to follow it by understanding the seeing through the code smell will help.
 
If you want to understand the sample in real computer science world then look into the example in code project here

Shortcut and code smell

 

          As for the code smell, if you find any additional "if statement" handling a particular object instance based on its type then you might be violating the Liskov principle.  

          In the below implementation code, if the Toyota type is ETIO then the implementation is different. 



Always have a general rule whenever you find an “if statement” to solve a particular condition like hack then it will mostly code smell.


Interface Segregation

           "I" in "SOLID" stands for Interface segregation principle.


If you are forcing the clients to implement methods which they don’t need to then you are violating this principle. 


Whenever you develop an interface for the client to consume then the interface should be as lean as possible. Interface should not never be fat meaning it should have only methods which it can handle. This is the simplest principle to follow. 

Code Smell

 

We will take the previous car example for the manual and automatic gear shifting, but the car will be an interface instead of a class.

In the above example Maruthi800 does not have auto gear vehicle so ShiftAutomaticGear() is irrelevant, so whenever you find yourself any interface that need not be implemented or need not be consumed, then either you are using wrong interface or your framework has fat interface for the functionality.

Dependency Inversion Principle

         
                    "D" in "SOLID" stands for Dependancy inversion Principle

          I have written separate blog regarding this principle because to understand this principle, you need to understand below concepts before understanding the actual principle. This principle when adhered will automatically adhere you to above principles and avoids code smell.


I have explained it in my blog in detail you can read more about it @ my blog

          Read more about the principle again in different ways which suits you best may be YouTube video or any other blog and make sure it becomes your second nature. Once you understand this principles you will be able to code better which is more maintainable and extensible. This will be base for any design patterns, so please make sure you understand them completely. In next blog we will look into the Laws of Computer Science and start with design patterns.



IMPORTANT: Leave a comment to share what you learned, and hit the “like” button to let others know about it (make sure you’re logged into Facebook to like and comment).

Sunday 26 June 2016

What is ARM & Revolutionizing the cloud deployment



Use Azure cloud ARM Spin up a web application/Sql Server/SQL Database and storage account in azure within 10 seconds  


                Early web developers knows how painful is to set up a web application in IIS and make it work because IIS behaves crazy when your day is bad. Azure has made the life of every web application developer's life so easy by creating the web application in just a few clicks and your website is public and available to internet user, which is not easy in IIS in any sense. And we don’t even have to talk about deploying the web application which has a load balancer. 

                With the Presence of ARM – Azure Resource manager, setting up a Web application, SQL Server, SQL Database and storage manager is only a configuration JSON and which can be created by the visual studio as a template, and deployed using visual studio !

You can spin up a new web application (even VM’s) with any resource (web-app, SQL server etc.) and you can also update the already ARM created resources.

                Let us look out how we can setup a Web application, a SQL Server, SQL Database and azure storage Account in seconds. 


In Visual studio 2015, create a new project and select the azure resource group template.




You need to select the Azure Template with WebApp + Sql from the next window that appear after clicking ok.



Once we click on OK, project is created will have only three files as below.




Three files are 

  • Deploy-AzureResourceGroup.ps1 
  • WebSiteSQLDatabase.json 
  • WebSiteSQLDatabase.parameters.json


We will look in detail about each and every file and see how these files helps us to create azure resources stack in matter of seconds.

Deploy-AzureResourceGroup.ps1

This file is used by the visual studio to create the application in azure and it is nothing but a power shell script. It runs the command needed to create the application using the JSON, provided as input. It will be same for any azure resource group project, irrespective of resource you choose to be deployed.

WebSiteSQLDatabase.parameters.json

                This files contains the parameter that can be used to configure the resources of the azure, this can be configured to have default values.  (Parameters section of WebSiteSQLDatabase.json file will be configuring the type of parameter used, default values etc.)

Empty Template contains following elements, will look like below.



WebSiteSQLDatabase.json
 
                This file provides the resources information that needs to be installed in the cloud, it has own variables that can be used declared and used inside the JSON file where we don’t want to repeat the logic for creating a string or any other object that can be reused. For more details about the every element you refer here . We will discuss the template further to understand the resources.

Empty Template contains following elements
{
   "$schema": "http://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
   "contentVersion": "",
   "parameters": {  },
   "variables": {  },
   "resources": [  ],
   "outputs": {  }
}

Every resource will have entry in the resources section and it will have its own configuration detail. For explanatory purpose, we will only look into the web application alone. For more details, look into my code repository in GitHub



Above JSON explains the web app that will be created from the above JSON, you can see the variables are set at runtime based on the parameter value, which can be altered by us in the configuration. 

The current template from the visual studio has only WebApp+SQL, when we need to add one more resource, in our case it is storage manager, we need to add through the another cool feature in Visual studio called as JSON Outline

You can open this window from other window in view menu. Open the WebsiteSQLDatabase.JSON before opening the JSON Outline. 


You can add the storage account by right clicking the resources in the JSON Outline and selecting ‘Add new resource’.  Select the Storage account and name it. 




Once we click add the below JSON will be added to the WebSiteSQLDatabase.JSON. Make sure you provide the name of the storage account in lower case letter.


You are all set with the configurations to create a web application, an SQL Server, an SQL Database and Azure Storage Account. Will not take more than 2 minutes to create a solution with these configuration using visual studio. 

You can also get lots of pre-existing template that is already available in GitHub. You can download any template or refer them to create more resource such as redis cache, mongo db, spin up a new Linux virtual machine. 

You can now deploy the ARM to azure to create the specified resources. 





You will see the deploy to resource group window where we can Edit Parameters that can be configured for our ARM, which can also be saved to the WebSiteSQLDatabase.parameters.json




Once you click on the deploy button, you need to watch the output window because the visual studio does everything at the background while running Power-Shell script.


 

  You can see after couple of minutes when you login into azure you can see the new resource group that was created as all the specified resources created automatically




ARM helps to create scripts to automate the resource creation process in azure cloud so we can do automate testing, add new web application to the new client it can also deploy the code automatically to the cloud. You should really try this in azure since it is the coolest feature in azure.






               

Build Bot using LUIS