Dealing with Situations That Your Code Doesn’t Handle

You’ll often write a function that works only in some situations. For example, you might write a function that takes as a parameter a number of people who want to eat a pie and returns the percentage of the pie that each person gets to eat. If there are five people, each person gets 20% of the pie; if there are two people, each person gets 50%; if there is one person, that person gets 100%; but if there are zero people, what should the answer be?

Here is an implementation of this function:

 def​ pie_percent(n: int) -> int:
 """Assuming there are n people who want to eat a pie, return the
  percentage of the pie that each person gets to eat.
 
  >>> pie_percent(5)
  20
  >>> pie_percent(2)
  50
  >>> pie_percent(1)
  100
  """
 
 return​ int(100 / n)

Reading the code, if someone calls pie_percent(0), then you probably see that this will result in a ZeroDivisionError. There isn’t anything that anyone can do about this situation; there isn’t a sensible answer.

As a programmer, you warn other people about situations that your function isn’t set up to handle by describing your assumptions in a precondition. Here is the same function with a precondition:

 def​ pie_percent(n: int) -> int:
 """Precondition: n > 0
 
  Assuming there are n people who want to eat a pie, return the percentage
  of the pie that each person gets to eat.
 
  >>> pie_percent(5)
  20
  >>> pie_percent(2)
  50
  >>> pie_percent(1)
  100
  """
 
 return​ int(100 / n)

Whenever you write a function and you’ve assumed something about the parameter values, write a precondition that lets other programmers know your assumptions. If they ignore your warning and call it with invalid values, the fault does not lie with you!

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.216.96.94