Solid Principles

My perspective on solid principles part-1

Solid Principles

As the title says this article is all about "Solid Principles" and how they moved me as a developer. Let me give you an acronym about solid here

  • S - Single responsibility principle

  • O - Open-closed principle.

  • L - Liskov substitution principle.

  • I - Interface segregation principle.

  • D - Dependency inversion principle.

So growing up as a developer I use to love Java a lot because learning objects, constructors, inheritence, and interfaces they really made me feel as i am a freaking developer !!

But using them precisely to develop any software meaning your code should be more readable and maintainable makes the difference between developer and a good developer is what I realized when I got to know about solid principles.

So let me share my perspective on how I saw this Topic :

I wanted to create a software for Birds. where i can store the details of every single bird. Created a class called Bird with some attributes like name, size weight, color etc.. also added methods such as makeSound(), eat(), and fly().

created the first bird which is a sparrow(Bird sparrow =new Bird()), But when make sound method is called the makeSound() might look something like this:

makeSoud(){
    if(name=='sparrow'){
        System.out.println("sound of sparrow");
    }
    eles if(name=='crow'){
        System.out.println("sound of crow");
    }
    else if(name=='eagle'){
        System.out.println("sound of eagle");
    }
    else{
        ...
        }
}

If you observe here the make sound method is violating the SRP which is the single responsibility principle. By performing two operations here checking the bird and printing the sound.

Not only SRP it also violates the OCP( Open-Closed principle) as well.

This means if I wanted to add a new bird to my software I need to make a change in the existing code which is not a good practice. OCP says that the code should be open for extension and closed for modification.

Then I decided to make a separate class for each kind of bird and declare the Bird class as an abstract class.

These subclasses here will override the makeSound() method with their respective implementation.

With this I am achieving SRP(Single responsibility principle) and OCP (Open-closed principle) that is makeSound method is having only one responsibility and whenever I want to add a new bird I can just go with creating a class ensuring extensibility and close for modification of any old code.

But there is a catch here some birds don't fly so overriding fly method in Penguin class is not correct to overcome this we need to use interfaces which we will discuss in the next part, till then keep learning and enjoy programming... bye.