6 Don’t surprise your users

 

This chapter covers

  • The Principle of Least Astonishment and how to avoid surprising your users
  • Preventing unexpectedly poor runtime performance
  • Careful coding with Python lists, tuples, and arrays
  • Refactoring code to improve performance
  • Applying Programming by Contract to a class and its methods

We all love surprise parties, but being surprised by the results of a function call is a definite sign of poor design. Well-designed software should not contain any surprises that can cause runtime logic errors or poor performance.

Ideally, when we design a class, its objects will behave and perform just the way its users expect. A user can be another programmer who uses the class or an end user who interacts with the application. Unexpected behavior can lead to runtime logic errors or applications that don’t perform well.

This chapter covers some common unwanted code surprises and ways to eliminate them. Some bad surprises are simply how Python works. However, some surprises are a result of preventable coding faults, such as the common off-by-one error. A well-named function or method won’t mislead another programmer to believe that it does something other than what its name suggests.

6.1 No surprises and the Principle of Least Astonishment

6.1.1 Off-by-one errors

6.1.2 Misnamed functions can mislead their callers

6.2 Poor performance is an unwelcome surprise

6.2.1 Bad design can cause unexpected performance problems

6.2.2 Performance surprises of lists, tuples, and arrays

6.3 Programming by Contract helps to eliminate surprises [optional]

6.3.1 Programming a circular buffer by contract

6.3.2 Precondition: What must be true before calling a function

6.3.3 Postcondition: What must be true after returning from a function

6.3.4 Class invariant: What must remain true of object states

6.4 Summary