Contact Me

Interface Segregation Principle

No code should be forced to depend on methods it does not use.

 The main sentence for the application of this principle should be: "many client-specific interfaces are better than one general-purpose interface.". In other words, it's better to have many small, specialized interfaces that a class can implement, rather than having one large, general-purpose interface that a class must implement. This principle helps to prevent unnecessary coupling between classes, making the code more flexible and easier to maintain.

 Let's say we have a class called Document that represents a document with text, images, and videos. In order to adhere to this principle, we would create separate interfaces for each of these features:

interface TextDocument {

getText(): string;

setText(text: string): void;

}

interface ImageDocument {

getImage(): string;

setImage(image: string): void;

}

interface VideoDocument {

getVideo(): string;

setVideo(video: string): void;

}

 Our Document class can then implement all three interfaces, providing the necessary functionality for each feature:

class Document implements TextDocument, ImageDocument, VideoDocument {

private text: string;

private image: string;

private video: string;


getText(): string {

  return this.text;

}

setText(text: string): void {

  this.text = text;

}

getImage(): string {

  return this.image;

}

setImage(image: string): void {

  this.image = image;

}

getVideo(): string {

  return this.video;

}

setVideo(video: string): void {

  this.video = video;

}

}

 This way, if a client only needs to work with text, it can use the TextDocument interface. If it only needs to work with images, it can use the ImageDocument interface. And if it needs to work with both text and images, it can use both interfaces. This allows for greater flexibility and reduces the chance of introducing unnecessary dependencies between classes.