How many lines should a function have?

This question is probably one of the most debatable in programming, ever, and I wasn’t much surprised to find it also on Stack Overflow(1).

Actually, I wasn’t surprised to find about a dozen different questions in the same gist, but here is the one that I really liked, especially some of the more interesting answers: How many lines should a method typically have?.

And to quote one of the answers that I really liked:

It should fit in my head.

That is to say, if I put my head against the monitor, the method should not be seen as extending past the boundaries of my head.

So what do you think should a method’s size be?

The way I see it – in the simplest terms – a function or method should be only as long to do one logical operation and no more. That being said, if your one logical operation is to large to fit on the screen, then something is very wrong with your logic 🙂 .


  1. The best programming questions and answers site – if you’re a programmer by trade or hobby and you’re not familiar with Stack Overflow, then go register. []

2 Responses to “How many lines should a function have?”

  1. Shlomi Fish:

    Hi Oded!

    I feel that the shorter the method, the better. Generally a method should receive parameters (which is generally a bit more complex in Perl 5 due to the @_ stuff), possibly validate them, and then return a value that is a single expression. The reason for this is that that way one can more easily over-ride such methods or inherit from them and have greater code re-use. I recall seeing a very long method in the Catalyst (a web-framework for Perl’s) codebase, and I needed to override a very small expression out of it in order to make sure that it did not treat URLs with a trailing slash (“/”) the same as URLs without them.

    Of course, I sometimes write my methods and functions longer out of laziness, and because they acquire cruft, but this is the ideal. One of the codebases that I’m most proud of in having short, single-purpose methods is Test-Run. I’ve spent a long time perfecting it, partly because I started from an old and monolithic and completely non-OOP codebase (reportedly dating back to Larry Wall’s perl 1.0), which I decided to whip into shape, and while completely breaking backwards-compatibility.

    And finally, can you please get comments previews here? I don’t know if this comment would be OK. Stupid WordPress.

  2. Oded:

    So – you do not believe in side-effects? programming with no side-effects is basically functional programming – a paradigm that I never though merited the hype around it, and like OOP – when taken to the extreme – results in unusable programs.

    Regarding preview comments – I never figure this for a good idea, you are basically writing text here. I’ll see what I can do, though due to my BiDi hack most text manipulation plugins for wordpress require some work to adapt to my blog.

Leave a Reply

 

 


Spam prevention powered by Akismet