Command line parsing

Jonathan M Davis via Digitalmars-d digitalmars-d at puremagic.com
Tue May 17 17:48:38 PDT 2016


On Monday, May 02, 2016 08:52:42 Andrei Alexandrescu via Digitalmars-d wrote:
> I found this in https://peter.bourgon.org/go-best-practices-2016/:
>
> "I said it in 2014 but I think it’s important enough to say again:
> define and parse your flags in func main. Only func main has the right
> to decide the flags that will be available to the user. If your library
> code wants to parameterize its behavior, those parameters should be part
> of type constructors. Moving configuration to package globals has the
> illusion of convenience, but it’s a false economy: doing so breaks code
> modularity, makes it more difficult for developers or future maintainers
> to understand dependency relationships, and makes writing independent,
> parallelizable tests much more difficult."
>
> This is interesting because it's what std.getopt does but the opposite
> of what GFLAGS (http://gflags.github.io/gflags/) does. GFLAGS allows any
> module in a project to define flags. I was thinking of adding
> GFLAGS-like capabilities to std.getopt but looks like there's no need
> to... thoughts?

My only issues with std.getopt have been its default settings (in particular
that bundling is not turned on by default when in *nix-land at least,
bundling is the norm) and the fact that it's a bit hard to handle errors
from it. When it throws, you tend to just know that something failed on not
what or why, but some improvements have been made to it with regards to
printing help and whatnot, and presumably, further improvements could be
made.

I've never personally felt the need to add options/flags separately from
main, but I've also never dealt with a framework that handled main for me
such that I wasn't in control of the code to handle the command-line
arguments in the first place. And certainly, my initial reaction is that
being able to inject additional command-line argument handling elsewhere in
the program is a bad idea and that if there is a framework that handles main
for you such that you aren't dealing with the command-line argument handling
directly, then it should provide a way for you to hook into the command-line
argument handling rather than just letting it be injected willy-nilly.
GFLAGS just seems like a bad idea to me. It might make sense in some
circumstances, but I'm inclined to think that such circumstances aren't
normal enough or common enough to warrant being explicitly supported in the
standard library.

- Jonathan M Davis




More information about the Digitalmars-d mailing list