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:

  1. Functions should be small.

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

  1. It leads to nice code.

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

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

    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