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).

No comments:

Post a Comment

Note: only a member of this blog may post a comment.

Build Bot using LUIS