Understanding the SOLID Principles

The following blog entry will explain the SOLID Principles based on the book Ace the programming interview: 160 questions and answers for success. 

SOLID stands for 5 widely accepted principles of object-oriented programming and design, these are the Single Responsibility Principle, Open/Closed Principle, Liskov Substitution Principle, Interface Segregation Principle, Dependency Inversion Principle. These principles will be explained through this entry. 

- Single Responsibility Principle: This principle says that a class should have only one responsibility. It should have only a reason or a class of reasons that cause it to change. This principle might cause a problem for programmers because deciding what a single responsibility means can be a difficulty. A single responsibility refers to a group of related business processes or it could be broken down in its constituent parts, with each part designated as a responsibility.

- Open/Closed Principle: This principle says that a class or function should be open for extension but closed for modification, attempts that object-oriented code becomes fragile or easily broken when base classes are modified in ways that break the behavior of inheriting classes. This means that adding new behavior you should leave base classes alone and create a new one, inheriting classes, adding behavior to these instead of the base class, and thereby avoiding the problem of unintended consequences for classes that inherit from the same base class.

- Liskov Substitution Principle: This principle is similar to the OCP principle, it implies that you should avoid modifying the behavior of a base class, but it also forbids the modification of that behavior through inheritance. So, if type S inherits from type T, then T and S should be interchangeable in functions that expect T. If the LSP is followed, there should be no problem when substituting a child class in a function that expects to deal with the base class. 

- Interface Segregation Principle: This principle says to avoid writing big interfaces that might cause classes to have responsibilities that they don't need or want. This principle says that it is needed to create a collection of smaller, discrete interfaces, partitioning interface members depending on what they need. Small interfaces mean implement those needed parts. 

- Dependency Inversion Principle: This principle stands in a sentence "depend upon abstraction, not concretions", so, this principle says that instead of writing code that refers to actual classes, you should actually write code that refers to interfaces or abstract classes. 


References: 

Guiness, E. (2013). Ace the programming interview: 160 questions and answers for success. (pp.121-126) Indianapolis, IN: WILEY.

Comentarios

Entradas más populares de este blog

Microservices

Ethical Reflection on Ready Player One