klaethecoder / PythonExercises

0 stars 0 forks source link

Review: nested if structures #1

Open waded opened 5 years ago

waded commented 5 years ago

In most languages developers would expect line 36-46 starting here:

https://github.com/klaethecoder/PythonExercises/blob/81709aaa5228174cbcd7f6ee6c60f615ebfc6292/caesarCipher.py#L36

to be structured using the language's switch/case construct instead of nested if/else. There are 3 possible outcomes here (answer is 1, answer is 2, or answer is not either of those) and the nested structure doesn't represent that well, especially in that it has to check if answer == 1 in two if blocks, and can be misleading or difficult to change later (e.g. when someone needs to add a 4th possible outcome.)

I know Python doesn't have switch/case, but it does have an "else if" (see 4.1 here https://docs.python.org/3/tutorial/controlflow.html) and that lets you build a similar flat structure.

waded commented 5 years ago

I suspect there may also be an even more "Pythony" way to do it than if/elif/else using a data structure and function references, but I'm not a Python dev so I can't recommend anything in particular. if/elif/else would be a good initial simplification.