November 6, 2006

...Learn TDD with Codemanship

Interface Segregation Question

I've had a question posted on the Yahoo! group about the Interface Segregation design principle. The questioner asks:

in the customer class some clients need to know the id only and the
others need to only convert the customer class into XML, so you have
created two interface for IBusiness interface for ID and IXML for
getting the XML

I need to get the XML for the customer class.

i did this

Customer objCustomer=new Customer();

((IXML)objCustomer.getXML());

what difference it make when i have a method like getXML() in
Customer Class

and Call directly objCustomer.getXML();


It's a fair question. Why bother to seperate out methods into two interfaces if we only end up binding directly to the class that implements both of them? And it's true that some object somewhere has to decide what concrete class to instantiate, so some class somewhere is coupled to the Customer interface.

Design principles are mostly about managing dependencies, though, and the critical question is which class makes the decision to create an instance of Customer? Certainly, in the code example above we don't necessarily need to explicitly create an instance of Customer if the object is, for example, being passed as an argument to a method. This allows us to create code that only depends on the minimum set of methods it requires to do its job. In the above example, it might look a little like this:

public void serialize(IXml xmlObject) {

xmlObject.getXml();

}


(People who know me well might spot a fond tribute to an old friend hidden somewhere in that code).

Most OO design patterns rely on this mechanism of deferring decisions about which concrete classes to instantiate to other objects, effectively decoupling them and encouraging the right kind of dependencies (dependencies on abstractions).
Posted 14 years, 2 months ago on November 6, 2006