How short should a function be?
Ask five programmers about ideal function size and you'll get maybe 10 answers
As a fan of Robert C. Martin, I will write his two rules about function size:
Functions should be small.
They should be smaller than that.
When he says “small” he means it. He’s talking about a maximum of five lines.
I have been following his up-to-five-lines rule and this is what I have found:
It leads to nice code.
In some languages it works better than in others. In Python, Java (which Robert C. Martin uses in his examples) and JavaScript it works. In C it doesn’t.
Most of my Python code has small functions (up to 10 lines), but I’m not religious about 5 lines.
While I think it is unlikely for you to explore the up-to-five-lines idea, I’m confident that you should write shorter functions than you do. But there are more important things, such as complexity. More on that on the next post.
If you are curious, here is an up-to-five-lines example; three Python functions (methods), which many programmers would write as a single function:
def _check_monotonic(self, index):
if index.is_monotonic:
return
else:
self._raise_monotonic_exception(index)
def _raise_monotonic_exception(self, index):
offender = self._locate_first_nonmonotonic_date(index)
raise ValueError(
"Data incorrectly ordered after "
+ offender.isoformat()
)
def _locate_first_nonmonotonic_date(self, index):
prev = None
for current in index:
if prev is not None and prev > current:
return prev
prev = current