Declared Type

One of the features of Java and other pessimistically typed languages is the need to declare the types of your variables. Since you have to declare the type, you may as well use the declared type as an opportunity to communicate. Pick the declared type that communicates how the variable is to be used, not how it is implemented.

List<Person> members = new ArrayList<Person>() tells me that members is to be used like a List. I expect to see operations invoked like get() and set(), since what sets List apart from Collection is indexed access to elements.

When I was first drafting this pattern, I wrote it dogmatically. Then I tried the rigid rule that all variables should be declared as generally as possibly. What I found was that the extra effort to generalize all types was not worth it. Sometimes a variable would be a List. Then I would pass it to a method where only Collection protocol was used. The inconsistency between the declarations was a bigger problem for readers than the lack of precision in just declaring it as a List everywhere it was used. Now I would say it more gently. It is useful to declare variables and methods with a general type where possible. Losing a little precision and generality to maintain consistency is a reasonable trade-off.

The best thing about generalizing declared types is that it opens up options for changing the concrete classes during later modifications. If I declare a variable as an ArrayList, I can’t easily change it later to a HashSet the way I could if I declared it as a Collection. In general, the further a decision propagates, the less flexibility you have for future change. To maintain flexibility, allow as little information as possible to spread as narrowly as possible. There is more information in the statement “members contains an ArrayList” than in the statement “members contains a Collection”.

Focusing on communication is a good heuristic for maintaining flexibility. Declared types are an example of this. When I say that a variable holds a Collection, I am speaking precisely. Communicating well provides the best flexibility.

Implementation Patterns

contents