grggls / cronparser

minimum viable cron parser
0 stars 0 forks source link

rewrite ugly if/elif/else block in `__init__` making use of the Strategy pattern #6

Closed grggls closed 6 years ago

grggls commented 6 years ago

use the method outlined in Make Mistakes in Python pp38, i.e.

We start by extracting the contents of our if/elif/else structure into separate functions with identical interfaces. Then we can create a dictionary to map conditions to those strategy functions. The dic‐ tionary key doesn’t have to be a string. It can be anything hashable, so tuples and frozensets can be quite effective if we need richer con‐ ditions. Finally, our original function determines which key to use, plucks the appropriate strategy function from our dictionary, and invokes it.


def strategy1():
     ... 

def strategy2():
    ... 

strategies = {
  'condition1': strategy1, 
  'condition2': strategy2,
  ...
}

def do_awesome_stuff():
    which_one = ... 
    strategy = strategies[which_one]
    strategy()

(Page 38).