Tuesday, December 3, 2019

Clean code practices with S.O.L.I.D. Principles

Writing code is the thing which most of software engineers do on daily basis but only few of them write clean code i.e. a code that is easy to understand, manage, scale and amend. Those people who write clean code are the most sought after developers and also the ones who has least number of production issues.

While there are many techniques of writing clean code but the most famous one is following S.O.L.I.D principles. It basically has 5 principles:
  • Single Responsibility Principle
  • Open/Closed Principle
  • Liskov Substitution Principle
  • Interface Segregation Principle
  • Dependency Inversion principle
We will try to learn more about these principles with the use of code examples from Python. Read through each of the below principles.

1. Single responsibility principle       “…You had one job” 
            — Loki to Skurge in Thor: Ragnarok

A class should have only one job.  If a class has more than one responsibility, it becomes coupled.  A change to one responsibility results to modification of the other responsibility.


2. Open/Closed principle
      Software entities (Classes, modules, functions) should be open for extension, not modification.


3. Liskov Substitution Principle
         A sub-class must be substitutable for its super-class.  The aim of this principle is to ascertain that a sub-class can assume the place of its super-class without errors.  If the code finds itself checking the type of class then, it must have violated this principle.


4. Interface Segregation Principle
         Make fine grained interfaces that are client specific clients should not be forced to depend upon interfaces that they do not use.  This principle deals with the disadvantages of implementing big interfaces.


5. Dependency Inversion Principle
         Dependency should be on abstractions not concretions
            A. High-level modules should not depend upon low-level modules. Both should depend upon abstractions.
            B. Abstractions should not depend on details. Details should depend upon abstractions.

There comes a point in software development where our app will be largely composed of modules.  When this happens, we have to clear things up by using dependency injection.  High-level components depending on low-level components to function.

No comments:

Post a Comment