SOLID

SOLID stands for:

  • S - Single-responsibility Principle

  • O - Open-closed Principle

  • L - Liskov Substitution Principle

  • I - Interface Segregation Principle

  • D - Dependency Inversion Principle

Single-responsibility Principle (SRP): a class should have one and only one reason to change, meaning that a class should have only one job.

Example: (Container/presentational components in React)

Open-closed Principle (S.R.P.): objects or entities should be open for extension but closed for modification.

You should strive to write code that doesn’t have to be changed every time the requirements change.

Example: (don't hardcode something in React components, just let it be configured by props), (use the composition of small components instead of monolith JSX).

Liskov Substitution Principle: every subclass or derived class should be substitutable for their base or parent class.

The Liskov Substitution Principle means that you can inherit from a base class as long as you conform to the standards that it sets, such as having the same method name and parameters, you do not specify any deeper conditions that must be fulfilled, you return the same type that the base method does and that any Exception that is thrown must match the ones thrown by the base method.

Using TypeScript, we can easily swap objects and functions that share the same contract, without breaking the functionality of the application.

Example: (let's say we have a set of Error classes inherited from the base Error class, and we have a logger that log these errors, to follow this principle we should have the same interface for all the Errors to give the ability to the logger log any types of errors).

Interface segregation principle: a client should never be forced to implement an interface that it doesn’t use, or clients shouldn’t be forced to depend on methods they do not use.

This means that the methods of a large interface can be broken up into groups of methods. If a client does not need a method then the client should not know about the method / should not have to implement it.

Example: (Pass to the child component only the props required in this component instead of passing a full object from the upper level)

Dependency inversion principle: entities must depend on abstractions, not on concretions. It states that the high-level module must not depend on the low-level module, but they should depend on abstractions.

Example: (Container component has fetching logic and depend on 'fetch' function, we should invert dependencies to follow this principle, move fetch logic to the separate service and pass this service as a prop to the container, so that our container become independent on concrete implementation of 'fetch')

Last updated

Was this helpful?