3 ms·
In order of preference: 1) Command line parameters, particularly when an application is using getopt() or getopt_long(). Among other things, they make it easie
by wahern 8y ago
In order of preference:
1) Command line parameters, particularly when an application is using getopt() or getopt_long(). Among other things, they make it easier to test and debug an application. For example, daemonization and sandboxing should be controllable from the command-line, assuming the application has such logic. That said, use of nonstandard option syntax in the Go community, for example, is maddening.
2) Environment variables. Personally I usually support environment variables which mirror command lines option. For example, FOO_B or FOO_BAR might be equivalent to specifying a -b or --bar command line option.
3) Configuration file. But please don't make it necessary if at all possible.
If I'm writing an application supporting all 3, then the above ordering is also the precedence ordering. A command line option overrides an environment variable which overrides a configuration file setting.
Command line options are constraining because of the flat namespace and because they become unwieldy in large numbers. But that's a good thing. They force you to think critically about semantics and default behaviors, and to make meaningful choices.
Simple key-value configuration files, like JSON or YAML, are IMO the worst choice of all. They just become dumping grounds. If you're going to support a configuration file format, use an expressive, declarative syntax. An HN poster the other day said that systemd's ini file format was declarative. No, it's not! The abstract configuration of systemd is declarative, but systemd's configuration syntax is anything but. Devising an expressive syntax and structure is difficult, but that's the point. It's a way to examine and reexamine your application behavior without ever writing a single line of code. As far as parsing the configuration file, most high-level languages have good PEG libraries which make it easy to write parsers for ad hoc grammars. For C if you're not comfortable using the classic yacc framework then maybe that's a strong hint to avoid a configuration file altogether.