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.
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