I say between 1 an开发者_C百科d 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
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.
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)
Let the requirements of the code dictate how long is too long.
Would you really rather your devs were spending their time writing emails than developing your code base?
A bit extreme, I think a cyclometric complexity of 5 or less is a reasonable measure rather than number of lines. Breaking code down to less than 5 lines could mean making it unreadable and laborious. I know there'll be differing thoughts on this which is why this thread should be closed as subjective.
I think it is more complicated than that.
First, methods tend to follow a power-law distribution: In any given project there will be some outliar methods which are so immensely larger than the vast majority of the other methods that the average size never converges.
Second, If you need to issue ten API calls in order to fulfil one specific task, there is no point in breaking this sequence of calls into two methods just to meet a size cap. When you break something into parts you have to give two names (or even three) instead of one. you have to document each part, etc. Bottom line: small is good, but do not follow it blindly. The best advice is to try to make every method coherent (focused).
Surely that just makes code harder to navigate and understand, A calls B, calls C, then E, then D, etc. I'm not sure how it enforces good naming, I have enough trouble thinking up good descriptive names for my existing methods, nevermind one ever 5 lines.
It also makes classes longer as you have to have the method signature, open and close brace and an extra line for readbility.
Also, most of my linq statements are well over 5 lines long.
精彩评论