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.
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.
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.
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.
Here’s a quick test to see how the new design works with different types of printers.
By restructuring the code:
BasicPrinter
only need to implement the Printer
interface, avoiding unnecessary methods. Meanwhile, AdvancedPrinter
can implement multiple interfaces to support a range of functionalities......
.....
.....