I would like to know what is the best way to handle a situation in which I repeatedly check a condition in a function using an if-elif-else string, and if the condition is different, I throw an exception. Is it better to repeat exactly the same if-elif-else string, knowing that the else condition will never occur, or, since I know it, to change the last elif to another? My question is probably better explained by an example.
One option is to repeat the entire if-elif-else string, knowing that the last
other the conditions will never be reached. For example:
a = 5 if case == "case1": a + = 5 case elif == & # 39; cas2 & # 39 ;: a - = 5 other: raise Exception ('unrecognized case') # do a bunch of other steps # then, later ... if case == "case1": a * = 5 case elif == & # 39; cas2 & # 39 ;: a / = 5 else: # this will never happen, should I remove it? raise Exception ('unrecognized case')
Another option is to replace the last final elif with another, as follows:
a = 5 if case == "case1": a + = 5 case elif == & # 39; cas2 & # 39 ;: a - = 5 other: raise Exception ('unrecognized case') # do a bunch of other steps # then, later ... if case == "case1": a * = 5 else: # I know that's the case 2 a / = 5
My goal is to make the code correct and expandable. There are many cases, although I only implemented the code for two of them. I would like to be able to implement them one by one when I need them. For the moment, I need only these two cases, but in a month, I may need two more. I will implement them when I do it and I want the code to make sense with any reasonable number (<= 8) of cases.
In the first example, have a
other condition that is never used seems like a waste. In the second example, the last
other works more like a "I know that's the case 2", which is fine for the moment, but when I get into the case3, I have to remember that this is not really the "other" situation, but the "case 2" situation. A third option is to completely delete the last
other of the first example, but then there is only one
elif, and it seems like a typo or an error is created to create a hard-to-find bug.