Should functions be _this_ small?
I am reading through the book Clean Code by Robert C. Martin. It is a book of advice on how to write more readable, and consequentially, more maintainable code. There is a chapter on writing good functions. His section on how small functions should be seems pretty extreme, and I wanted to hear the communities opinion on what he says. The following are some brief excerpts, followed by a couple examples.
Quote:
Originally Posted by pg. 34
Small!
The first rule of functions is that they should be small. The second rule of functions is that they should be smaller than that....
How short should a function be? In 1999 I went to visit Kent Beck at his home in Oregon...At one point he showed me a cute little Java/Swing program that he called Sparkle...Every function in this program was just two, or three, or four lines long. Each was transparently obvious. Each told a story. And each led you to the next in a compelling order. That's how short your functions should be!
Quote:
Originally Posted by pg. 35
Blocks and Indenting
This implies that the blocks within if statements, else statements, while statements, and so on should be one line long. Probably that line should be a function call. Not only does this keep the enclosing function small, but it also adds documentary value because the function called within the block can have a nicely descriptive name.
This also implies that functions should not be large enough to hold nested structures. Therefore, the indent level and a function should not be greater than one or two. This, of course, makes the functions easier to read and understand.
Quote:
Originally Posted by pg. 302
G30: Functions Should Do One Thing
...For example:
Code:
public void pay() {
for (Employee e: employees) {
if (e.isPayday()) {
Money pay = e.calculatePay();
e.deliverPay(pay);
}
}
}
...This code would be better written as:
Code:
public void pay() {
for (Employee e: employees)
payIfNecessary(e);
}
private void payIfNecessary(Employee e) {
if (e.isPayday())
calculateAndDeliverPay(e);
}
private void calculateAndDeliverPay(Employee e) {
Money pay = e.calculatePay();
e.deliverPay(pay);
}
There is another example found at this link of a team who tried implementing the small function advice in their java code base.
I have not made up my mind what I think about breaking functions apart like this. What do you guys think?