CSC/ECE 517 Fall 2007/wiki3 4 s2

From Expertiza_Wiki
Jump to navigation Jump to search

Interface Segregation principle

The Interface Segregation principle states that

"Clients should not be forced to depend upon interfaces that they do not use."[1]

Several other definitions are possible:[2]

  • "Many client specific interfaces are better than one general purpose interface"
  • "The dependency of one class to another one should depend on the smallest possible interface"
  • "Make fine grained interfaces that are client specific."


Each of these definitions point to the same thing. A desire to avoid "fat" interfaces. "Fat" interfaces are interfaces whose methods can be divided into more than one group.

This is very similar to another object-oriented principle, "A class should only do one thing and do it well."

Any interface, therefore, should be as small as possible for the required functionality and many small interfaces are favored over fewer larger interfaces. Clients are likely to change the requirements of a system over time. If the same interface is shared among multiple client, you will quickly run into a situation where a client's code contains functionality the he or she has no use for. In addition to making the client carry unnecessary code, this also creates the potential for conflicts within the code.


Example: Online Bookseller

An excellent example of why "fat" interfaces should be avoided is provided by DoodleProject:

Recall the on-line bookseller system introduced in the Open-Closed Principle and referred to in the Dependency Inversion Principle. Now the company wants to start offering music CDs for sale through its website. To accommodate this, the search engine portion of the website will need to be modified. Trying to reuse as much code as possible, the SearchEngine and Query types are amended to accept CD searching queries. The resulting class diagram is:

To satisfy the requirements of CD searching, the Query interface was forced to handle both BookServletQuery and CDServletQuery functionality. In the future, if there is any change to the searching functionality of CDServletQuery, then that change will be forced onto the Query interface. Furthermore, any change to Query forces a change to all of its implementers, including BookServletQuery. This scenario, a change in the CD query portion of the website forces a change (and possible bugs) in the book query portion of the website, makes the software very fragile. To fix this BookServletQuery and CDServletQuery must be implemented from separate interfaces. This can easily be accomplished by adding some additional abstract types to the design that are more specific in their tasks. The new class diagram is:

With this design, the two functional concerns have been separated. Now, if CDServletQuery needs new searching functionality, the change is forced upon CDQuery but can not propagate to the book query portion of the design.