chapter two

2 Simple code

 

This chapter covers

  • Breaking large units of code into smaller pieces
  • Moving new complexity away from existing units of code
  • Documenting your code to improve understanding

Making code simple and small is the first thing you should always consider. Even with a well-designed software system, losing sight of code complexity is easy. Lines of code tend to overgrow if we don’t actively work to prevent it, leading to oversized classes. Long classes and methods happen more often and more naturally than we like to admit. It’s just too easy to open an existing class in the system and add more code instead of reflecting on the impact of these new lines and re-design the code.

Uncontrolled complexity hinders code evolution. Complex code is harder to read and understand than simple code. As a developer, you’ve likely experienced the mental strain of deciphering a 200-line method compared to a 20-line one. You feel tired even before starting to read it.

It’s also known that highly complex code is more prone to bugs. It’s easier to make mistakes in code that’s difficult to grasp. It’s also hard to write tests for complex code, as it has too many different cases and corner cases to be explored, and it’s just too easy to forget one of them. And we can’t blame the developer. It’s hard to develop good test cases for complex code.

2.1 Make units of code small

2.1.1 Break the complex method into private methods

2.1.2 Move the complex unit of code to another class

2.1.3 When not to divide code into small units?

2.1.4 Example: Importing employees

2.2 Make code readable and documented

2.2.1 Keep looking for good names

2.2.2 Document decisions

2.2.3 Add code comments

2.2.4 Example: Deciding when to send an update e-mail

2.3 Move new complexity away from existing classes

2.3.1 Give the complex business logic a class of its own

2.3.2 Break down large business flows

2.3.3 Example: waiting list for offerings

2.4 Summary