SOLID principles are key in object-oriented programming. But what does each principle actually mean, and why are they significant?
๐ฆ๐ข๐๐๐ ๐ฟ๐ฒ๐ฝ๐ฟ๐ฒ๐๐ฒ๐ป๐๐ ๐ณ๐ถ๐๐ฒ ๐ฝ๐ฟ๐ถ๐ป๐ฐ๐ถ๐ฝ๐น๐ฒ๐ ๐ผ๐ณ ๐ผ๐ฏ๐ท๐ฒ๐ฐ๐-๐ผ๐ฟ๐ถ๐ฒ๐ป๐๐ฒ๐ฑ ๐ฝ๐ฟ๐ผ๐ด๐ฟ๐ฎ๐บ๐บ๐ถ๐ป๐ด. Whether or not you use OOP, ๐ธ๐ป๐ผ๐๐ถ๐ป๐ด ๐๐ต๐ฒ๐๐ฒ ๐ฝ๐ฟ๐ถ๐ป๐ฐ๐ถ๐ฝ๐น๐ฒ๐ ๐ด๐ถ๐๐ฒ๐ ๐๐ผ๐ ๐ฎ ๐น๐ฒ๐ป๐ ๐ถ๐ป๐๐ผ ๐๐ต๐ฒ ๐ณ๐ผ๐๐ป๐ฑ๐ฎ๐๐ถ๐ผ๐ป๐ ๐ผ๐ณ ๐ฐ๐น๐ฒ๐ฎ๐ป ๐ฐ๐ผ๐ฑ๐ฒ which can be applied to many areas of programming.
๐ฆ โ Single Responsibility Principle
๐ข โ Open/Closed Principle
๐ โ Liskov Substitution Principle
๐ โ Interface Segregation Principle
๐ โ Dependency Inversion Principle
Letโs break down each principle โ
๐ญ. ๐ฆ๐ถ๐ป๐ด๐น๐ฒ ๐ฅ๐ฒ๐๐ฝ๐ผ๐ป๐๐ถ๐ฏ๐ถ๐น๐ถ๐๐ ๐ฃ๐ฟ๐ถ๐ป๐ฐ๐ถ๐ฝ๐น๐ฒ (๐ฆ๐ฅ๐ฃ)
Each unit of code should only have one job or responsibility. A unit can be a class, module, function, or component. This keeps code modular and removes the risk of tight coupling.
๐ฎ. ๐ข๐ฝ๐ฒ๐ป-๐๐น๐ผ๐๐ฒ๐ฑ ๐ฃ๐ฟ๐ถ๐ป๐ฐ๐ถ๐ฝ๐น๐ฒ (๐ข๐๐ฃ)
Units of code should be open for extension but closed for modification. You should be able to extend functionality with additional code rather than modifying existing ones. This principle can be applied to component-based systems such as a React frontend.
๐ฏ. ๐๐ถ๐๐ธ๐ผ๐ ๐ฆ๐๐ฏ๐๐๐ถ๐๐๐๐ถ๐ผ๐ป ๐ฃ๐ฟ๐ถ๐ป๐ฐ๐ถ๐ฝ๐น๐ฒ (๐๐ฆ๐ฃ)
You should be able to substitute objects a of base class with objects of its subclass without altering the โcorrectnessโ of the program.
An example of this is with a Bird base class. You might assume that it should have a โflyโ method. But what about the birds that canโt fly? Like a Penguin. In this example, having a โflyโ method in the Bird class would violate LSP.
๐ฐ. ๐๐ป๐๐ฒ๐ฟ๐ณ๐ฎ๐ฐ๐ฒ ๐ฆ๐ฒ๐ด๐ฟ๐ฒ๐ด๐ฎ๐๐ถ๐ผ๐ป ๐ฃ๐ฟ๐ถ๐ป๐ฐ๐ถ๐ฝ๐น๐ฒ (๐๐ฆ๐ฃ)
Provide multiple interfaces with specific responsibilities rather than a small set of general-purpose interfaces. Clients shouldnโt need to know about the methods & properties that don't relate to their use case.
Complexity โ
Code flexibility โ
๐ฑ. ๐๐ฒ๐ฝ๐ฒ๐ป๐ฑ๐ฒ๐ป๐ฐ๐ ๐๐ป๐๐ฒ๐ฟ๐๐ถ๐ผ๐ป ๐ฃ๐ฟ๐ถ๐ป๐ฐ๐ถ๐ฝ๐น๐ฒ (๐๐๐ฃ)
You should depend on abstractions, not on concrete classes. Use abstractions to decouple dependencies between different parts of the systems. Direct calls between units of code shouldnโt be done, instead interfaces or abstractions should be used.