Let's suppose we find ourselves in a situation where we have no other option than to write a lengthy if-else statement (definitely not something that would make cleaner by polimorphism).
def inevitable_long_if (n):
if n == 0:
print('Zero')
elif n == 1:
print('One')
elif n == 2:
print('Two')
else:
print('Manu-manu')
Can we re-write it so that we do not use IFs?
import collections
import functools
d = collections.defaultdict(lambda : functools.partial(print, 'Manu-manu'))
d[0] = functools.partial(print, 'Zero')
d[1] = functools.partial(print, 'One')
d[2] = functools.partial(print, 'Two')
Now, let's call some to see how it works:
d[0]() ==> Zero
d[1]() ==> One
d[2]() ==> Two
d[7]() ==> Manu-manu
The first version is 9 lines long, the second one (without imports) is 4 lines long. To me, the second version is also much more readable, but you decide.
I have had the rare opportunity of watching and being part of the change that the software industry has gone through throughout over 20 last years. This blog is a collection of my reflections on pursuing agility path. It includes observations and advice regarding development teams and notes on useful engineering practices. Enjoy! Piotr Górak.
See also
-
We may often come across a piece of code that was written without Unit Tests at all. In addition, the piece of code may be dealing with IO l...
-
Google Mock provides several ways to maintain state inside mock objects. One way of implementing state maintenance is with SaveArg . Consid...
-
Requirements have a long history in software industry. We all have heard or read terms like: requirements definition, requirements managemen...
-
Google Mock provides a way to return newly created objects from a mock method. Suppose we have a Generator class that is supposed to ...
-
Can we verify that a mock object is properly destroyed? Of course! There is a couple of subtle differences between mocking regular func...