Skip to content

Modularising argument definitions

Martin "Marrow" Rowlinson edited this page Sep 14, 2017 · 1 revision

If you don't want to clutter up your static main(String[] args) with the definitions of your applications argument definitions, simply create a class that extends the ArgumentDefinitions class, e.g.

package com.mycompany.myapplication;

import com.adeptions.clarguments.*;
import com.adeptions.clarguments.definitions.*;

public class ApplicationArgumentDefinitions extends ArgumentDefinitions {
    // expose the names so the caller can use them to refer to found arguments...
    public static final String ARG_NAME_FOO = "foo";
    public static final String ARG_NAME_BAR = "bar";
    public static final String ARG_NAME_HELP = "help";

    public ApplicationArgumentDefinitions() {
        super(
                new StringArgumentDefinition(ARG_NAME_FOO, "Some string argument"),
                new FlagArgumentDefinition(ARG_NAME_BAR, "Some flag argument"),
                new InformationalArgumentDefinition(new String[] {ARG_NAME_HELP, "h", "?"}, "Display this help")
        );
    }
}

and your static main(String[] args) can be a whole lot cleaner, e.g.

package com.mycompany.myapplication;

import com.adeptions.clarguments.*;
import static com.mycompany.myapplication.ApplicationArgumentDefinitions.*;

public class Application {
    public static void main(String[] args) throws BadArgException {
        // define arguments...
        ApplicationArgumentDefinitions argumentDefinitions = new ApplicationArgumentDefinitions();

        // parse args...
        Arguments arguments = argumentDefinitions.parseArgs(args);

        if (!arguments.anythingSeen() || arguments.get(ARG_NAME_HELP).isSpecified()) {
            // the user didn't specify any args or asked for help...
            System.out.println("My application accepts the following arguments:-");
            System.out.println(argumentDefinitions.getHelp());
        } else if (arguments.hasParsingExceptions()) {
            // there were some problems with the args...
            for (BadArgException badArgException: arguments.getParsingExceptions()) {
                System.err.println(badArgException.getMessage());
            }
        } else {
            // run the actual application...
            System.out.println(ARG_NAME_FOO + " specified as: '" + arguments.get(ARG_NAME_FOO).getValue() + "'");
            System.out.println(ARG_NAME_BAR + " was specified? " + (arguments.get(ARG_NAME_BAR).isSpecified() ? "Yes" : "No"));
        }
    }
}