Understanding the SOLID Principles

Understanding the SOLID Principles

In a section on the book “Ace the Programming Interview: 160 Questions and Answers for Success”, Edward Guiness talks about a set of practices to have simple and efficient code: The SOLID Principles. The acronym stands for: 

  • Single Responsibility Principle
  • Open/Closed Principle
  • Liskov Substitution Principle
  • Interface Segregation Principle
  • Dependency Inversion Principle

The Single Responsibility Principle (SRP) states that each class should have one and exactly one responsibility. Only experience and practice will help you determine what one responsibility envolves,

The Open/Closed Principle (OCP) says that each class should be open for extension, but closed for modification. When adding new behavior, we should leave the base class alone and instead create new inheriting classes, and avoid unexpected consequences for the original subclasses.

The Liskov Substitution Principle (LSP) says that the less inheritance we have in our code the better and if we are going to inherit functions they should stay the way they are. Overriding a function often creates problems in our code.

The Interface Segregation Principle (ISP) says that instead of having one interface with a lot of methods we should create a lot of interfaces with very few methods each. This is the same way of thinking for the Single Responsibility Principle, applied to interfaces.

Finally, the Dependency Inversion Principle (DIP) says that if one of our classes creates an object of another class somewhere, then it is better to write an interface and refer to it in its code. Giving different classes the implementation of this new interface gives the chance of our class to handle different objects.

In summary, the main purpose of the principles is to minimize dependency. The less dependent our classes, methods, functions and code is to some other code, the better. This way we can understand it better, change only the things we want to change when we need it and preserve its functionality.

Comments

Popular posts from this blog

Moon Machines

Hidden Figures