Can you give an example where the interface segregation principle helps make code more modular and extendable?
sobes.tech AI
Answer from AI
The Interface Segregation Principle helps avoid creating large, universal interfaces that force classes to implement methods they do not need. In Node.js, this is especially useful when designing modules and services.
For example, if you have an interface for working with different types of notifications:
interface NotificationService {
sendEmail(email: string, message: string): void;
sendSMS(phone: string, message: string): void;
sendPushNotification(deviceId: string, message: string): void;
}
If a class implements this interface but only needs to send emails, it is forced to implement the other methods, which is inconvenient.
By splitting the interface into smaller ones:
interface EmailSender {
sendEmail(email: string, message: string): void;
}
interface SMSSender {
sendSMS(phone: string, message: string): void;
}
interface PushSender {
sendPushNotification(deviceId: string, message: string): void;
}
Now, a class can implement only the needed interface, making the code more modular and easier to extend. When adding new notification types, there is no need to change existing interfaces and classes; just add a new interface and implementation.