Interface Segregation Principle
Definition Clients should not be forced to depend on methods they do not use. Prefer small, cohesive interfaces to “fat” interfaces. ISP helps you resolve the problem with LSP violations. www.seavus.com
Motivational poster
Motivational poster
Interfaces Why interfaces exist? Who owns the interfaces? Who defines the interfaces? Should we think about interfaces in terms of the concrete classes that implement those interfaces? www.seavus.com
Interfaces The purpose of the interfaces in the first place is to introduce loose coupling. It’s not really the concrete class that needs the interface – it’s the client that needs the interface. The client owns the interface! The client defines what it needs! www.seavus.com
Example 1
Problems ReadOnlyStream needs to provide implementation of the write() method, even though it does not require them. This is a violation of the Interface Segregation Principle. Violation of the Interface Segregation Principle also leads to violation of the complementary Open Closed Principle. For example, consider that the Stream interface is modified to include a new method. As a result, you now need to modify all existing Stream implementation classes to include the new method even if they do not need it. www.seavus.com
Following the Interface Segregation Principle
Example 2 Both clients HAVE A CustomerTransaction object Both clients don’t required all of the methods from CustomerTransaction www.seavus.com
Example 2 www.seavus.com
So, what’s the problem? www.seavus.com
Problems Changes in the CustomerTransaction class could result in recompilation and redeployment of both of this dependent client modules. For example, if we update method: chargeCustomer( String arg ), TransactionReportGenerator will be forced to recompile and redeploy although it doesn’t use this method. www.seavus.com
Solution www.seavus.com
Demo www.seavus.com
When to fix ISP Once there is pain If there is no pain, there’s no problem to address If you find yourself depending on a “fat” interface you own Create a smaller interfaces with just what you need Have the fat interface implement your new interface Reference the new interface with your code If you find “fat” interfaces are problematic but you do not own them Create a smaller interface with just what you need Implement this interface using an Adapter that implements the full interface (adapter would be between you and the third party interface that you don’t have control over) www.seavus.com
ISP tips Keep interfaces small, cohesive and focused (refactor large interfaces so they inherit smaller interfaces) Whenever possible, let the client define the interface (don’t force client code to depend on things it doesn’t need) www.seavus.com
Thank you for your attention Copyright: © 2019 Seavus. All rights reserved. | www.seavus.com | info@seavus.com | sales@seavus.com