Java Package Organisation

No Cycles

If a package B contains classes that are dependant on package A (directly, or indirectly: B -> C -> A) then package A must not have classes that are dependant on package B (directly or indirectly)

This makes the code easier to read/understand. It also makes it more testable, as you have definite levels and can test the bottom level of packages then the next level etc etc

This can mean that if cycles exist they may have to be broken by creating an interface in package A or in a package before package A that is then implemented by package B.

Parent depends on Child packages

A class in a top level package may depend on sub packages. (ok: A.MyClass1 imports A.B.MyClass2) A class in a sub package may not depend on a class in the parent package (not ok: A.B.MyClass2 imports A.MyClass1)

This rule is arbitrary, but it helps readability if you choose either parent packages rely on sub packages only or sub packages rely on parent packages only

Package A.X.Y may depend on package A.D and/or A.D.E

Clean

Keep around 10 or less classes per package.

The number of classes in a package depends on the complexity/simplicity/regularity of the package.

A package that contains sub packages should contain a small number classes.

Stucture

<com.company>.<application-suite>.<application>.<section>.<component>.<subcompnent>...

Where

  1. com.company - the domain name of the organisation
  2. application-suite - an optional collection of related applications/services
  3. application - name of application, may build into a war, jar
  4. section - a forced high level struture for all applications for example: It can be more convenient to have this organisation at the component/subcomponent level, but this can result in harder to catch dependancies (e.g. facade components being dependant on model components in other parts of the application)
  5. component - logical component of application.
  6. subcomponent - one or more logical subcomponents. The depth of subcomponents (i.e subsubcomponents etc) depends on the complexity of the component/subcomponent

Components and subcomponents make up most of the package structure. Organisation should be around components in the system. For example a simple event system component might define an Event interface for event listeners to implement and some class to hold a set of events. Classes that implement the event interface should probably be with the component/subcomponent interested in recieving the event - not in the event package

The facade is separated at the top level of the package hierachy to allow the compilation process to control the packages and classes the facade uses, especially to avoid dependancies on other packages in the same project

Facade, IOC, delegate