Home > Articles > Programming > Java

  • Print
  • + Share This
Like this article? We recommend

Keep Environmental Variables Out

A frequent problem that I see in Ant build files is hard-coded file locations or path information. This invariably leads to problems because not all developers on a team have all the files in the same location (or even use the same operating system). Thus, each developer keeps his own "version" of the build file, making it harder to maintain. A single change to the master build file can have disastrous effects.

To avoid this problem, it is best to keep all environment-specific variables out of the build file itself. This of course leads to the following question: How do I tell the build file where everything is and where to put things?

The question has two answers. One solution is to use environmental variables. Just like specifying JAVA_HOME and ANT_HOME, other environmental variables can be set and used inside the build file. Specifying CATALINA_HOME instead of hard-coding tomcat's location can make the build file a lot cleaner and more robust. Setting JBOSS_HOME or even a LIBRARY_HOME in the environmental variables and then using those variables inside of the build file to point to libraries can remove a lot of inconsistencies between developer machines. If this route is chosen, place the following tag in the ant build file. It can access all your environmental variables by appending "env" to the name of the variable:

<property environment="env"/>

For instance, if you have JBOSS_HOME defined as an environmental variable, it is easy to reference it as ${env.JBOSS_HOME}.

The second option is to use a user-specific properties file along with the Ant build file by using a properties file with simple name value pairs and then loading it dynamically into the build file at run time to eliminate all environment-specific variables. Ant even has a function built into it to load a properties file. Using this function along with the variable ${user.name} (also built into Ant) allows the build file to look for a user-specific properties file to find all its file locations.

In keeping with the other suggestions noted previously, when you add variables to the build file, make sure that their variable names make sense and are easy to understand. Naming the variable JBOSS_HOME instead of JBOSS lets the other developers know that the variable points to the root of the JBoss installation—not to one of its numerous library directories.

  • + Share This
  • 🔖 Save To Your Account