visit
Hello guys, this is the fourth part of SOLID Principles in JavaScript and if you haven't read the previous three (first part, second part and third part), I highly recommend reading them first and coming back here.
"I" - Interface Segregation Principle. This principle says: clients should not be forced to depend upon interfaces that they do not use.
What does it mean?This principle says about the interface, but as we know, we don't have interfaces in Javascript. But, in Javascript we have something similar to them, it's classes. Of course, it's not the same, but this principle could be applied to JS classes. So, if we speak about classes, this principle means that when we create a base class, we should declare all methods that will be used in subclasses and try to avoid methods, that some subclass will use, but some another subclass shouldn't use.Let's take an example. Let's create a base class for transports with the next methods: move, stop, fly and sail. For this example, methods will contain just
console.log
, but of course, in real life, it will be real business logic.You maybe noticed, that in each subclass we rewrite inherited methods and put
return null
. Let's speak about why. Think about the plane. The plane can fly, can move, but the plane can't sail.Our base class contains logic for the sail method and of course Plane can't sail. We should do something because someone could call this method at a plane instance. We can throw an error or rewrite this method as it is now.The same with the other two classes, car, and ship. Car can't fly and sail. The ship can't fly.So, the problem is we created in base class methods, that some subclass can use, but others can't. . This is what the interface Segregation Principle says. We, shouldn't create logic in a base class, which shouldn't be in a subclass. Of course, it isn't relative to polymorphism. If we should prepare a common method, but each child should rewrite logic, it's ok. Just for example:If we have an Animal base class, which can breathe and we have subclasses, who also can breathe, but in a different way, we use polymorphism and it's ok: