10

I'm really a beginner when it comes to programming and have read that I should make each method as small as possible. Can anyone suggest how many lines of code is a good number for each method?

25

There is no exact number of lines you should put in a method. What matters is making sure each method performs its task. I've seen people say that if you have a method that does several things, like creates an employee gives him a raise and fires him, those should all be separate functions so you need smaller functions. But don't worry about lines of code per se, but make sure that each function is doing what it should, and it does it well. :D

11

However many lines it takes to do one task.

The only time methods get longer than "necessary" is when you try to do too many things in them. Keep it to one task per method.

If you have a method that does a few multi-step things, then all it should do is call other one-task methods.

7

Aim for zero. It guarantees the best combination of efficiency and readability.

7

42 would be best

6

As a general rule, try to keep them small enough to fit entirely on screen. This way you can refer to the entire body of the method at once.

That said, with experience, you'll begin to naturally break things up without need to refer to external rules like this. The important thing is that each method perform some independent, logical task, so you can clearly focus on a single level of abstraction without getting caught up in too many details.

5 accepted

I'll build on what CrazyJugglerDrummer said. A method should do one thing, and only one thing. I've seen Agile programmers go so far as to say that each method should be only one line long. I think that's taking things to an extreme, but I understand their intent. You want each method to be simple and well-defined.

If you already have a pile of complex code that you've inherited, you might want to apply the principles from the classic Refactoring book by Martin Fowler. Should help you identify pieces of long methods that can be broken off into their own methods.

4

LOC will tell you just how much you've typed. I suggest you to forget about it and look for some other metrics, like Cyclomatic Complexity.

4

As posed, the question isn't really language-agnostic. I tend to figure that 10 lines is fairly long for a Python function, but fairly short for a C++ function. Some C++ function signatures are longer than the equivalent Python implementation. Still, that's not to say you shouldn't make C++ functions short where possible, or that longer Python functions are unacceptable. Just that I don't think much of it if a C++ function takes a couple of lines to declare, then a few lines of variable declarations, and some lines with nothing on them but curly braces. They aren't really "meat", and don't imply that the function is complicated. On the other hand, 10 lines of Python probably does at least 10 independent things, which is starting to sound like hard work.

I definitely agree with everyone else, though, that the answer to the "real" question is language-agnostic. A function should be long enough to do what it says on the tin, and no longer. If you can't look at a whole function at once then you're storing up trouble for yourself, so you do in general want a function to fit on screen. But don't treat that as a serious limit - clearly it doesn't mean that functions I write on my desktop with a 1920x1200 monitor should be twice as big as functions I write on my laptop at 1280x800. The underlying point is just that a function should do one thing, and you should be able to take in what it does when you read the code.

There are always times where you know you have to go through a whole sequence of steps, and you do it, and you've written a great long function. It's debatable whether it's worth then breaking this down into smaller functions, one per step. If it makes it more clear what's going on then probably yes, and if it makes it less clear then probably no. Sometimes it's pretty much a wash, so if the code is nasty look for a better way to express the algorithm that's more amenable to being broken down, and if it's "good enough" despite being a long function, you get on with the rest of your life.

3

I'm reading Code Complete right now and there's a bit of advice on this topic and similar ones. Here's a short quote from a chapter called "How long can a routine be":

A mountain of research on routine length has accumulated over the years, some of which is applicable to modern programs, and some of which isn't:

  • A study [...] found that routine size was inversely correlated with errors: as the size of routines increased (up to 200 lines of code), the number of errors per line of code decreased [...].

  • Another study found that code needed to be changed least when routines averaged 100 to 150 lines of code [...].

  • A study at IBM found that the most error-prone routines were those that were larger than 500 lines of code. Beyond 500 lines, the error rate tended to be proportional to the size of the routine [...].

Where does all this leave the question of routine length in object-oriented programs? [...] From time to time, a complex algorithm will lead to a longer routine, and in those circumstances, the routine should be allowed to grow organically up to 100?200 lines. (A line is a noncomment, nonblank line of source code.) Decades of evidence say that routines of such length are no more error prone than shorter routines.

That said, if you want to write routines longer than about 200 lines, be careful. None of the studies that reported decreased cost, decreased error rates, or both with larger routines distinguished among sizes larger than 200 lines, and you're bound to run into an upper limit of understandability as you pass 200 lines of code.

I don't know how long a quote can be without violating the copyright though .. there's more in the book of course.

1

I try not to think so much about lines of code (which can vary a lot by language) but the issue isn't quite so much that methods are long in that they try to do too much. The very fact that you are considering this issue is great for a beginner.

You generally want methods to do one thing (and do it correctly), and not repeat code. Give it a descriptive name that should easily identify it's purpose and/or side effect. If the "one thing" that it does is implement a complex algorithm that takes many lines of code, that's fine. If a lot of the code is repetitive, you should edit (or what programmers call, "refactor") and take that repetitive code out into another method.

The ideal is, with each part doing its one thing and doing it well, the whole system should work together nicely.

1

It really depends a lot. There's no hard and fast rules, and there are many times where you need to do things that at other times might be bad.

I'd personally say you should often try to be able to get the meat of the function to be able to fit within a page or less. At the same time, try to group all the code that fits logically together, and if you ever think you'd need to reuse that code, it might be a good idea to throw it into its own funtion/method (generally marked as private or an equivalent is a good idea).

Personally, I also don't really like when a function is only one or two lines long, but sometimes that's all they need to be, yet at the same time they need to be in their own function.

Also, at the same time, don't try to pad your code to make them longer, and don't put too much crap onto one line to make it appear shorter (I'd say try to never extend beyond the end of the screen horizontally, that really hurts readability).

1

I find it depends on the language and framework you're using. For example, I try to stick to less than 10 lines of code in Ruby on Rails, while I'll try to keep it under 15 or 20 in .Net.

1

Here's another way to look at it; what not to do.

I occassionaly support a legacy Vb6 application (not written by myself) that has a method with thousands of lines, it has no comments, it uses many GoSub calls and features variable names such as k, kk, and jjj, and of course not forgetting multi-dimension arrays.

This is how not to write your methods.

1

as icco already stated, a maximum of fifty.

A method has the following requisite:

1) its name must clearly convey what it does

therefore

2) it must do one thing, and be clear on how this is achieved.

as a consequence

3) the implementation must be concise, understandable and visible as a whole

Leading to

4) a method must fit in a single page of an editor. Two pages is the real maximum.

If you have a method that is larger than two pages, chances are that you can refactor out some parts of it into a more appropriate method. It is a warning sign. Of course, the less expressive is the language, the more difficult is to have functions that obey this criterium. If you program in highly expressive languages (e.g. Java and above) the rule is good as is.

1

These answers saying an exact amount aren't valid. A method should simply contain as many lines or as few lines of code it takes to get A(one) job done. There's a good argument about this over here at a forum I visit.

To Quote myself from there,

It doesn't matter for lines of code as to whether it works. x.x

Just keep that in mind. If you're learning what you're coding at the same time, you'll have a couple 10s of lines. As you learn more, you'll refactor and reduce that to something simple.

A PERFECT example comes to mind as I type:

I was writing a method to check whether a computer was online in our computer lab and using System.Diagnostics.Process class to launch ping.exe each time. Lines of code: ~15 lines of code. I reduced it down to 1 line of code by calling Microsoft.VisualBasic.Devices.Network.Ping :) 15 lines to 1 line.

0

As CrazyJugglerDrummer said, there is no exact number. You should break your code up using descriptive functions that tell you exactly what a block of code is doing, so that you can more or less read it like english. If you find a particular function getting really long (a couple screen lengths perhaps), then examine the code and see if there aren't blocks of code within that function that are doing one thing, which you can describe with some sort of action verb. If so, toss it in another function.

0

It not only depends on the language you're using, it also depends on the task you're trying to complete. I see no reason to separate a method of 30 lines into 3 methods, each with 10 lines, unless you're planning on reusing one of those new methods somewhere else.

Don't be so worried about the number of lines in a method, be worried about duplicating code across your codebase. If there's anywhere where it looks like two or three lines of code do very similar things, try to break it out into a method.

0

This gets easier to assess with experience.

