Home

Adding sentinel values

When reading Practice of programming by Brian W. Kernighan and Rob Pike I came across this advice:

As a rule, try to handle irregularities and exceptions and special cases in data. Code is harder to get right so the control flow should be as simple and regular as possible.

I came across a piece of code I could apply it today!

Instead of this:

required_days_list = []
# ...lots of code where we append stuff in the list...
# in a senario where no products in database has delay, we can't apply max on empty arg
if len(required_days_list) == 0:
	return 0
return max(required_days_list)

You could do this:

required_days_list = [0]
# ...lots of code where we append stuff in the list...
return max(required_days_list)

Shorter and nicer don't you think?