10

How do you decide what a package name should be and what class should go into what package ?

I'm working on a project where I am constantly adding/removing classes and not really sure if I need a new package, or should add it to an existing one that im not currently aware of.

Do you follow a set of rules when creating a new package ?

How do you know if you are not duplicating package functionality ? Is this just down to familiarity with the project.

Any pointers appreciated.

blue-sky
  • 51,962
  • 152
  • 427
  • 752
  • @Alex K: I don't think it's duplicated. The question you point is about how packages work in Java while this question is about how to define packages more effectively. – helios Sep 22 '11 at 13:40

3 Answers3

15

I strongly discourage from organizing packages from an implementational point of view, like controllers, data, etc. I prefer grouping them by functionality, that is, feature1, feature2, etc. If a feature is reasonably complex and requires a large number of classes, then (and only then) I create subpackages like above, that is, feature1.controllers, feature1.data, etc.

michael667
  • 3,241
  • 24
  • 32
  • 2
    The benefit of the approach michael667 is describing, IMO, is that it makes logging configuration much easier. If I want to see everything related to automobiles I can just configure logging in the automobile package, for example – IcedDante Oct 02 '15 at 13:53
12

Classes should do one thing (Single Responsibility Principle).

Classes that do related things should go in the same package. If you find you can more closely relate some of the classes in a package, make them a subpackage!

For example, if I had a project with these classes:

  • GreetingInputWindow
  • GreetingDatabaseObject
  • GreetingDatabaseConnector

I might just put them all in the greeting package. If I wanted to, I might put GreetingInputWindow in the greeting.ui package, and the other 2 into the greeting.db package.

jefflunt
  • 33,527
  • 7
  • 88
  • 126
Josh Pordon
  • 289
  • 1
  • 9
2

I don't believe there are any hard and fast rules on packaging convention (though I could be wrong). Normally I break it up into

com.mycompanyname and then:

  • api
  • controllers
  • data (for models)
  • jobs (for cron jobs)
  • reporting
  • servlet
  • utils

If I find I have a class which does not fit into any of those, then I create a new package.

Gerard
  • 4,818
  • 5
  • 51
  • 80
  • Yeah, I use something similar. I find this keeps the code organised but some seem to think this isn't very good practice. – W.K.S Jun 05 '13 at 16:33