7 Make code hard to misuse

 

This chapter covers

  • How the misuse of code can lead to bugs
  • Common ways code can be easy to misuse
  • Techniques for making code hard to misuse

Chapter 3 discussed how the code we write is often just one piece of the jigsaw in a much larger piece of software. For a piece of software to function correctly the different pieces of code have to fit together and work. If a piece of code is easy to misuse, then the chances are sooner or later it will get misused and the software will not function correctly.

Code is often easy to misuse when there are assumptions baked in that are unintuitive or ambiguous and other engineers are not prevented from doing the wrong thing. Some common ways code can be misused are as follows:

  • Callers providing invalid inputs
  • Side effects from other pieces of code (such as them modifying input parameters)
  • Callers not calling functions at the correct times or in the correct order (as seen in chapter 3)
  • A related piece of code being modified in a way that breaks an assumption

Writing documentation and providing usage instructions for code can help mitigate against these. But as we saw in chapter 3, these are like small print in the code contract and can often be overlooked and become out of date. It’s therefore important to design and write code in a way that makes it hard to misuse. This chapter shows some common ways code can be easy to misuse and demonstrates techniques for instead making it hard to misuse.

Hard to misuse

7.1 Consider making things immutable

7.1.1 Mutable classes can be easy to misuse

7.1.2 Solution: Set values only at construction time

7.1.3 Solution: Use a design pattern for immutability

7.2 Consider making things deeply immutable

7.2.1 Deep mutability can lead to misuse

7.2.2 Solution: Defensively copy things

7.2.3 Solution: Use immutable data structures

7.3 Avoid overly general data types

7.3.1 Overly general types can be misused

7.3.2 Pair types are easy to misuse