How to structure packages?

Last Update: 08.06.2018. By Jens in Developers Life | Learning | Newsletter

  I was recently chatting with a reader and the topic of how to structure packages came up.

Basically, the traditional way is to structure by layer and each layer got its own subpackage. For the imaginary Evil Corp with their project doom it would look like: * com.evil.doom.model * com.evil.doom.service * com.evil.doom.controller * com.evil.doom.dao Perfectly reasonable. But it has some drawbacks. It encourages spaghetti code. Sooner or later your code will be entangled like hell inside each subpackage. It is not clear, where the boundaries of functionality is.

Another way of structuring your code would be to subpackage by business domain or use cases. So, if it a shop, we would have domains like products, order, cart, payment and so on. * com.evil.doom.products * com.evil.doom.order * com.evil.doom.payment * com.evil.doom.cart And inside those, you could use the classic service, model, controller approach or not, depending on how complex the part is. This makes it clearer while coding, that you enter a foreign domain. Technically nothing is preventing you from it, except maybe some package-visibility-only-modifiers. If you need to access a different domain, think twice why you are doing this and proceed with a contract between those. It really helps if you ever split that monolith into multiple services. Done consequently, it also saves you some headaches intertwined code brings with.

To add another mental barrier of doing the wrong thing, is to keep only public classes in the domains base package and move the rest into an internal. Seeing internal makes you think again.
However, it is only as good as the devs following it. If they don’t care, you will end up with a mess anyway :-)


Want content like this in your inbox each workday irregularly? No BS, spam or tricks... just useful content:

I understand and agree to the privacy policy