Monday, January 9, 2012

Command-line option argument processing in Java

If your program processes command-line options, then you have to write duplicative, boilerplate code and documentation:

  • to parse command-line options and set variables in your program,
  • for usage messages (such as printed by a --help option), and
  • for documentation in the program's manual and/or manpage.

It is a pain to write all this code.  Furthermore, it is easy for the different representations of data about command-line options to get out of sync, which leads to bugs and user confusion.

When you are writing in Java, a better approach is the Options class of plume-lib.  If you use the plume.Options class, you do not have to write any code, only declare and document variables.  For each field that you want to set from a command-line argument, you write Javadoc and an @Option annotation.  Then, field is is automatically set from a command-line option of the same name, and usage messages and printed documentation are generated automatically.

This class has been in daily use for well over five years and is slowly gaining adherents, but it still pains me when I see code that duplicates command-line logic and documentation.  This includes most other solutions I am aware of, including Apache Commons CLI.  It is, however, similar to args4j, which seems to have been independently conceived around the same time as this class.  Use whichever one you find more convenient and useful.

For full usage information, see the plume.Options documentation.