Search This Blog


Packages: A Tool to Organize Classes

One of these days I was taking to a work colleague about what should be the package (a.k.a. Namespace) of a certain class. Not rare there is a small debate about it. Should the class WorkerRiskActivity belong to the Health package or to the Activity package ? And so on ....

Although it may sound a useless discussion it has been proven ( at least to our organization ) that this kind of worry is healthy specially in the long term.

I can enumerate the following advantages in using good packages for classes:

  • It breaks the complexity of hundreds of classes in blocs composed by few classes just like folders for files.

  • It gives a clue for developer about what is the role of this class in the system.
The fully qualified nameFinance.Sevices.DebtManagement tell you what the class actually does.

  • It organizes the logic architecture of your software. This is specially useful for layered architecture where the classes are organized according to the class role.
Organizing classes can also be confusing. In order to avoid wrong classification, the following anti-patterns are listed below:

  • Packages with vagues names
One of the traps that should be avoided is to create packages with too vague names such as General, Etc or Miscellaneous. This names are going to be used by lazy developers to place classes they don't want to think about how to classify to the right package.

  • Too much debate about packages

In the other hand, organizing classes in packages should not give rise to a long debate. If a class was placed in the wrong package, a code refactoring can solve the problem later.
  • Package-by-layer
Although it can sound perfectly reasonable to have classes organized by layer. Actually this kind of packages can be harmful since it is no more possible determine what kind of permission a specific package can have since this package actually has all kinds of classes from varying parts of your system that don't relate to each other. The preferred way to use packages is to organize them by feature as it can be seen in all examples listed in this post. In fact this is not a "personal way" of modeling packages, this is the original purpose of a package.
Thus the package Finance has all classes that compounds a financial application including its UI layer, services and the problem domain classes.