Reputation: 1
I want to get devs' opinions about next code examples. Which code is more readable? Which is better style?
Note: expression int(a is not None) + 3*int(b is not None) + 5*int(a != b)
return unique code for all combinations values of listed conditions.
And sorry for my english. I am trying to make it better.
First:
if (a is not None) and (b is not None) and (a != b):
exit()
elif (a is not None) and (b is not None) and (a = b):
func1()
elif (a is not None) and (b is None):
func2()
elif (a is None) and (b is not None):
func3()
elif (a is None) and (b is None):
func4
second:
code = int(a is not None) + 3*int(b is not None) + 5*int(a != b)
if code == 9:
exit()
elif code == 4:
func1()
elif code == 1:
func2()
elif code == 3:
func3()
elif code == 0:
func4()
third:
code = int(a is not None) + 3*int(b is not None) + 5*int(a != b)
switch = {9:exit, 4:func1, 1:func2, 3:func3, 0:func4}
switch[code]()
Upvotes: -1
Views: 53
Reputation: 2463
I would do:
if a is None:
if b is None: func4()
else: func3()
else:
if b is None: func2()
elif a == b: func1()
else: exit()
I'm definitely not a fan of the int switching. And, even more ideally, your structure for a and b would allow you to just check not a
instead of a is None
, which would be even cleaner.
In the off-chance that you do ever need to encode boolean flags into a number, I would also recommend that you use base 2 (1,2,4...) instead of the base system you're using (1,3,5..)--which might make sense if you were bounded by space (saving compressed data, eg Chess bitboards, or lots of fast network IO), but if you don't have a crazy requirement, remember:
"Premature optimization is the root of all evil." Donald Knuth
Upvotes: 4