Alex Rivera | Logout

Are there best practices for (Java) package organization?

Asked 2010-07-12T06:20:05.267
233

A little while ago, I saw a question answered here regarding the fine-grained organization of Java packages. For example, my.project.util, my.project.factory, my.project.service, etc.

Are there best practices with regards to the organization of packages in Java and what goes in them?

How do you organize your classes in your Java project?

For instance, a project I'm working on with a few people has a package called beans. It started out being a project containing simple beans, but it has ended up (through poor experience and lack of time) containing everything (almost). I've cleaned them up a little, by putting some factory classes in a factory package (classes with static methods that create beans), but we have other classes that do business logic and others that do simple processing (not with business logic) like retrieving a message for a code from a properties file.

Edit
Report

1 Answer

200

Package organization or package structuring is usually a heated discussion. Below are some simple guidelines for package naming and structuring:

  • Follow Java package naming conventions
  • Structure your packages according to their functional role as well as their business role
    • Break down your packages according to their functionality or modules. e.g. com.company.product.modulea
    • Further break down could be based on layers in your software. But don't go overboard if you have only few classes in the package, then it makes sense to have everything in the package. e.g. com.company.product.module.web or com.company.product.module.util etc.
    • Avoid going overboard with structuring, IMO avoid separate packaging for exceptions, factories, etc. unless there's a pressing need.
  • If your project is small, keep it simple with few packages. e.g. com.company.product.model and com.company.product.util, etc.
  • Take a look at some of the popular open source projects out there on Apache projects. See how they use structuring, for various sized projects.
  • Also consider build and distribution when naming (allowing you to distribute your API or SDK in a different package, see the servlet API)

After a few experiments and trials, you should be able to come up with a structuring that you are comfortable with. Don't be fixated on one convention, be open to changes.

answered 2010-07-12T06:41:32.397

Your Answer