Ant: Building a Better Build File
From the developer who uses VIM or Emacs to the developer who uses a more complex IDE such as NetBeans, Eclipse, or IntelliJ's Idea, Jakarta's Ant has made their life much easier and more consistent. However, there does seem to be a growing trend to make build files that are overly complex and difficult to maintain. I doubt that anyone starts out writing a build file with the goal of making it un-maintainable, but as a project grows, the build tends to become more and more complex—often with multiple targets that do the same thing in a slightly different way. Listed in this article are a few ways to keep your build file lean, mean, and totally maintainable.
Although this may seem like old advice for a seasoned programmer, it bears repeating: Avoid having Ant targets that do more than one task unless it is logical for them to be combined. For instance, imagine a target that does the following:
- Removes old class files
- Compiles all source code
- Creates a Java archive of all class files
- Creates a Web archive of all files
- Copies the Web archive over to the development server
Although it is definitely a useful target, its scope is quite limited. Unless you want to always completely rebuild and redeploy the application you are working on, this target will not see very much use. Consider using several smaller targets with the following names instead:
With these targets, you can then assign dependencies as follows:
- jar depends on compile
- war depends on jar
- deploy depends on war
- all depends on clean and deploy
In this situation, there is a single target that does everything that the previous large target did by calling ant all. In fact, you can set this up as the default target; you can merely call ant to rebuild the entire project. But, more importantly, if you just want to recompile the class files you just modified to ensure that they compile, you can do that without having to deploy everything.
By keeping the targets small and simple, the build file becomes more flexible, useful, and easier to maintain.