Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 9

Interface Segregation Principle in C#

Recommended resources

In our last session, we explored the Liskov Substitution Principle (LSP), which ensures that a subclass can replace its base class without causing errors. This principle is vital for making polymorphism work reliably. However, LSP's effectiveness depends on having well-defined abstractions to begin with. If a base class or interface is poorly designed, it becomes nearly impossible for derived classes to substitute it correctly.

This brings us to the "I" in SOLID: the Interface Segregation Principle (ISP). This lesson will show you how to design lean, focused interfaces that prevent the very problems LSP warns against. Your goal is to be able to explain ISP and demonstrate its application with a C# code example, a common task in technical interviews for roles like the one you're targeting.

1. What is the Interface Segregation Principle?

The Interface Segregation Principle is formally stated as:

Clients should not be forced to depend on methods they do not use.

In simpler terms, it's better to have many small, specific interfaces than one large, general-purpose one. An interface that has too many methods covering unrelated functionalities is often called a "fat" or "polluted" interface. When a class implements a fat interface, it is forced to provide implementations for methods it doesn't actually need, leading to bloated code, confusion, and often, violations of other principles like LSP.

This short video provides a very clear initial example of this problem and its solution.

What is Interface Segregation Principle ?

This video from the Interview Happy channel introduces ISP with a simple and effective analogy.

First, watch the definition and the initial problem setup with an IVehicle interface that includes both Drive and Fly methods in this segment. Notice how the Car class is forced to implement a Fly method it doesn't use. Then, watch the solution, where the single large interface is segregated into two smaller ones, IDrive and IFly. This allows the Car and FlyingCar classes to implement only the functionalities relevant to them.

The key takeaway is that forcing a class to implement an irrelevant method is a design flaw. This often results in empty method bodies or, worse, throwing a NotImplementedException, which is a red flag we discussed in our lesson on LSP.


2. A Practical C# Example: The "Fat" Printer Interface

Let's ground this concept in a more detailed C# example that is very common in discussions of ISP. Imagine you're designing a system to handle various office devices. You might start by creating a single interface for all printer-related tasks.

Interface Segregation Principle Examples in C# - Dot Net Tutorials

This article from Dot Net Tutorials provides an excellent, step-by-step walkthrough of an ISP violation and its correction.

First, read the definition of ISP in the section What is ISP?. Next, move to the section Example to Understand. This introduces the scenario with a single fat interface, IPrinterTasks. Finally, read the section Example Without ISP, which shows the C# code for the fat interface and two implementing classes: HPLaserJetPrinter (an all-in-one device) and LiquidInkjetPrinter (a simple printer). Pay close attention to the LiquidInkjetPrinter.cs code; notice that it is forced to implement Fax and PrintDuplex even though it doesn't support those features.

As you read, you can see the problem clearly: LiquidInkjetPrinter is polluted with methods it has no use for. This makes the class harder to understand and maintain. If a developer sees a Fax() method on an object of this class, they might mistakenly assume it can fax. The interface is making a false promise on behalf of the class.


3. The Solution: Segregating the Interface

The solution, according to ISP, is to break the "fat" interface down into smaller, more cohesive interfaces based on roles or capabilities.

This diagram illustrates the core concept of ISP. The design on the left violates ISP by forcing a 2D `Square` to implement a `volume()` method. The design on the right adheres to ISP by segregating the `volume()` method into a separate `3DShape` interface, which is only implemented by relevant classes like `Cylinder`.

Applying this to our printer example, we can split IPrinterTasks into several smaller interfaces. Each one represents a distinct capability: printing, faxing, or duplex printing.

This C# code shows the result of applying ISP. The original large interface has been split into three smaller, role-specific interfaces: `IPrinterTasks`, `IFaxTasks`, and `IPrintDuplexTasks`.

Now, let's see how this refactoring solves the problem for our classes.

Interface Segregation Principle Examples in C# - Dot Net Tutorials

Continue with the same article from Dot Net Tutorials.

Read the section "Example using Interface Segregation Principle in C#". This section shows how the single IPrinterTasks interface is broken down and how the HPLaserJetPrinter and LiquidInkjetPrinter classes are modified. The HPLaserJetPrinter now implements all three interfaces, while the LiquidInkjetPrinter only implements the one it needs (IPrinterTasks).

By segregating the interface, we achieve a much cleaner design:

  • High Cohesion: Each interface now has a single, well-defined responsibility (e.g., IFaxTasks is only about faxing).
  • Low Coupling: The LiquidInkjetPrinter class is no longer coupled to the contracts for faxing or duplex printing. If you were to change the IFaxTasks interface, you would not need to recompile or even re-test the LiquidInkjetPrinter class.
  • Clarity and Intent: The design is self-documenting. When a class implements IPrinterTasks and IFaxTasks, it clearly communicates its capabilities.

4. How to Explain ISP in an Interview

Your extensive background in software development gives you a great platform to provide a nuanced answer. Here is a recommended structure for your interview response:

  1. Start with the Definition: "The Interface Segregation Principle states that no client should be forced to depend on methods that it doesn't use. It advocates for creating multiple, smaller, cohesive interfaces over a single, large 'fat' interface."

  2. Explain the Core Problem (The "Why"): "The problem with fat interfaces is that they force implementing classes to provide code for methods they don't need. This often leads to empty method bodies or throwing a NotImplementedException, which is a code smell and a violation of the Liskov Substitution Principle. It also creates unnecessary coupling; a change to one part of the interface can force changes in classes that don't even use that part."

  3. Provide a C# Example: "A classic example is a multi-function office device. You might be tempted to create a single IWorker interface with methods like Print(), Scan(), and Fax(). If you have an advanced device, that's fine. But if you have a simple, low-cost printer that can only print, it would still be forced to implement Scan() and Fax(). This is misleading and brittle."

  4. Describe the Solution using ISP: "To fix this using ISP, I would segregate that fat interface into smaller, role-based interfaces: IPrinter, IScanner, and IFaxer. The simple printer class would then only implement IPrinter. The multi-function device would implement all three. This design is much cleaner, more flexible, and each class only implements what it can actually do."

This answer shows you not only know the definition but also understand the negative consequences of violating ISP and can articulate a practical solution in C#.


Conclusion

The Interface Segregation Principle is a crucial guideline for creating clean, modular, and maintainable object-oriented systems. By designing small, cohesive interfaces, you make your code easier to implement, less coupled, and more explicit about its capabilities. This directly supports the Liskov Substitution Principle by reducing the likelihood that a class will need to provide a "dummy" implementation for an interface method.

Key Takeaways:

  • Prefer small, cohesive interfaces over large, multi-purpose ones.
  • "Fat" interfaces force classes to implement methods they don't use, leading to unnecessary coupling and confusing code.
  • Violating ISP often leads to violations of LSP (e.g., by throwing NotImplementedException).
  • Applying ISP leads to a more modular, flexible, and self-documenting design.

We have now covered how to define (ISP) and implement (LSP) abstractions correctly. The final piece of the SOLID puzzle is understanding how different parts of our application should depend on these abstractions. In our next lesson, we will cover the Dependency Inversion Principle (DIP), which will set the stage for understanding dependency injection—a cornerstone of modern frameworks like ASP.NET Core.