INTERFACE SEGREGATION PRINCIPLE
No class should be dependent on methods it doesn't need. An example would be a "Machine" interface that forces the print() , scan() , and fax() methods. Not every machine has these 3 methods. So we create the IPrinter , IScanner , and IFax interfaces. Now a machine signs only the contracts it actually needs and fulfills only those. Code Example (Optional - Illustrating the text): // ❌…
The Interface Segregation Principle (ISP) asserts that a class should never be dependent on methods it does not use. To avoid a rigid interface with unnecessary methods, it recommends creating smaller, more specific interfaces. This concept ensures that a class only needs to implement the methods relevant to its purpose, thereby reducing code pollution and unnecessary coupling.
Consider a blog system where each user must sign a generic contract. This approach forces the implementation of methods that are irrelevant for regular users, such as writing posts or banning other users. Consequently, it leads to unnecessary coupling and code bloat.
The solution, in line with the ISP, is to divide the contract into smaller, well-scoped interfaces. For instance, instead of a single, bulky `IUserActions` interface, create separate interfaces for different functionalities, like `IReader`, `IWriter`, and `IAdmin`. This way, each user only needs to implement the specific interface(s) that match their role, leading to a more modular and maintainable system.
For example, a regular user would implement `IReader` and `IWriter` interfaces, while an admin would implement `IReader`, `IWriter`, and `IAdmin` interfaces. This approach allows changes to one contract (like the banning rules) without affecting other parts of the system, much like Lego blocks fitting together based on their specific purpose.
Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.