Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's a good average method size? [closed]

Tags:

java

c#

oop

I say between 1 and 5 lines. Anymore than that you should justify with an email to the rest of your dev team. This aids reuse, forces good naming and couples methods.

Any comments?

Thanks

like image 322
DayOne Avatar asked Jul 06 '10 11:07

DayOne


2 Answers

The method code size is a wrong metric for method's responsibilities. The method should just have exactly one main behavioral/creational task without code duplicates.

like image 158
BalusC Avatar answered Oct 05 '22 23:10

BalusC


1 and 5 lines seems like way too small a limit to me. If you're putting together simplistic business apps that don't do much processing then this seems OK, but if there are any algorithms or processes it's often far more readable (and maintainable) to write the processing steps sequentially rather than spread across multiple methods or classes - even if it is logical for the purposes of encapsulation, validation and so on.

5 lines in many cases isn't even enough to validate parameters and iterate through a collection.

I would suggest 'about a pageful'; 20 to 30 lines are ideal.


For example: this seems valid to me, but you would consider it no good at 8 lines:

    // Calculates the depth of the layer in the object graph
    public int GetIndex()
    {
        int ct = 0;
        ViewLayer pos = this;
        while (pos.Parent != null)
        {
            ct++;
            pos = pos.Parent;
        }
        return ct;
    }

(I realise I am opening myself up to criticism by posting code, but my point stands, this is readable code)

like image 25
Kieren Johnstone Avatar answered Oct 06 '22 00:10

Kieren Johnstone