3 Shatter long functions

 

This chapter covers

  • Identifying overly long methods with Five lines
  • Working with code without looking at the specifics
  • Breaking up long methods with Extract method
  • Balancing abstraction levels with Either call or pass
  • Isolating if statements with if only at the start

Code can easily get messy and confusing, even when following the Don’t Repeat Yourself (DRY) and Keep It Simple, Stupid (KISS) guidelines. Some strong contributors to this messiness are as follows:

  • Methods are doing multiple different things.
  • We use low-level primitive operations (array accesses, arithmetic operations, etc.).
  • We lack human-readable text, like comments and good method and variable naming.

Unfortunately, knowing these issues is not enough to determine exactly what is wrong, let alone how to deal with it.

In this chapter, we describe a concrete way to identify methods that likely have too many responsibilities. As an example, we look at a specific method in our 2D puzzle game that is doing too much: draw. We show a structured, safe way to improve the method while eliminating comments. Then, we generalize this process to a reusable refactoring pattern: Extract method (P3.2.1). Continuing with the same example draw method, we learn how to identify another problem of mixing different levels of abstraction and how Extract method can also alleviate this issue. In the process, we learn about good method-naming habits.

3.1 Establishing our first rule: Why five lines?

3.1.1 Rule: Five lines

3.2 Introducing a refactoring pattern to break up functions

3.2.1 Refactoring pattern: Extract method

3.3 Breaking up functions to balancing abstraction

3.3.1 Rule: Either call or pass

3.3.2 Applying the rule

3.4 Properties of a good function name

3.5 Breaking up functions that are doing too much

3.5.1 Rule: if only at the start

3.5.2 Applying the rule

Summary

sitemap