88. Naming your packages

If all Groovy and Java programmers just relied on the default package or mypackage it’d be almost impossible to share code as it’s extremely likely more than one Person class would be created. The package naming convention helps to avoid this and there are two key elements to remember:

  1. Package names are written in lower-case to avoid clashing with elements such as class names.
  2. It is recommended that a reversed domain name is used as the base package name

The first point is straight-forward so let’s explore the second. If you or the company you work for own a domain name, you basically just reverse it and then prefix specific package names. For example, as I own the groovy-tutorial.org domain I should use:1

org.groovy_tutorial.mypackage

I would use org.groovy_tutorial as the basis and then start with a prefix that reflects a project or library name for which I’m developing (e.g. org.groovy_tutorial.shapes). If I didn’t own a domain I could have used the name of the site on which my code is hosted:

com.github.groovy_tutorial.shapes_demo

I’m not pretending to own github.com but I’ve also included the organisation name and project name to ensure uniqueness.

One final point to remember is that your chosen package name needs to be based on something that’s not likely to change and isn’t pinned to a single person. I’ve seen email addresses used (e.g. com.gmail.example) but this isn’t the best idea. Just take a moment before committing to a package name - you’ll thank yourself if the code is still going in five years.

  1. I’ve converted the hyphen (-) to an underscore (_) as package names can’t contain a hyphen (and domain names can’t contain an underscore).