Self-Configuring Classes W/ Command Line Args: Pattern or Anti-Pattern?
I've got a program where a lot of classes have really complicated configuration requirements. I've adopted the pattern of decentralizing the configuration and allowing each class to take and parse the command line/configuration file arguments in its c'tor and do whatever it needs with them. (These are very coarse-grained classes that are only instantiated a few times, so there is absolutely no performance issue here.) This avoids having to do shotgun surgery to plumb new options I add through all the levels they need to be passed through. It also avoids having to specify each configuration option in multiple places (where it's parsed and where it's used).
What are some advantages/disadvantages of this style of programming? It seems to reduce separation of concerns in that every class is now doing configuration stuff, and to make programs less self-documenting because what parameters a class takes becomes less explicit. OTOH, it seems to increase encapsulation in that it makes each class more self-contained becaus开发者_如何学编程e no other part of the program needs to know exactly what configuration parameters a class might need.
Regardless of the way you do it, you have several "modules" which compete for the same sequence of command-line arguments. There must be some cooperation so that the same command-line arguments can be processed by your classes without clashes.
By having each class implements the parsing, you simply make that cooperation implicit. There is no module dedicated to the cooperation between your classes. The problem becomes a matter of documentation rather than a matter of code. It is not bad but it may seductively appear as if the problem has simply "gone away". To be brief, this practice requires more discipline.
Also, it will make major overhauls of command-line argument syntax more difficult.
it seems to increase encapsulation in that it makes each class more self-contained because no other part of the program needs to know exactly what configuration parameters a class might need.
If I understand what you're proposing, it really makes each class hide their dependencies.
The dependencies in this case may be simple (primitive), but if a class needs an username and password to function correctly, it should say so in its constructor. Otherwise, the class' callers need to look at the source code or documentation to use it.
精彩评论