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:
-
Person.groovyis in themypackagepackage so I create amypackagedirectory and putPerson.groovyin there -
Main.groovyis in themypackage.apppackage:- As
appis a subpackage ofmypackageso I should create anappsubdirectory undermypackageand placeMain.groovythere.
- As
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.