Chapter 11. One Task at a Time
Code that does multiple things at once is harder to understand. A single block of code might be initializing new objects, cleansing data, parsing inputs, and applying business logic, all at the same time. If all that code is woven together, it will be harder to understand than if each âtaskâ is started and completed on its own.
Key Idea
Code should be organized so that itâs doing only one task at a time.
Said another way, this chapter is about âdefragmentingâ your code. The following diagram illustrates this process: the left side shows the various tasks a piece of code is doing, and the right side shows that same code after itâs been organized to do one task at a time.
You might have heard the advice that âfunctions should do only one thing.â Our advice is similar, but isnât always about function boundaries. Sure, breaking a large function into multiple smaller functions can be good. But even if you donât do this, you can still organize the code inside that large function so it feels like there are separate logical sections.
Hereâs the process we use to make code do âone task at a timeâ:
List out all the âtasksâ your code is doing. We use the word âtaskâ very looselyâit could be as small as âmake sure this object is validâ ...
Get The Art of Readable Code now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.