I had previously written a post related to coupling and cohesion here and that was more of a basic definition of both the terms.
In this post I would like to throw some light on the tight dependency on the type of the component in use. Generally we would aim to design classes such that they interact via the interfaces or more generally put via API. Suppose we use interfaces (more of a generic term where we dont have implementations, not specific to keyword interface in Java or C#), but this is not enough, we need to provide some kind of implementation for the interface which is actually consumed by the other client classes.
Liskov Substitution principle (LSP) states that,
Methods that use references to the base classes must be able to use the objects of the derived classes without knowing it
This principle was written by Barbara Liskov in 1988.
The idea here is that the subtypes must be replaceable for the super type references without affecting the program execution.
This principle is very closely related to Open Closed Principle(OCP), violation of LSP in turn violates the OCP. Let me explain:
Open Closed Principle (OCP) states that,
Software entities (Classes, modules, functions) should be OPEN for EXTENSION, CLOSED for MODIFICATION.
Lets try to reflect on the above statement- software entities once written shouldn’t be modified to add new functionality, instead one has to extend the same to add new functionality. In otherwords you don’t touch the existing modules thereby not disturbing the existing functionality, instead you extend the modules to implement the new requirement. So your code is less rigid and fragile and also extensible.
OCP term was coined by Bertnard Meyer.
How can we confirm to OCP principle?
Its simple- Allow the modules (classes) to depend on the abstractions, there by new features can be added by creating new extensions of these abstractions.
The Single Responsibility principle (SRP) states that:
There should never be more than one reason for a class to change.
We can relate the “reason to change” to “the responsibility of the class”. So each responsibility would be an axis for change. This principle is similar to designing classes which are highly cohesive. So the idea is to design a class which has one responsibility or in otherwords caters to implementing a functionality . I would like to clarify here that one responsibility doesnt mean that the class has only ONE method. A responsibility can be implemented by means of different methods in the class.
In the previous post here, I had introduced few concepts related to constructors in Scala. In this post I would go a bit deeper into the constructors and how we can provide different constructors. Summarizing about the introduction in the previous post here–