Monday, August 04, 2008
500 lines of code in one method? uh... U R DOING IT WRONG!

Long methods are a code smell. And a loud one at that. Methods should be focused on doing ONE thing. That thing can be simple or complex, but inner complexity should be refactored out into other (small) methods, keeping them each small and focused on a single task. A method with 4 nested levels of for/foreach/while statements is just so wrong in so many ways... Keep it simple. Keep it straightforward. Did I mention keep it simple?

Jeremy Miller posted a nice article a while back about short methods, and Ward Cunningham has another on C2 that Jeremy references.
We definitely need a Visual Studio plug-in to turn the background yellow when a method exceeds 20 lines, and turn red when it goes over 40 lines...

Here is a simple example. Code by intent means writing code by declaring what it does by well named (and usually long-named) methods. This method is only three lines long, but it conveys that there are two steps to be done, the second with the result of the first. This should be clear to anyone reading it. Further, the XML comment summary (missing from this example) should provide the reader with any information needed not conveyed with the title.
public void DoOneThing()
{
int n = 0;
n = DoStep1ReturnNumber(n);
DoStep2WithResultOfStep1(n);
}

private void DoStep1ReturnNumber(int number)
{
// simple method } private void DoStep2WithResultOfStep1(int number)
{
// more simple stuff }

Seriously, if there is something out there already that does this, please let me know! If not, I am going to have to write one...

C#
Monday, August 04, 2008 11:41:20 AM (Pacific Standard Time, UTC-08:00)  #    Comments [0]  | 
© Copyright 2008, John E. Boal