89. Packages and directory structure

Groovy is very forgiving and I can put all of my code files in a single directory, regardless of which package I say they’re in. This, however, is poor practice and I should create a directory structure that mirrors my package structure. In the last example I had two packages, mypackage and the sub-package mypackage/app and, when compiled, the following directory structure appeared:

mypackage/
├── Person.class
└── app
    └── Main.class

This structure reflects the one I should be using in my source:

mypackage
├── Person.groovy
└── app
    └── Main.groovy

Here’s the logic:

  1. Person.groovy is in the mypackage package so I create a mypackage directory and put Person.groovy in there
  2. Main.groovy is in the mypackage.app package:
    1. As app is a subpackage of mypackage so I should create an app subdirectory under mypackage and place Main.groovy there.

Once I’ve shuffled the files into the new structure I can compile them with:

groovyc -d classes mypackage/Person.groovy mypackage/app/Main.groovy

You’ll find the compiled class files in the classes directory (as set by the -d switch).

At this point you’re probably thinking that having to individually name all of the directories in a large codebase is going to be unwieldy and you’re absolutely correct. Once you get beyond a few files you’ll turn to a build system such as Gradle.