there bits of code i'd customize. want assign bunch of student applications summer program various readers (so 100 apps, 3 readers, divide them evenly, etc). in cases, want take reader preferences consideration (i want read applications students in california, etc.). in other cases, don't care assigned to. right i've got looks this:
def assign_readers(preferences_flag): if preferences_flag: assign_readers_with_preferences() assign_remaining
i've got multiple cases of similar features throughout code turn on/off, doesn't clean way of doing it. same flag used in other parts of code, i'm passing around these flags left , right. example:
def log_reader_stats(preferences_flag, other_flag): if preferences_flag: log_reader_stats_with_preferences() if other_flag: log_readers_stats_with_other_stuff() log_remaining_stats
what alternative way of doing this? passing flags around seems repetitive , inefficient, other i'm not sure how can "toggle" such features on , off.
below example of how of actual code being used, , how flags come play.
use_pref = true use_spec_grp = true def main(): # load , store config file information fnames = {} snames = {} options = read_config_file() validate_config_params(options, fnames, snames) # load applications file apps = pio.file_to_frame(fnames["apps"], snames["apps"]) # load target , max number of apps each reader can handle. rdr_counts = pio.file_to_frame(fnames["rdr_counts"], snames["rdr_counts"]) # assign applications depending on options enabled if use_spec_grp: assign_all_special_groups(apps, fnames["spec_grp"], snames["spec_grp"]) if use_pref: assign_apps_with_prefs(apps, rdr_counts, fnames["rdr_prefs"], snames["rdr_prefs"]) assign_remaining_apps(apps, rdr_counts, fnames, snames)
although didn't ask this, there code smell warrants explanation. whenever find using parallel data sources fnames
, snames
in:
assign_all_special_groups(apps, fnames["spec_grp"], snames["spec_grp"])
you making error prone code. instead have
names['spec_grp'] = ('something', 'anotherthing')
which ensures elements of spec_grp
remain associated each other. there exists namedtuple type makes access readable:
names['spec_grp'].f_thing names['spec_grp'].s_thing
but without getting slight complexity you'll need access them with
names['spec_grp'][0] names['spec_grp'][1]
if reading intent properly, code above combine these values option flags that
options['spec_grp'] = (fname_for_spec_grp, sname_for_spec_group) if options['spec_grp']: assign_all_special_groups(apps, options["spec_grp"][0], options["spec_grp"][1])
this makes initializing configuration elements have no value none
important practice.
but didn't make calling code longer , harder read? kinda. did buy flexibility, maintainability, , safety few characters? yep. , turn 3 data structures (options, fnames, snames) 1 dictionary signals if option desired , if so, arguments are.
Comments
Post a Comment