Ensuring DRY for the configuration

We have a potential Don't Repeat Yourself (DRY) issue between our construction of the argument parser and the use of the arguments to configure the application. We built the arguments using some keys that are repeated.

We can eliminate this repetition by creating some internal configurations that map to the externally visible values. For example, we might define this global as follows:

dealer_rule_map = {"Hit17": Hit17, "Stand17", Stand17} 

We can use it to create the argument parser, as follows:

parser.add_argument(
"--dealerhit", action="store", default="Hit17",
choices=dealer_rule_map.keys(),
dest='dealer_rule')

We can use it to create the working objects, as follows:

dealer_rule = dealer_rule_map[config.dealer_rule]() 

This eliminates the repetition. It allows us to add new class definitions and parameter key mappings in one place as the application evolves. It also allows us to abbreviate or otherwise rewrite the external API, as shown here:

dealer_rule_map ={"H17": Hit17, "S17": Stand17} 

There are four of these kinds of mappings from the command-line (or configuration file) string to the application class. Using these internal mappings simplifies the simulate_blackjack() function.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset