Java Forum / General / December 2005
Huge methods, can they ever be justified ?
Duncan - 16 Dec 2005 17:15 GMT Hello
Can a single method with 1300 lines of code in it ever be justified.
Madness, sheer madness.
Monique Y. Mudama - 16 Dec 2005 17:42 GMT > Hello > > Can a single method with 1300 lines of code in it ever be justified. > > Madness, sheer madness. I'm sure someone could come up with a pathological example.
In general, probably not.
I try to follow a guideline a coworker suggested to me when I was starting out: try to keep methods small enough to fit them on a screen, so that a person can read them without scrolling.
It can actually clean up code pretty well to break things into methods (duh, right?). Especially if you have a lot of heinous if/else blocks, pulling the contents into separate methods can make things a lot clearer.
The hard part, often, is figuring out the appropriate descriptive method name.
 Signature monique
Ask smart questions, get good answers: http://www.catb.org/~esr/faqs/smart-questions.html
HalcyonWild - 17 Dec 2005 14:01 GMT > > Hello > > [quoted text clipped - 3 lines] > > I'm sure someone could come up with a pathological example. ... snip ....
> The hard part, often, is figuring out the appropriate descriptive > method name. Alas, How True. I really looked up a thesaurus once.
Thomas Schodt - 17 Dec 2005 15:51 GMT >>The hard part, often, is figuring out the appropriate descriptive >>method name. > > Alas, How True. I really looked up a thesaurus once. <http://thesaurus.reference.com/search?q=thesaurus&db=roget>
^_^
richardsosborn@gmail.com - 23 Dec 2005 18:25 GMT no kidding. does anyone here want to walk in on a method 1200 lines along and try and debug it? comments can only go so far. one vote for machine generated and used only.
Alun Harford - 16 Dec 2005 17:55 GMT > Hello > > Can a single method with 1300 lines of code in it ever be justified. > > Madness, sheer madness. Performance, and where breaking things down into more methods won't aid understanding (eg. lots of bitwise operations that you have calculated, but where no individual operation is doing anything other than "moving towards the result"). eg. Evaluation functions for game-playing programs are usually huge and nasty like this.
Alun Harford
Daniel Dyer - 16 Dec 2005 18:59 GMT > Hello > > Can a single method with 1300 lines of code in it ever be justified. > > Madness, sheer madness. Maybe, if it's machine generated, like a JSP. But I can't see an excuse for hand-written code. Bear in mind that the JVM has a limit of 64kb of bytecode per method (which can be hit if you write a complex JSP with lots of custom tags).
I once worked on a system that had a 13,000 line class (people just kept adding methods to it).
Dan.
 Signature Daniel Dyer http://www.dandyer.co.uk
"." - 16 Dec 2005 19:18 GMT > Hello > > Can a single method with 1300 lines of code in it ever be justified. Most the time it is someone who is rather junior or never learned not to do that sort of thing.
By the way, I think the largest I have seen is just over 2600 lines for one method. This was in a utility program and not the main application. It was created by a co-op student who oddly enough the company hired full time when he graduated.
> Madness, sheer madness. Agreed.
 Signature Send e-mail to: darrell dot grainger at utoronto dot ca
Monique Y. Mudama - 16 Dec 2005 19:57 GMT >> Hello >> [quoted text clipped - 8 lines] > application. It was created by a co-op student who oddly enough the > company hired full time when he graduated. I was guilty of this sort of behavior when I got my first internship.
People do learn, especially if someone gives them a chance by telling them how to do better.
Most of my deeper understanding of OO, software engineering, and coding for maintainability happened after I graduated, not before.
 Signature monique
Ask smart questions, get good answers: http://www.catb.org/~esr/faqs/smart-questions.html
"." - 20 Dec 2005 21:53 GMT > >> Hello > >> [quoted text clipped - 13 lines] > People do learn, especially if someone gives them a chance by telling > them how to do better. I forgot to mention, the method was actually around 1500 lines when he finished his internship. No one else wanted to touch it so it became his when he was hired full time. It was at that point it grew to 2600+ lines.
I don't blame him completely. Not only do you have to give them a chance by telling them how to do better (the site has training on refactor, software engineering and OO) but management has to give them a chance to apply the new knowledge.
Statements like, "if you aren't working over 60 hours a week you aren't working hard and if you aren't working hard you are on the list of people to be laid off" really doesn't work.
> Most of my deeper understanding of OO, software engineering, and > coding for maintainability happened after I graduated, not before. Agreed. You just have to be in the right work environment. I see too many graduates going for the big money rather than the nurturing work environments.
> -- > monique > > Ask smart questions, get good answers: > http://www.catb.org/~esr/faqs/smart-questions.html
 Signature Send e-mail to: darrell dot grainger at utoronto dot ca
Andrew McDonagh - 16 Dec 2005 19:40 GMT > Hello > > Can a single method with 1300 lines of code in it ever be justified. > > Madness, sheer madness. No, never in an OO language, and hardly ever in most other paradigm languages.
Large methods in the name of 'performance' is a complete mis-conception & red-herring.
If performance is so critical that multiple private or virtual method calls is a problem, then you'd usually swap into assembler code. Because the actual sum cost of these method calls is far less than the processing done within the large method.
From an OO perspective, a method that is that long would really contain at least an entire additional class, if not more, thats hiding there. Add to it that this long method is probably just one of several methods on a class and we have a god class - a class doing everything (badly - as in hard to see- in this case).
Feel free to post the method - we'll refactor it together to reveal the hidden classes.
As a guide my teams and I use - 7 lines of code per method (cause 7 is an amount that is memorable apparently).
Its a guide not a rule, but once going over that limit we start to look for hidden helper methods or classes. The majority of the time, our methods are around 3 or 5 lines of code.
Andrew
VisionSet - 16 Dec 2005 20:08 GMT > As a guide my teams and I use - 7 lines of code per method (cause 7 is > an amount that is memorable apparently). Was the pre or post 1.5?
If it was before, then perhaps now it should be 4 or 5
1.5 has made a massive impact on my method size, that 'for each' construct is superb!
I think 7 is perhaps a little UTT though if I were to pick some magic number I'd say max of about 10
-- Mike W
Andrew McDonagh - 16 Dec 2005 21:44 GMT >>As a guide my teams and I use - 7 lines of code per method (cause 7 is >>an amount that is memorable apparently). [quoted text clipped - 11 lines] > -- > Mike W either - its only a guideline
"And thirdly, the Code is more what you'd call guidelines than actual rules." -- Captain Barbossa (Pirates of the Caribbean)
I actually aim for single line methods where possible as they usually add 'intent' into the code...
Essentially when ever I find myself writing a comment, I look to see if I can turn that comment into a method name instead. This way, the comment (method name) is likely to stay up more to date than a comment
It makes the code self documenting and exposes code duplication.
Contrived example being....(cause I can't think of a more real example off top of my head)....
public long withdraw(Currency amount) throws InsufficentFundsException() {
// is there sufficient funds for withdrawal? if ( (currentBalance - amount) < overDraftLimit) { throw new InsufficentFundsException();
currentBalance = currentBalance - amount;
}
becomes
public long withdraw(Currency amount) throws InsufficentFundsException() { if ( insufficentFunds(amount) { throw new InsufficentFundsException();
currentBalance = currentBalance - amount;
}
private boolean insufficentFunds(Currency amount) { return (currentBalance - amount) < overDraftLimit; }
Alun Harford - 16 Dec 2005 20:13 GMT >> Hello >> [quoted text clipped - 10 lines] > If performance is so critical that multiple private or virtual method > calls is a problem, then you'd usually swap into assembler code. JIT-compiled Java will almost certainly beat hand-written x86 these days (certainly my x86, and I used to be good at it!), but I'd agree with swapping over to C.
> Because the actual sum cost of these method calls is far less than the > processing done within the large method. How much surely depends on how much processing is actually occuring. A large method could be a complex, but be executed quickly - and the performance overhead of calling methods could make them a bad idea. The best example I can think of is written in C, but the same reasons apply: Cafty is a chess-playing engine written in C. The code it uses to evaluate a board position in its tree is run *very* frequently, and as a result is heavily optimised and very complex. While it is not all one function, it's very close - the evaulatePawns() function is about 1100 line long (some of which is comments, however). (And the code that runs evaluations is about 4000 lines in total) On the other hand, a modern desktop machine can evaluate (and hash, handle in a tree etc) over 2 million positions a second.
Alun Harford
(Note: I am not advocating large methods in general - I'm saying that there are a few obscure situations where they are justified)
Chris Smith - 17 Dec 2005 02:55 GMT > As a guide my teams and I use - 7 lines of code per method (cause 7 is > an amount that is memorable apparently). Sounds like you got that from the "seven plus or minus two" rule, based on George Miller's work on the number of discrete pieces of information that an average person can hold in their short-term memory at any given point in time.
The problem is that this number doesn't really apply to where you're using it. There are several reasons for this:
- It's not the 1950s. Despite the popularity of George Miller's work and its very well-documented procedure, more recent studies have cast great doubt over the truth of his results.
- Lines of code are not discrete pieces of information. They can be less discrete (in that one line is often intimately connected with those around it) or less coherent (i.e., perhaps you should count a line of code that chains several method calls as two
- Lines of code aren't held in short-term memory. The part of the brain exercised by reading code is analytical. The code is sitting right in front of you. Reading code doesn't mean memorizing the lines. Pieces of information that are held in memory (whether short-term or otherwise) are generally elsewhere; the name of the class, where it fits into the system, the names and purposes of instance fields, etc.
- Programmers aren't average people. Software developers work with large numbers of tidbits of information for a living. Writing code as if they are average in this respect is a waste of resources. I wish I remembered the source (more because I'd like to reread it than to cite it... this is just USENET after all), but there's one particularly interesting book out there in which someone repeated George Miller's work with software developers, and found that for the really "natrual" programmers - those for whom writing complex code is easy, the number is more like 50 to 100, dozens of standard deviations above George Miller's original number.
> Its a guide not a rule, but once going over that limit we start to look > for hidden helper methods or classes. The majority of the time, our > methods are around 3 or 5 lines of code. My rule of thumb (stated on this group more than once in the past) is as follows: if there is a strong abstraction, extract a new method. Otherwise, don't bother with the length of your methods. A strong abstraction can be recognized as follows: (a) there is an obvious SHORT name for the new method; and (b) when a programmer who hasn't read that method sees your name, the entire set of inputs and outputs and side- effects of that method are brought to mind. That doesn't exclude the possibility that the programmer would need to know the whole contract, but nothing in that contract should be truly surprising.
Of course, there are also other reasons to write methods (to provide an interface to others, to conform to a specified interface, to eliminate redundancies)... but in terms of shortening methods, it should be done based on the availability of abstractions. Otherwise, people just have to go look up the methods you've extracted to see what they do... and then it IS about short-term memory because they have to memorize that section to use it after returning to your code.
 Signature www.designacourse.com The Easiest Way To Train Anyone... Anywhere.
Chris Smith - Lead Software Developer/Technical Trainer MindIQ Corporation
zero - 17 Dec 2005 13:37 GMT Chris Smith <cdsmith@twu.net> wrote in news:MPG.1e0d09a7ef79046d989c45 @news.altopia.net:
> (a) there is an obvious SHORT > name for the new method so I can't use my handleMouseMovementInJFrameWhilePressingRightMouseButton method?
 Signature Beware the False Authority Syndrome
Roedy Green - 16 Dec 2005 22:14 GMT On Fri, 16 Dec 2005 17:15:30 +0000 (UTC), Duncan <lyallex@diespammersdie.yahoo.co.uk> wrote, quoted or indirectly quoted someone who said :
>Can a single method with 1300 lines of code in it ever be justified. If the code is mechanically generated, e.g. a parser, it does not matter. No human has to understand or maintain it.
If the code is linear or one giant loop, again it does not matter.
If the code does not logically group itself, there is little point in imposing artificial groupings.
On the other end, in FORTH, particularly when you have a FORTH chip, there can be almost no penalty for calling/returning from a method. It makes sense to have extremely short methods 2 or 3 JVM instructions long. When you start to code with tiny methods, a whole new world of reusability and encapsulation opens up. .
 Signature Canadian Mind Products, Roedy Green. http://mindprod.com Java custom programming, consulting and coaching.
Jakob Bieling - 17 Dec 2005 15:04 GMT > long. When you start to code with tiny methods, a whole new world of > reusability and encapsulation opens up. Though coming from C++ and using Java only once in a while for mobile development, I found the above comment of yours very valuable. Worth pointing out :)
Only one question arose in my mind: When having many /many/ tiny methods, you need the big picture of the project, or else you might end up writing duplicate tiny functions. Or you keep spending time trying to find out, if a function for a small task exists or not .. until you do have the big picture, which, if the number of tiny methods is just high enough, might never happen.
regards
 Signature jb
(reply address in rot13, unscramble first)
Chris Smith - 17 Dec 2005 15:35 GMT > Only one question arose in my mind: When having many /many/ tiny > methods, you need the big picture of the project, or else you might end > up writing duplicate tiny functions. Or you keep spending time trying to > find out, if a function for a small task exists or not .. until you do > have the big picture, which, if the number of tiny methods is just high > enough, might never happen. Of course, accidentally duplicating a small method is no worse (actually, easier to fix) than duplicating code to do the same stuff when it does NOT belong to its own method. The difficulty in identifying duplicated code is not unique to any particular method size.
 Signature www.designacourse.com The Easiest Way To Train Anyone... Anywhere.
Chris Smith - Lead Software Developer/Technical Trainer MindIQ Corporation
Chris Smith - 17 Dec 2005 15:55 GMT > Only one question arose in my mind: When having many /many/ tiny > methods, you need the big picture of the project, or else you might end > up writing duplicate tiny functions. Or you keep spending time trying to > find out, if a function for a small task exists or not .. until you do > have the big picture, which, if the number of tiny methods is just high > enough, might never happen. As a side note, if you're really interested in promoting reuse within a project, you could work in Eclipse, where there are several plugins that claim to track duplicated code and let you know about it. Google for "SimScan" and "Duplication Management Framework". I looked at SimScan a while back, and it was interesting... but I ended up deciding that it interfered too much with the normal development process if used regularly... and if not used regularly, it's just a pain.
 Signature www.designacourse.com The Easiest Way To Train Anyone... Anywhere.
Chris Smith - Lead Software Developer/Technical Trainer MindIQ Corporation
Andrew McDonagh - 17 Dec 2005 18:09 GMT >> Only one question arose in my mind: When having many /many/ tiny >>methods, you need the big picture of the project, or else you might end [quoted text clipped - 10 lines] > interfered too much with the normal development process if used > regularly... and if not used regularly, it's just a pain. PMD is very good for this and other violations....
http://pmd.sourceforge.net/
Free MagazinesGet these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...
|
|
|