Understanding the SOLID Principles


Hi, this entry is going to talk about a section called “Understanding the SOLID principles” from the book “Ace the Programming Interview: 160 Questions and Answers for Success” by Wiley in 2013. Basically, the acronym SOLID is explained a round this book section. This acronym stands for five accepted principles about object-oriented programming and design:

1.     Single Responsibility Principle: It stays that a class should have just one responsibility. Despite the fact that this principle sounds easy, I found it a little bit complicated, because the explanation wasn’t direct and simplified. Also, the author mentioned that there might be cases in which a class might have two responsibilities. So, at the end, what exactly does this principle stands for?

2.     Open/Closed Principle: It stays that a class or a function should be open for extension but closed for modification. What does this mean? Our code must have the capability of being extended, but we have to always avoid modifying an existing method or class. I understand this principle, but I think that there could be situations in which modifying the code will result much simpler that extending it. Since its our code, we have to know what exactly does modifying it will affect other sections and be able to correct it, but also extending is fine to avoid that.

3.     Liskov Substitution Principle: It is intended to keep a happy working relationship between classes and functions alive and well. What is “happy working relationship”? An example is passing a new class to an existing function written to work with a base class, so that function will work as if you passed a base class’s instance. This principle is very clear, as the author said, we should avoid inheritance and instead use composition.

4.     Interface Segregation Principle: It stands that to avoid writing monstrous interfaces with a lot of methods, we should create a collection of smaller interfaces. This one is easy, we will end with a smaller and more organized code

5.     Dependency Inversion Principle: It stays that instead of writing code that refers to actual classes, we should write code referring to interfaces or even abstract classes. Basically, we are writing code easier to modify and with dependency injection. 


I was expecting simpler principles, but after reading them twice, I finally understood them. I think they’re very important for having a well-organized and much better code. We must follow them while doing object-oriented programming.

Comments

Popular posts from this blog

Hidden Figures

An Introduction to Metaprogramming

Microservices