Are there best practices for (Java) package organization?

Cyntech picture Cyntech · Jul 12, 2010 · Viewed 132.9k times · Source

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.

I can't find it now, so I may as well ask the question.

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 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.

Your thoughts and comments are appreciated.

Answer

onof picture onof · Jul 12, 2010

I organize packages by feature, not by patterns or implementation roles. I think packages like:

  • beans
  • factories
  • collections

are wrong.

I prefer, for example:

  • orders
  • store
  • reports

so I can hide implementation details through package visibility. Factory of orders should be in the orders package so details about how to create an order are hidden.