Technique: Extract Method

If you have a 100+ line Page_Load routine, or any method for that matter, how can you be sure it does (only) what it's supposed to???  There's only one answer: you can't.  No one can.  If you're going to “Code by Coincidence“, then don't leave any evidence that you're the author.  That way, the next poor bastard that has to wade through the code can only blame some anonymous shadow for the trouble.  Realistically, it can be gratifying to refactor the ugly stuff out... but if it's you writing the ugly stuff, and it's really ugly, just stay anonymous, and pick up a good patterns book. Moving on...

One of the easiest and most initial steps to take toward Agile Programming is learning to keep your methods concise and deliberate... and ideally, no more than 10 lines long.  In practice, this easily streches out to 20 lines...  Extract Method is the foremost, and most frequently used technique when working with messy code.  It may be tedious, but once you're done:

1. Your extracted methods will be MUCH easier to read, and much easier (read: possible) to test against.
2. You will probably expose and be able to eliminate duplicate code
3. You will probably be able to push some methods down into base classes, enabling easier code reuse and cleaner inherited classes
4. There won't be a "next poor bastard", and you can proudly tag the code with your name

There is no need to clutter the post up with an example, the one I'm currently working on would take up 2 pages (yeah, a single routine... the Page_Load is just as bad - this post is a result).  Examples are everywhere online, in just about every language imaginable.  Follow the links below for examples of method extracting goodness.

Extract Method

Print | posted on Tuesday, April 05, 2005 2:06 PM


No comments posted yet.
Email (never displayed)
Please add 4 and 2 and type the answer here: