0% completed
In the previous lesson, we saw how a bloated Printer
interface violated the Interface Segregation Principle (ISP) by forcing classes to implement methods they didn’t need. To solve this, we will refactor the code to create smaller, more specific interfaces that only define the methods needed by each type of printer.
Step 1: Break the Large Interface into Smaller Interfaces
Instead of having a single large Printer
interface, we can split it into more focused interfaces. Each interface will represent a specific functionality, allowing classes to implement only what they need.
Now, we have four separate interfaces: Printer
for printing, Scanner
for scanning, Fax
for faxing, and Stapler
for stapling. This way, classes only need to implement the interfaces they require.
Step 2: Implementing BasicPrinter
Let’s refactor the BasicPrinter
class so it only implements the Printer
interface. Since the BasicPrinter
only needs to print documents, we no longer have to worry about unnecessary methods like scanning or faxing.
The BasicPrinter
class is now clean and focused. It doesn’t need to implement any methods it doesn’t use, which simplifies the code and avoids throwing exceptions for unsupported operations.
Step 3: Implementing AdvancedPrinter
For an AdvancedPrinter that supports all functionalities (printing, scanning, faxing, and stapling), we can implement multiple interfaces. This allows the class to inherit only the behaviors it needs, without being forced to implement everything from a single large interface.
The AdvancedPrinter now implements all the relevant interfaces (Printer
, Scanner
, Fax
, and Stapler
). This allows the class to handle each task while keeping the design clean and modular.
Step 4: Test the New Design
Here’s a quick test to see how the new design works with different types of printers.
Why This Follows ISP?
By restructuring the code:
- Smaller, Focused Interfaces: Each interface now represents a specific task (printing, scanning, faxing, or stapling). This allows classes to implement only what they need, following the Interface Segregation Principle.
- More Flexible Design: Classes like
BasicPrinter
only need to implement thePrinter
interface, avoiding unnecessary methods. Meanwhile,AdvancedPrinter
can implement multiple interfaces to support a range of functionalities. - Cleaner, Easier to Maintain Code: The code is easier to understand and maintain since each class focuses on the exact responsibilities it needs to fulfill.
.....
.....
.....
Table of Contents
Contents are not accessible
Contents are not accessible
Contents are not accessible
Contents are not accessible
Contents are not accessible