Quality Coding Practice
Before design patterns there are some principles followed by conventional programmers.This series of blogs will guide you if you don't know about it or if you are aware of it, then this is just to brush up on these best practices.
I strived to do it as narrative based to avoid rather boring theoretic examples. I think you will enjoy it while you are gaining knowledge by reading those stories. All examples here are my own examples in order to be very simple to understand even for the novice developer.
SOLID Principle
S.O.L.I.D. abbreviation means,
S -> Single Responsibility,
O -> Open Close principle
L -> Liskov Substitution principle
I -> Interface segregation principle
D -> Dependency inversion principle.
Let's discuss each concept in detail.
Single Responsibility Principle (SRP)
This is the most basic principle among these five principles. As the name implies this means one class does only one responsibility (in other words, class has one reason to change). If many responsibilities are executed by that class just delegate that to other classes.
The advantage of it is that you can understand code very cleanly and then you can reuse methods among the applications.
If you Google SRP then you will come up with a lot of sources, but it all seems to be a bit harder to understand for novices since this theory most of the time is used with enterprise level complex applications (great architecture design perspective).
I think before that first of all we have to thoroughly understand the principle and based on that we can add more paradigms of that principle in applications.
I am striving to give you a basic example of it and to try to elaborate to make it much understandable. I have cornered the example only to highlight the main concept.
OK here we go ..
It's better to understand it with SRP and without SRP.
I have a basic console calculator :)
(I am highlighting again, the following code is very basic to understand the SRP)
- class Program {
- static void Main(string[] args) {
- try {
- Console.WriteLine("Enter No 1 :");
- var no1 = Console.ReadLine();
- Console.WriteLine("Enter No 2 :");
- var no2 = Console.ReadLine();
- Console.WriteLine("Enter operator :");
- var operation = Console.ReadLine();
- switch (operation) {
- case "+":
- Console.WriteLine("your result is {0}:", Convert.ToDouble(no1) + Convert.ToDouble(no2));
- break;
- case "-":
- Console.WriteLine("your result is {0}:", Convert.ToDouble(no1) - Convert.ToDouble(no2));
- break;
- default:
- break;
- }
- Console.ReadKey();
- } catch (Exception) {
-
- throw;
- }
- }
- }
Wow nice... but if you show it to a professional developer he will turn this code upside down.
He ill say: "you have put lot of responsibilities in one class ... dude it's hard to maintain ..bla bla ..".
Oops what is it...?
And this is how it should have tbeen written without breaking SRP.
"You seem to be implementing a calculator eh?? So why can't you create a class for it and make it that responsibility rather than put all responsibilities to program class and ask program class to fulfill parameters and show them the result?"
"ah ..then if you have a problem with calculator then the only one reason is to change the calculator rather than the whole class in Program ..."
- class Program {
- static void Main(string[] args) {
- Console.WriteLine("Enter No 1 :");
- var no1 = Console.ReadLine();
- Console.WriteLine("Enter No 2 :");
- var no2 = Console.ReadLine();
- Console.WriteLine("Enter operator :");
- var operation = Console.ReadLine();
- Console.WriteLine("Result:{0}", Calculator.MathOperation(no1, no2, operation));
- Console.ReadKey();
- }
- }
- public static class Calculator {
- public static double MathOperation(string no1, string no2, string operatorMark) {
- try {
- double result = 0;
- switch (operatorMark) {
- case "+":
- result = Convert.ToDouble(no1) + Convert.ToDouble(no2);
- break;
- case "-":
- result = Convert.ToDouble(no1) - Convert.ToDouble(no2);
- break;
- default:
- break;
- }
- return result;
- } catch (Exception) {
- throw;
- }
- }
- }
Now our Calculator class will do all calculation related things, not like in previous Program class. If you want to change the calculation logic do it in Calculator class only not the Program class, do one class and do a single responsibility and do it well.This is basically about SRP.
In practically if you wish to add error logging to the calculator then you have to make new class(ExceptionLoggerClass) to it and from the catch statement you call it, that also makes it the SRP way.
Open Close Principle (OCP)
Open Close abbreviation mean open to extend and close for modification.
It is more vital to understand the concept behind this for more maintainable code designing.
It is quite hard to understand the concept without an example so let start the journey with examples,
Suppose we need to create a small calculator(special one) witch calculates cubic volume.
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- namespace Volum_OpenClose {
- class Program {
- static void Main(string[] args) {
- double oneSideLenght;
- Console.WriteLine("Enter one side lenght :");
- oneSideLenght = Convert.ToDouble(Console.ReadLine());
- double volum = CalculateVolum(oneSideLenght);
- Console.WriteLine("The volume is : {0}", volum.ToString());
- Console.ReadKey();
- }
- public static double CalculateVolum(double oneSideLength) {
- return oneSideLength * oneSideLength * oneSideLength;
- }
- }
- }
Once I sell my calculator to the client then he demands: "Hey, Dude I only bought your calculator so it could calculate the volume of the cylinder."
Hummm OK, I will change my code
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- namespace Volum_OpenClose {
- class Program {
- static void Main(string[] args) {
- string ShapeType;
- Console.WriteLine("Enter type :");
- ShapeType = Console.ReadLine();
- dynamic operand = null;
- if (ShapeType == "cubic") {
- Console.WriteLine("Enter one side lenght :");
- double oneSideLenght = Convert.ToDouble(Console.ReadLine());
- operand = new Tuple < string, double > (ShapeType, oneSideLenght);
- } else if (ShapeType == "cylinder") {
- Console.WriteLine("Enter radius :");
- double radius = Convert.ToDouble(Console.ReadLine());
- Console.WriteLine("Enter height :");
- double hieght = Convert.ToDouble(Console.ReadLine());
- operand = new Tuple < string, double, double > (ShapeType, radius, hieght);
- }
- double volum = CalculateVolum(operand);
- Console.WriteLine("The volume is : {0}", volum.ToString());
- Console.ReadKey();
- }
- public static double CalculateVolum(dynamic operandValue) {
- double volume = 0;
- string shapeType = operandValue.Item1;
- if (shapeType == "cubic") {
- double oneSide = Convert.ToDouble(operandValue.Item2);
- volume = oneSide * oneSide * oneSide;
- } else if (shapeType == "cylinder") {
- double radius = Convert.ToDouble(operandValue.Item2);
- double height = Convert.ToDouble(operandValue.Item3);
- volume = height * Math.PI * radius * radius;
- }
- return volume;
- }
- }
- }
before I have to sell it to the customer I ask my lead to review my code ...
Lead: "Oh no what have you written..?"
Me: :( :( :( feeling sad ...."why what's wrong with this ???"
Lead :"You need to change a whole lot of code once again.The customer has asked for another shape don't you know the Open Close principle?? Don't you know that you have changed the existing behavior of the code ?"
Me :"What is it? How can I write it for any shape of calculation without changing the code? I wonder how it works?"
Lead:"Yes you are correct we do need to change it, there is no magic, but we have to do the changes with minimum breaks of existing code and a maximum way to extend it for future potential occurrences."
Here it's obvious we must support different shapes, let's do the code refactoring
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- namespace Volum_OpenClose {
- class Program {
- static void Main(string[] args) {
- var shape = new object() as Shape;
- var objectType = string.Empty;
- Console.WriteLine("Please enter type of object");
- objectType = Console.ReadLine();
- if (objectType == "Cube") {
- shape = new Cube();
- }
- if (objectType == "Cylinder") {
- shape = new Cylinder();
- }
- InitializeParameters(shape);
- PrintCalculation(shape);
-
- Console.ReadKey();
- }
- private static void PrintCalculation(Shape shape) {
- Console.WriteLine("Volume of your shape is : {0 }", shape.calculateVolume());
- }
- public static void InitializeParameters(Shape generalShape) {
- generalShape.InitializeParameters();
- }
- }
- public abstract class Shape {
- public dynamic Operand;
- public string Operation {
- get;
- set;
- }
- public abstract void InitializeParameters();
- public abstract double calculateVolume();
- }
- public class Cube: Shape {
- public override double calculateVolume() {
- return Operand * Operand * Operand;
- }
- public override void InitializeParameters() {
- Console.WriteLine("Please enter one side lenght :");
- Operand = Convert.ToDouble(Console.ReadLine());
- }
- }
- public class Cylinder: Shape {
- public override double calculateVolume() {
- return Operand[1] * Math.PI * Operand[0] * Operand[0];
- }
- public override void InitializeParameters() {
- Operand = new double[2];
- Console.WriteLine("Please enter radius:");
- Operand[0] = Convert.ToDouble(Console.ReadLine());
- Console.WriteLine("Please enter height:");
- Operand[1] = Convert.ToDouble(Console.ReadLine());
- }
- }
- }
Now you see there is no need to change the existing code each time you introduce new shapes; just add that class and only creation logic changes. Others remain the same so there is no need to retest your code, just test the newly introduced separate classes."
The next time the client asks for different calculations see how easy it is ....:D:D
Liskov substitution Principle (LSP)
Let's dive into the next pillar of solid design principles.
Linkov substitution principle is a very high level state in which the pattern that derived class uses should be substituted by it' base class.
If you have googled the LSP, you will come up with square and rectangle examples.
I'm fed up with this conventional example aren't you??
Let's talk about it in a simple, out-of-the-box way. Suppose I have a simple class called "SingleClass" and I implement it like this,
- public class SingleClass {
- int _Value1;
- int _Value2;
- public virtual void setValue1(int a) {
- _Value1 = a;
- }
- public virtual int getValue1() {
- return _Value1;
- }
- public virtual void setValue2(int a) {
- _Value2 = a;
- }
- public virtual int getValue2() {
- return _Value2;
- }
- public virtual int Sum() {
- return _Value1 + _Value2;
- }
- }
- cool..even kid can understand is 't it ?
- I have call to my derived class as follows,
- public class LiskovDoubleClass: SingleClass {
- public override void setValue1(int a) {
- base.setValue2(2 * a);
- }
- public override void setValue2(int a) {
- base.setValue2(2 * a);
- }
- public override int Sum() {
- return (base.getValue1() + base.getValue2());
- }
- }
In my main method(clients) utilize LiskovDoubleClass as follows
- LiskovDoubleClass doubleClassRefactored = new LiskovDoubleClass();
- doubleClassRefactored.setValue1( 4);
- doubleClassRefactored.setValue2(5);
- var childConditionRefactored = doubleClassRefactored.getValue1() + doubleClassRefactored.getValue2() == doubleClassRefactored.Sum();
Now according to LSK,the child class should have to be substituted by its base class without any trouble,
Ok I will substitute my LiskovDouble class with it base class called SingleClass
- SingleClass singleClass = new SingleClass();
- singleClass.setValue1(4);
- singleClass.setValue2( 5);
var parentCondition = singleClass.getValue1() + singleClass.getValue2() == singleClass.Sum();
WOW the base class successfully replaced with it derived class (just scope to client)
In order to understand it better think about the following scenario,
- public class DoubleClass: SingleClass {
- public virtual int Sum() {
- return 2 * (getValue1() + getValue2());
- }
- }
my consumer
- DoubleClass doubleClass = new DoubleClass();
- doubleClass.setValue1(4);
- doubleClass.setValue2(5);
- var childCondition = 2*(doubleClass.getValue1() + doubleClass.getValue2()) == doubleClass.Sum();
- SingleClass singleClass = new SingleClass();
- singleClass.setValue1(4);
- singleClass.setValue2( 5);
-
- var parentCondition = 2*(singleClass.getValue1() + singleClass.getValue2()) == singleClass.Sum();
Interface segregation principle (ISP)
Ok lets talk about a very very important concept called "Interface segregation principle"
As the name implies, interface segregation means interface should not be a fat big interface, it should have to be segregated into thin interfaces where we can decouple greatly.
Suppose we have calculator functionalities as follows,
- public interface ICalculatorOperation
- {
- double Add(double a,double b);
- double Substract(double a, double b);
- double Multiply(double a, double b);
- double Divide(double a, double b);
- }
Then my calculator is implemented as follows,
- public class Calculator: ICalculatorOperation {
- public double Add(double a, double b) {
- throw new NotImplementedException();
- }
- public double Divide(double a, double b) {
- throw new NotImplementedException();
- }
- public double Multiply(double a, double b) {
- throw new NotImplementedException();
- }
- public double Substract(double a, double b) {
- throw new NotImplementedException();
- }
- }
Suppose I am selling this calculator to the clients ..WOW great business is't it ?
Now I'm going to market this software to a client who is a measuring guy .
He says he will buy my calculator if it has the functionality of calculating the area of a circle.
(I suggest you can calculate this by pi R in to R )
Then that guy is not satisfied with my answer.
OK I come to my development team and tell the story ...
I pressure the development team to do it ASSP :( :(
Then because of high pressure from me, after all they have implemented an area calculation included with my previous calculator as follows,
- public interface ICalculatorOperation {
- double Add(double a, double b);
- double Substract(double a, double b);
- double Multiply(double a, double b);
- double Divide(double a, double b);
- double AreaOfCircle(double r);
- }
- public class Calculator: ICalculatorOperation {
- public double Add(double a, double b) {
- throw new NotImplementedException();
- }
- public double AreaOfCircle(double r) {
- throw new NotImplementedException();
- }
- public double Divide(double a, double b) {
- throw new NotImplementedException();
- }
- public double Multiply(double a, double b) {
- throw new NotImplementedException();
- }
- public double Substract(double a, double b) {
- throw new NotImplementedException();
- }
I show it to my area measuring guy to sell the sofware and he is happy with the new feature.
But ....
when my conventional client comes to buy my software I ask for money for my new feature which they do not want to pay. I say you should have to buy that one too I can't give it you a free new feature ... :(:(.
Not only that, because of adding a new feature some problem occurred and then my previous client also complains that I broke the system.
So after figuring out that something went wrong with the software design, I hire a software consultant....
Then they drill down the problem and give me the solution as follows.
- public interface ICalculatorOperation {
- double Add(double a, double b);
- double Substract(double a, double b);
- double Multiply(double a, double b);
- double Divide(double a, double b);
- double AreaOfCircle(double r);
- }
This interface has tightly coupled the components and we need to segregate them
- public interface IArithmaticCalculator {
- double Add(double a, double b);
- double Substract(double a, double b);
- double Multiply(double a, double b);
- double Divide(double a, double b);
- }
- public interface IAreaCalculator {
- double AreaOfCircle(double r);
- }
- public class AreaCalculator: IAreaCalculator {
- public double AreaOfCircle(double r) {
- throw new NotImplementedException();
- }
- }
- public class ArithmaticCalculator: IArithmaticCalculator {
- public double Add(double a, double b) {
- throw new NotImplementedException();
- }
- public double Divide(double a, double b) {
- throw new NotImplementedException();
- }
- public double Multiply(double a, double b) {
- throw new NotImplementedException();
- }
- public double Substract(double a, double b) {
- throw new NotImplementedException();
- }
- }
- public class FullCalculator: IArithmaticCalculator, IAreaCalculator {
- public double Add(double a, double b) {
- throw new NotImplementedException();
- }
- public double AreaOfCircle(double r) {
- throw new NotImplementedException();
- }
- public double Divide(double a, double b) {
- throw new NotImplementedException();
- }
- public double Multiply(double a, double b) {
- throw new NotImplementedException();
- }
- public double Substract(double a, double b) {
- throw new NotImplementedException();
- }
- }
Wow. Now the problem is solved ..
Dependency Inversion Principle (DIP)
Theoretically Dependency Inversion Principle states that,
Higher level module should not depend upon lower level module. They should depend via abstraction.
Abstraction should not depend on details, details should depends on abstraction.
It's a little bit tricky, isn't it?
As we have seen in other principles, this principle's intention is also to decouple the classes and modules.
OK let's try to understand it with examples.
Suppose there are two companies which are giving hiring facilities to customers.
There is a hotel which consumes the service of the hiring facility.
Let's see it as follows through a simple implementation,
Some company gives a vehicle which has superb facilities such as beds for resting. Here is the implementation of it.
- public class SuperLuxuryVehicle {
- private int NoOfBeds {
- get;
- set;
- }
- private int IntererVoltage {
- get;
- set;
- }
- public double RentalPerDay() {
-
- throw new NotImplementedException();
- }
- }
Suppose some other small car rents their vehicles where HotelXYZ gets hired.
- public class BudgetVehicle {
- private int NoOfSeat {
- get;
- set;
- }
- private double Milage {
- get;
- set;
- }
- public double RentalPerDay() {
-
- throw new NotImplementedException();
- }
- }
The hotel uses the above two (consumer class) vehicles for their customers and calculates the bill according to car type.
- public class HotelXYZ {
- SuperLuxuryVehicle _slv;
- BudgetVehicle _bv;
- public HotelXYZ() {
- _slv = new SuperLuxuryVehicle();
- _bv = new BudgetVehicle();
- }
- public double generateClientBill() {
-
- throw new NotImplementedException();
- }
- }
As you can see here, their two hiring classes are tightly coupled with the HotelXYZ high level class.
(hint : If there are many "new" keywords it indicates bad practices where tightly coupled code was introduced.)
If the hiring company (low level classes) changes the logic, it will directly effect the HotelXYZ high level class, so it is violating the DIP.
OK let's see how we can overcome it by introducing DIP.
- public interface IHireService {
- double RentalPerDay();
- }
- public class SuperLuxuryVehicle: IHireService {
- private int NoOfBeds {
- get;
- set;
- }
- private int IntererVoltage {
- get;
- set;
- }
- public double RentalPerDay() {
-
- throw new NotImplementedException();
- }
- }
- public class BudgetVehicle: IHireService {
- private int NoOfSeat {
- get;
- set;
- }
- private double Milage {
- get;
- set;
- }
- public double RentalPerDay() {
-
- throw new NotImplementedException();
- }
- }
- public class HotelXYZ {
- IHireService hireService;
- public HotelXYZ() {
-
- }
- public double generateClientBill() {
- hireService.RentalPerDay();
- hireService.RentalPerDay();
-
- throw new NotImplementedException();
- }
- }
Now both high level class and low level class interact with the abstraction, not the class definitions, which is the so called dependency inversion principle.
DRY
When we think about quality coding we must know the following practice too.(Don't get confused with SOLID where my topic is about quality coding.)
Ooops what is DRY ??
Many of you may already be aware what dry in coding is, if you are not, this is for you to merge with the other codes.
The DRY abbreviation means Do not Repeat Yourself.
As the name implies this simply means your code must not repeat the same logic many times.
Then you might think about why it is so important as a principle?
If you're writing a simple code in a project then it is trivial to come as principle.
But in enterprise level applications peoples are writing thousands of millions of lines of code in the project so in such a case if you are writing the same logic just copy and paste the code then think about if a newcomer wants to do some change of the behavior of some method, then that guy suffers the pain of it to find everywhere he needs to apply same change.
But if you only use that method in one place and other places you just reuse it, then you are minimizing the lines of coding with what you are writing (minimum coding means minimum unit test ..and minimum maintainability) then if that new comer comes to change the behavior of that method that guy needs not to worry about every occurrence of change just simply do the change in once place and be happy.
Other benefit of it is you seamlessly test your reusable code many times then that method is more robust.
Another thing is if you are changing a highly reused code then if you change such a method incorrectly then the impact of that change gives your application a massive blow.
Thanks for your valuable time for reading this article, and if you can give feedback on this I appreciate it. I hope the next time you code you stay dry ... :)