Can functions be too short?

(Initially written as part of Week­notes 2023 W01: Boredom.)

Common advice is “keep your functions short”. But can functions be too short?

Lately, I’ve been working in codebase where this advice is followed to the extreme. The code that I’ve seen looks a bit like this made-up example of a #total_price method:

def base_price
  @_base_price ||= @item.price
end

def tax_fraction
  tax_config.tax_fraction
end

def tax
  base_price * tax_fraction
end

def total_price
  base_price + tax
end

def tax_config
  @global_config.tax
end

That code is hard to follow because the execution flow jumps all over the place, from function to function. There is no straight-line flow. Compare with this:

def total_price
  base_price = @item.price
  tax = base_price * tax_fraction
  base_price + tax
end

def tax_fraction
  @global_config.tax.tax_fraction
end

I much prefer the second version: I can read it from top to bottom and understand what is going on. Admittedly, this shorter version looks more complex — but the complexity is there in the first version, too, just more obscured.

The idea behind the advice “keep your functions short” is increased readability. In the example above, though, that advice is counterproductive.

Note last edited November 2023.