SOLID Principles in programming
If you follow, these principles you can improve the reliability of your code by working on its structure and its logical consistency.
The SOLID principles are:
- The Single-Responsibility Principle (SRP)
- The Open-Closed Principle (OCP)
- The Liskov Substitution Principle (LSP)
- The Interface Segregation Principle (ISP)
- The Dependency inversion Principle (DIP)
In other words, every component of your code (in general a class, but also a function) should have one and only one responsibility. As a consequence of that, there should be only a reason to change it.
Too often you see a piece of code that takes care of an entire process all at once. I.e., A function that loads data, modifies and, plots them, all before returning its result.
2) The Open–closed principle (OCP)
You should need to modify the code you have already written to accommodate new functionality, but simple add what you now need.
This does not mean that you cannot change your code when the code premises needs to be modified, but that if you need to add new functions similar to the one present, you should not require to change other parts of the code.
3) The Liskov substitution principle (LSP)
Alternatively, this can be expressed as “Derived classes must be substitutable for their base classes”.
In (maybe) simpler words, if a subclass redefines a function also present in the parent class, a client-user should not be noticing any difference in behaviour, and it is a substitute for the base class.
For example, if you are using a function and your colleague change the base class, you should not notice any difference in the function that you are using.
Among all the SOLID principle, this is the most abstruse to understand and to explain.
4) The Interface Segregation Principle (ISP)
In the contest of classes, an interface is considered, all the methods and properties “exposed”, thus, everything that a user can interact with that belongs to that class.
In this sense, the IS principles tell us that a class should only have the interface needed (SRP) and avoid methods that won’t work or that have no reason to be part of that class.
This problem arises, primarily, when, a subclass inherits methods from a base class that it does not need.
5) The Dependency Inversion Principle (DIP)
So, that abstractions (e.g., the interface, as seen above) should not be dependent on low-level methods but both should depend on a third interface.
To better explain this concept, I prefer to think of a sort of information flow.
Imagine that you have a program that takes in input a specific set of info (a file, a format, etc) and you wrote a script to process it.
What would happen if that info were subject to changes?
You would have to rewrite your script and adjust the new format. Losing the retro compatibility with the older files.
However, you could solve this by creating a third abstraction that takes the info as input and passes it to the others.
Comments
Post a Comment