Wednesday, September 15, 2010

Designing Interfaces guidelines.

We all write interfaces when programming, these are the few rules that I found useful to keep in mind when designing and implementing interfaces.

1. Do not write interfaces for Model classes
Model like classes are classes like your DB model, or any other kind of class whoose primary function is to hold values. I usually do not write interfaces for these kind of classes for their main purpose is to hold values, and so let say you have Person class with getters and setters for Name and Address. And you have a interface call IPerson so you have getters and setters in the interface for IPerson. If you add a Telephone to Person, you need to add both the getters and setters to the IPerson. And it just goes on and on.

So far I haven really found a nice use case for implementing interfaces for simple value/model kind of classes.

2. Reduce your external dependecies
The reason you are writing interfaces is so that you can reduce the dependcies and change implementations if necessary. Consider the following

import org.internal.*
import org.external.NameValuePair

public interface HttpPost{
public void setPostParameters(NameValuePair[] pairs);
....
}

You are writing an interface to HttpPost and you have a method to add the post parameters. Your NameValuePair class actually comes from an external library. Now you have a dependency to that external library and you will need to package that every time you are using this interface.

I will try to keep this to a minimium, the reason why I write interfaces is to keep dependencies simple not to introduce new ones. So i might introduce a new class to break that dependency if needed or change the method signature to something like addPostParameter(String,String);

3. Keep your interfaces small and cohesive
Try not to have interfaces that does sort of everything, keep your interfaces small and cohesive (that means the methods in the interfaces are related to each other).

Bob martin in his article on the Interface Segregation Principle talks about using the Adapter pattern and multiple inheritance to join multiple interfaces together.

I like the line from Uncle Bob, "Clients should not be forced to depend on interfaces they do not use". Keep that as a rule when designing and implementing interfaces.

Martin Fowler Role Interface article also talks about this.

Interfaces are great for breaking up dependency and when use together with the Dependency Inversion principle you will have a easier time coping with changes to your software.

These are the book I recommend to improve your code.
Effective Java
Effective Java (2nd Edition)
Clean Code: A Handbook of Agile Software Craftsmanship

Clean Code: A Handbook of Agile Software Craftsmanship
Agile Software Development, Principles, Patterns, and Practices
Agile Software Development, Principles, Patterns, and Practices