args4j icon indicating copy to clipboard operation
args4j copied to clipboard

boolean option cannot have value

Open simon-zhou opened this issue 11 years ago • 3 comments

If I use the below code, I cannot pass "-v true" from command line since "true" will be parsed as an option but not a value for an option. This is largely due to the implementation of BooleanOptionHandler and NamedOptionDef. However, String option doesn't have this problem. Is this a bug or something by design? Cannot we make the two types consistent?

@Option(name = "-v", usage = "enable/disable validation mode")
private boolean validation = false;

simon-zhou avatar Jan 29 '14 00:01 simon-zhou

As to my understanding the idea behind boolean switch is that, if it is specified amonst the arguments, then it is set to true. Eg.

program -dosomething something -skipimport

in the above example, there's no point for me to write -skipimport true as it is already clear from the fact that I specified the parameter, that it is true (as it is false by default).

Whereas there may be cases, when you want user to explicitly specify behaviour of the program with the boolean key. For example you're importing data to database from text file and it is important to specify whether retries should be performed on error or not. In this case you may want to have an explicit parameter: -retryonfail

myimport -someparam someparam -retryonfail true

But to implement the above you need to have a string parameter which with the required flag.

@Option(name="-retryonfail", usage="specify true or false of whether you
want to retry database insertion if the first attempt fails.",
required=true)
private String retryOnFail;

And then you check whether retryOnFail equals "true" or `"false"``.

So the bottom line is that, you can accomplish many things with the combination of boolan or string parameters.

dimkir avatar Jan 29 '14 09:01 dimkir

Thanks dimkir for the quick response. Yes I can workaround that issue by using String and parse it to boolean in the code. So in args4j, we can only use boolean variable as a switch but not a key-value pair. I just expect consistent behaviors among all types (boolean, String, int, etc.). Anyway, thanks again.

simon-zhou avatar Jan 30 '14 01:01 simon-zhou

Or for the lazy ExplicitBooleanOptionHandler is also a way to go. Simply add handler = ExplicitBooleanOptionHandler.class to your @Option annotation.

MikeMatrix avatar Jan 30 '14 04:01 MikeMatrix