The S.O.L.I.D Principle in JavaScript (P3)

Tram Ho

In this article, we will learn about the 4th principle of SOLID, which is the Interface Segregation principle through 2 sections:

  • What is the Interface Segregation Principle?
  • How to apply the Interface Segregation principle in JavaScript?

What is the Interface Segregation Principle?

Content:

A class should not be forced to implement methods it does not use. Multiple Interfaces with specific purposes are better than a general purpose Interface.

For example:

In the picture you can see we have the parent class Shape and 2 subclasses including Retangle and Line . Class Shape is inherited from Interface IDrawable . This interface has 2 methods: draw and calculateArea for drawing and calculating area. That means all subclasses will also have to have these two methods.

However, Line not 2-dimensional so it has no area. But it still needs to implement this approach. This is a violation of the principle.

OK, how to solve it now? You can see the draw and calculateArea are two methods with 2 different purposes, you should not combine them. The essence of the principle is to subdivide the Interface by purpose, so now we will add one more interface for the area calculation. That is IDrawable2D and this interface will apply to areas such as Shape . And IDrawable now has only one method, draw exactly with its name. Much more explicit, right?

How to apply the Interface Segregation principle in JavaScript?

JavaScript does not have an Interface. But you can understand the principle through this example

For example:

We have the User class and as you can see in the initialization it is always necessary to check validation. However, there are cases where you do not need a validate? So when there is no need to validate, but you still have to perform validate and violate this principle.

To handle this case is also quite simple, you just need to pass validate = true / false and then check the condition to check validation in the initialization. Thus, the parts that need to be checked and validated will be checked, and the parts that are not needed will be ignored.

This article is over, thank you for following the article. See you at the end.

Share the news now

Source : Viblo