Sunday, April 26, 2009

Class Names and Patterns

We could talk years and years about name conventions and design and don't arrive to a concrete solution. That's why you should only consider this post as a opinion and nothing more than that.

Names seems to be a serious problem for some developers. I worked with C++ several years and me and my fellows didn't talk about this topic too much, but now that I'm working with JAVA it seems that names are important!. One of the things I would like to talk today is about patterns and names. How do we call a class that is implementing a pattern?, for example, a Strategy class, should be called, for example, "calculationStrategy"?, as in everything related to design there are multiple opinions. Some people think that it is unnecessary because if a developer is reading your code he should know how a strategy pattern is implemented and is redundant to specify the implemented pattern in the class name. On the other hand, some people think it is right!, they consider that being redundant in this case is a benefit for the reader because it makes code easier to read. 

Before continue, we should also consider the difference between the pattern's intent and it's implementation. The most important thing when we need to analyse of a pattern is it's intent: what it is suppose to solve and what is useful for, we should decide whenever to implement a patter or not based on these intentions. The implementation is secondary, you could implement a pattern the way you want, there are different ways to code a pattern and achieving the same result. However, if you decide to use the implemented pattern's name in your class name try to make a standard implementation of it, it is a way to avoid readers confusions.

Let me show you some examples, 

An abstract factory is not a factory method. These patterns are quite similar but they are expected to do different things. The factory Method is similar to the abstract Factory without the emphasis on families. If you call a Factory Method as an abstract Factory you may leading to confusions. Consider the following,




If another developer reads "CarAbstractFactory", instead of expecting what I've showed before, he will be waiting to read something like:





Which is not the same. in this case you should reconsider the name of your class, and named it as "CarFactoryMethod" or "CarFactory".



Strategy is different from polymorphic. When you have to implement a strategy pattern consider that the class that is implementing the Strategy Pattern is injected to a client or Director. Something like this:



and not something like this:




What I'm trying to say with this examples is that you can use pattern names in your class names, but if you do it, be sure that the implementation of the pattern corresponds to the name of your class and it is implemented in a standard way so everyone can understand it without having problems.


No comments:

Post a Comment