user4824732
user4824732

Reputation: 15

Should I parse input arguments in main class or elsewhere?

I have a class containing the main method and I've been wondering if I should parse input arguments and check if they're correct in main or in an object to which i pass those arguments. What makes classes more reusable?

Upvotes: 0

Views: 388

Answers (1)

nanofarad
nanofarad

Reputation: 41281

Ideally, you will want to make clean, modular code. Imagine if one day you decide you need to take arguments from somewhere other than the command-line.

A good way to go about this is with an interface, ArgumentParser, that the rest of your code can use (for example, by passing an instance implementing that interface to whatever parts of your code need to read arguments). Include methods like hasSwitch for args like --foo and getValue for ones like --foo=bar.

If you ever need to get arguments from a different location (e.g. interactive user prompts, config file, etc), it is as simple as changing a few lines of code to instantiate a different kind of argument parser.

Arguments should be checked at two points:

  • Syntactical validity of the config file/command line/etc should be done by the parser itself. If it cannot parse the args, then the rest of the program has no business trying to use those arguments. The parsing is usually specific to the kind of representation, since args at a command line will be fomatted differently than settings in a config file.
  • Semantic validity of the arguments should be done in the part of the program that actually acts upon those arguments. Say a module takes a number from 0-10. You only need to add this check once inside that module, as opposed to in every parser. Additionally, if one day you update the module and it can now work with numbers up to 20, you only have one point that is already logically related to the module itself, where you will need to change the validity check.

Upvotes: 1

Related Questions