DEV Community

Julie Cherner
Julie Cherner

Posted on • Edited on

Basic SOLID: must to do

SOLID principles are an essential base of software engineering because they give recommendations for projects on how to change and add new functionality without breaking existing code and creating bugs, save maintainability and easy understandable software.

SOLID principles are:

  • Single responsibility principle
  • Open/closed principle
  • Liskov substitution principle
  • Interface segregation principle
  • Dependency inversion principle

Using all 5 principles at the same time may be complicated (with good or bad consequences) and is not necessary for quality software, but there is an approach on how to deal with common software engineering problems.
These principles should be applied depending on the actual problem and situation.

Let’s start with an overview of each of 5 principles.

  • Single responsibility principle: 1 class - 1 aim With time, the complexity of class will grow dramatically and it will cause code redundancy, maintaining difficulties and as a result higher code breaks probability.

Write the class with the 1 only aim, for more - extend super class with subclass.

Avoid tight coupling!

Tight coupling is the state of a system where the components are highly dependent on each other. Better use loose coupling (state of a system where components are independent).

  • Open/close principle: add to class - yes, change - big no

Don’t change the class, add new functionality to it with subclass.

Stop breaking other parts of software that are dependent on the piece of code you change. If new functionality for your software, add it but don’t erase the existing versions.

  • Liskov substitution principle: while extending the super class, subclass behaves like parent class and does not alter superclass behavior

Similarities in behavior are:

  • Subclass takes the same parameters, returns the same, throws (or not) the same errors.
  • Subclasses don’t change (generally) conditions and results to save behavior predictable.
  • Always true conditions or relations of superclass must be preserved.
  • Subclass can’t change private fields of superclass.

Read more about Liskov substitution principle.

  • Interface segregation principle: tiny interface - yes!

Don’t add a lot of not necessary functionality in 1 class, break it in many ones.

  • Dependency inversion principle: high-level class depends on low-level class - no, low-level depends on abstraction - yes!

This way dependency “high-class -> low-level class” is changed to “high-level class -> abstract class <- low-level class”.

High level classes has high-level abstraction classes and low-lever classes depend on high-level abstraction class.

Top comments (0)