I found, personally, after 10 year of programming ostly procedural code (primarily Java, but plenty of Django, ASP, VB, PHP, and C/C++ in year bygone), that now I have a feel for functions which I am happy with, which ones I am not proud of, and which ones I am man to admin that I wrote but I wish I did not have to.

This does not meant that I rewrite every function to meet a line number target. It depends what I am doing. Besides correctness, I try to strive for readability. Sometimes though, backwards compatibility takes a big bite out of readability. C'est la vie.

Anyway, to get back on point, Ii find that I have about 3 types of functions I write.

  1. Simple functions
  2. Loopers
  3. Procedural steps 1.2.3.etc.

Simple functions are of the type isValid() or canBeDoneRightNow() or getCurrentValue(). These generally look up a value, check some conditions, and return a response. I try to keep these to under 10 lines, including empty lines for legibility. Most of the time, I try to make sure these functions do not need comment as the name is descriptive and logic is simple.

Loopers are a special breed. They are a necessity in procedural languages. In function languages, there are ways of getting rid of these, since the language itself provides ways of not having to write functions as this. In general, they have a syntax of:

function processListOfItems()
{
   for each item:
      if not item.isValid(): 
            continue;
      if needsPreProcessing(item):
            preProcessItem(item);

       processItem(item);
}

The procedural step functions tend to run long. These are usually high-level functions of the type createAccount() or processOrders() or initServerSubsystemX(). They usually implement high-level things, keep some state though the run of the function, and do not affect class fields directly. Usually, they can be easily transcribed as a flowchart. They can contain 1 level deep (maybe 2 if I am feeling particularly daring) conditionals. They call the simple functions and loopers. I try to keep loops our of these functions as well, unless necessary.

This covers about 80% of my code. The rest, I am simply not proud of, haven't gotten a chance to fix, or it has such interdependencies with other code that I am incapable of fitting it in the above molds.

I hope this helps. You will develop your own style if you like what you are doing. You will also have situations where you will break it and it will cause you some pain, but you will be aware of the tradeoffs which forced you to do it.

Good luck in your journey.

0

A method should only perform one task, and that method should be named accordingly. If you finish your method and realize it does more than a single task, then it needs to be refactored. You will find that if you keep your code refactored this way, that you will have very loose coupling in your programs (which is excellent), and good modularity (also excellent). As for lines of code perse, honestly there's no limit. However, once you see your method reaches an excessive amount or it's unreadable or maintainable, then you can probably find ways to refactor it, because it probably needs it.

On another note, one thing that will help you is to treat your classes and structures as real world objects. This, again will help with modularity and refactorability in your code, thus again bringing about loose coupling and better architecture. A good example is my gaming headset. If I wanted to write a class to represent my headset, I could code everything into a single class. But this would make it large and possibly unmaintainable. So, I could break it up. I could have a Headset class, a Speaker class, a EarPiece class, and so on so forth. This is modularity.

Good modularity, refactorability, and loose coupling are 1:1:1 to good architecture and design, and a quality implementation of whatever it is you're doing.

0
  1. Divide your program into methods that perform one identifiable task.
  2. Keep all of the operations in a method at the same level of abstraction.

This will naturally result in programs with many small methods, each a few lines long. This is called the Composed Method pattern and it is one of the cornerstones of writing clean code. See this presentation for more details (its PDF slides are here).

The benefits:

  • shorter methods easier to test
  • method names become documentation
  • large number of very cohesive methods
  • discover reusable assets that you didn?t know were there

The class should then read like a newspaper, top to bottom, so that first come the methods with the highest level of abstraction and as they call other methods, the lower level methods will come after their first usage in the order that they are used.

For more information and examples, read the book Clean Code.

0

Ask a peer to read your method, if he says WTF, you should break your method in several more readable methods.

0

No more than 17 lines. No more, no less. So if is under 17 lines carriage returns will do the trick. If its more than 17 you will need to start calling other functions from within the function.

For example:

public function myFunction() {
...
line 17: myFunctionPart2();
}

public function myFunctionPart2() {
...
line 17: myFunctionPart3();
}

And so on.

Its pretty standard programming practice.

-2

A maximum of Fifty. If you are putting more in you should probably abstract your method out some more, and never go over 200.