Composed Method
posted on: Sep 9, 2019

The problem with a sloppy program is that it does too much work, often at various levels of abstractions. It will connect to the database, fetch data, create objects and perform validation in the same method. The code is too long, it is hard to read, and it doesn’t communicate with the reader. It is hard to maintain, hard to test, and can’t handle future changes. What to do?

Composed method is a pattern that solves these issues. A common solution for these type of problems is to divide the program into methods that perform one task at a time, and keeping all the operations in a method at the same level of abstraction. When writing a new method from bottom-up, we can create a bunch of smaller methods. On the other hand, if an existing method is doing too much, we can extract the pieces of code into separate methods. Finally, we can give an intention revealing name to each method.

Not only composed method pattern results in better code, it also improves developer productivity. A programmer reading a piece of code saves a lot of cognitive resources if the method name indicates what the method is doing, and they don’t have to dive deep into the code to see how it’s doing it. The reader can read the program much more quickly and accurately if they can chunk the internal implementation details of the method into higher-level abstractions. The method is also easy to maintain in the future and flexible to handle future changes.