by windows_sucks · 4y ago · 0 comments
make_pepperoni_pizza()
is bad code compared to
make_pizza(toppings=[PEPPERONI])
How would you make Hawaiian pizza? I forget, does it include Ham? or just pineapple? you're forced to the remember that nuance in your suggested implementation, but not with "make_hawaiian_pizza()" make_pizza(toppings=HAWAIIAN_TOPPINGS)
or make_pizza(HAWAIIAN)
or similar. Data should generally not be hard-coded, both because it changes and because it wants to be validated. Starting with: HAWAIIAN = { TOPPINGS: [ PINEAPPLE ...
is okay. That can later be loaded from a config file, a database, or otherwise, as the system expands.I use Python. It's easy enough to, for example, make an `enum` from entries in a config file or even a database:
https://docs.python.org/3/library/enum.html
Scroll down to the functional API. There are many similar design patterns. The nice thing about these is that you get automatic type checking. If your config file is:
toppings: ['pepperoni', 'ham', 'pineapple'],
pizzas: {
'Hawaiian': ['pinapple']
}
If you load this in as strings, it will load and later silently fail. If you add validation code, you'll only validate what you remember. If you make an enum or similar custom type, it necessarily will fail-on-load, and probably with a reasonable error.The major downside -- which is really incidental (due to poor library design) -- is that most JSON/YAML libraries won't reasonably serialize/deserialize non-Python types. So there's a bit of (unnecessary) overhead there.