developer.com
Search EarthWeb
CodeGuru | Gamelan | Jars | Wireless | Discussions
Navigate developer.com
Architecture & Design  
Database  
Java
Languages & Tools
Microsoft & .NET
Open Source  
Project Management  
Security  
Techniques  
Voice  
Web Services  
Wireless/Mobile
XML  
Technology Jobs  

   Developer.com Webcasts:
  The Impact of Coding Standards and Code Reviews

  Project Management for the Developer

  Defining Your Own Software Development Methodology

  more Webcasts...




See the Winners!


Developer Jobs

Be a Commerce Partner
Promote Your Website
Computer Deals
Rackmount LCD Monitor
KVM over IP
Car Donations
Auto Insurance Quote
Build a Server Rack
Web Design
Hurricane Shutters
Prepaid Phone Card
Server Racks
Disney World Tickets
Boat Donations
Calling Cards

 


Web Devs:
Moonlight as a Game Developer and Win Cool Prizes by Accepting the RIA Run Challenge

Now, your mission--should you choose to accept: Take your shot at gaming stardom if you think you might have what it takes to build a cool RIA game and you could win an Xbox 360 or other fabulous prizes. Hurry! You only have until May 15, 2008 to enter. »

 
Article:
Leveraging Your Flash Development with Silverlight

You're not giving up Flash any time soon (and we don't blame you.) But if you could get your Flash application working in Silverlight, why wouldn't you? We show you the tools and techniques required to have your rockin' Flash application rolled for Silverlight. Learn more here. »

 
Article:
What Does it Take to Build the Best RIA?

With the proliferation of Rich Interactive Application (RIA) platform choices out there, you no longer have to take a one-size-fits-all approach to developing your next RIA application. Knowing the strengths (and weaknesses) of each platform can help you to decide the best RIA for your next application. »

 
Related Article -
Comments on Comments on Comments
Why Pair?: Challenges and Rewards of Pair Programming
Java 5's DelayQueue
Pair Programming Dos and Don'ts
A Brief Introduction to Agile
Writing a Simple Automated Test in FitNesse
Moving Forward with Automated Acceptance Testing
Java 5's BlockingQueue
The Need for Automated Acceptance Testing
Developer News -
SaaS Tool Offers Custom Database Development    May 9, 2008
Microsoft’s Automated Agent: Can We Talk?    May 7, 2008
Borland Finally Sells CodeGear    May 7, 2008
Red Hat Heads For The JON 2.0    May 7, 2008
Free Tech Newsletter -

Project Management Guide: Developing a Web Site. Best Practices, Tips and Strategies. Download Exclusive eBook Now.

Can Refactoring Produce Better Code?
By Jeff Langr

Go to page: 1  2  Next  

One of the more common buzzwords thrown around by programmers and non-programmers over the past several years is "refactoring." Given that most English-language dictionaries don't include the word "refactor," a definition is probably a good idea.

Wikipedia defines refactoring as "any change to a computer program which improves its readability or simplifies its structure without changing its results" (emphasis added). Simply put, refactoring is moving code about to make it more maintainable. Refactoring can involve an operation as simple as renaming a local variable. Or, refactoring can entail complex design manipulations such as converting a switch statement into a polymorphic hierarchy.

Why is refactoring so important? All systems exhibit entropy, and code-based systems are no different. Without concerted efforts to keep them clean, systems will continually degrade. The predominant cost of a system is not in its initial development—it is in the ongoing maintenance of such a system. Continual refactoring is essential to keeping a system easily comprehensible and thus maintainable by its developers.

More formal definitions of refactoring exist. The original use of the term refactoring likely derives from a doctoral paper written by William Opdyke in 1993. This paper demonstrated mathematically how code could be transformed from a state A to another state B while maintaining the same recognized behavior.

How do we know whether or not we've changed "recognized behavior?" In some sense, refactoring almost always does change recognized behavior—most code manipulations change the performance characteristics of code. Most of the time, however, refactoring does not significantly impact performance. Developers can choose to verify performance if necessary.

Performance aside, other ways of baselining behavior include design by contract and unit testing. Design by contract allows programmatic specification of function preconditions, postconditions, and invariants. Unit testing allows behavior to be externally recognized by code that exercises function calls, comparing the results to baselined results.

Most developers today use unit tests instead of design by contract. In the remainder of this article, I'll talk about refactoring in the context of having supporting unit tests.

Once unit tests exist and are all passing, a developer can safely refactor the code. After a developer makes changes to the code, he or she can execute unit tests. If the developer properly refactored the code—he or she did not change the recognized behavior—all the unit tests still pass. If the unit tests fail, the developer knows quickly that he or she made mistakes while changing the code.

Without the existence of good unit tests, refactoring is a high-risk activity. It's very easy to break code by moving it around. The classic programmer's adage is "if it ain't broke, don't fix it!" The result is that most code in most systems isn't kept clean over its lifetime. These systems continually degrade in code and design quality, which makes maintenance costlier with each passing day.

Refactoring: Improving the Design of Existing Code

Martin Fowler's book, Refactoring: Improving the Design of Existing Code, is the bible for the practice. It contains a catalog of refactoring "patterns," or mechanics. The patterns each describe how to transform code from one state to another state.

Many of these catalog patterns represent very simple code transforms. The simplest pattern, named "Extract Method," describes how to break code out into its own method. Some refactoring patterns represent complex code transforms such as "Replace Switch Statement With Polymorphism," an involved transform that's comprised of many smaller refactorings.

Most developers already have an ingrained approach to executing refactorings as simple as Extract Method. Many scoff at the notion of a specific set of detailed steps to accomplish this very common operation. Nonetheless, there is value in the patterns: first, they have names; names allow developers to talk about them concisely. Second, Fowler's steps represent the optimal approach for each refactoring. His steps also support odd conditions that a developer might not have considered.

Although the book's subtitle includes the phrase "Improving the Design," it's important to keep in mind that the refactoring catalog patterns themselves are neither "good" nor "bad." It's up to each developer to determine whether a given code transformation improves the code or makes it worse.

A Sample Refactoring Pattern

Each refactoring pattern is given a name that concisely describes the goal of the refactoring. Take a further look at Extract Method, for which you can view a synopsis at Fowler's Refactoring site.

Each pattern first describes forces, or circumstances, that drive the need for applying the code transform. The force for Extract Method is: "You have a code fragment that can be grouped together." The force is followed by a brief description of the steps to be taken ("Turn the fragment into a method whose name explains the purpose of the method"). The remainder of the pattern is predominantly a detailed set of steps to accomplish the transform. Fowler also lists related refactoring patterns.

A simple example, before and after, is shown in Listings 1 and 2.

Listing 1. Extract Method—Before.

public Date dateDue() {
   // figure out how long the book can be held

   int period = 0;

   switch (book.getType()) {
      case Book.TYPE_BOOK:
         period = Book.BOOK_CHECKOUT_PERIOD;
         break;
      case Book.TYPE_MOVIE:
         period = Book.MOVIE_CHECKOUT_PERIOD;
         break;
      case Book.TYPE_NEW_RELEASE:
         period = Book.NEW_RELEASE_CHECKOUT_PERIOD;
         break;
      default:
         period = Book.BOOK_CHECKOUT_PERIOD;
         break;
   }

   // add period to checked out date

   Calendar calendar = Calendar.getInstance();
   final long msInDay = 1000L * 60 * 60 * 24;
   calendar.setTime(new Date(dateCheckedOut.getTime() +
                             msInDay * period));
   calendar.set(Calendar.HOUR, 0);
   calendar.set(Calendar.MINUTE, 0);
   calendar.set(Calendar.SECOND, 0);
   calendar.set(Calendar.MILLISECOND, 0);
   return calendar.getTime();
}

Listing 2. Extract Method—After.

public Date dateDue() {
   return addDays(dateCheckedOut, getHoldingPeriod());
}

private Date addDays(Date date, int days) {
   Calendar calendar = Calendar.getInstance();
   final long msInDay = 1000L * 60 * 60 * 24;
   calendar.setTime(new Date(date.getTime() + msInDay * days));
   calendar.set(Calendar.HOUR, 0);
   calendar.set(Calendar.MINUTE, 0);
   calendar.set(Calendar.SECOND, 0);
   calendar.set(Calendar.MILLISECOND, 0);
   return calendar.getTime();
}

private int getHoldingPeriod() {
   int period = 0;

   switch (book.getType()) {
      case Book.TYPE_BOOK:
         period = Book.BOOK_CHECKOUT_PERIOD;
         break;
      case Book.TYPE_MOVIE:
         period = Book.MOVIE_CHECKOUT_PERIOD;
         break;
      case Book.TYPE_NEW_RELEASE:
         period = Book.NEW_RELEASE_CHECKOUT_PERIOD;
         break;
      default:
         period = Book.BOOK_CHECKOUT_PERIOD;
         break;
   }
   return period;
}

There are, of course, more changes you could make to improve this code. The addDays method probably belongs on a date utility class. The code in getHoldingPeriod could be better structured. Most importantly, however, you've taken the first step toward improving the code. The dateDue method clearly states the business logic—the high-level policy.

Most refactorings are this small, and should be this small. Having unit tests that run rapidly means that you can incrementally make simple changes to our code. Each incremental change is cheap. If you keep this attitude from day one, refactoring can usually remain inexpensive, and just part of how you craft software. Your software slowly gets better, or at least it doesn't get any worse.

Go to page: 1  2  Next  


Tools:
Add www.developer.com to your favorites
Add www.developer.com to your browser search box
IE 7 | Firefox 2.0 | Firefox 1.5.x
Receive news via our XML/RSS feed


Techniques Archives

Developing Intelligent Communications? Visit the Avaya DevConnect Center on DevX.
Whitepaper: Embeddable Content Platform for OEM's
Five Trends for Application Development & Program Management. Download Complimentary Report Now.
Five Trends for Application Development. Download Your Complimentary Report. Exclusive. Act Now.
Guide to Developing a Web Site. Best Practices, Tips and Strategies. Download Exclusive eBook Now.



JupiterOnlineMedia

internet.comearthweb.comDevx.commediabistro.comGraphics.com

Search:

Jupitermedia Corporation has two divisions: Jupiterimages and JupiterOnlineMedia

Jupitermedia Corporate Info


Legal Notices, Licensing, Reprints, & Permissions, Privacy Policy.

Advertise | Newsletters | Tech Jobs | Shopping | E-mail Offers

Solutions
Whitepapers and eBooks
Microsoft Article: HyperV-The Killer Feature in WinServer ‘08
Avaya Article: How to Feed Data into the Avaya Event Processor
Microsoft Article: Install What You Need with Win Server ‘08
HP eBook: Putting the Green into IT
Whitepaper: HP Integrated Citrix XenServer for HP ProLiant Servers
Intel Go Parallel Portal: Interview with C++ Guru Herb Sutter, Part 1
Intel Go Parallel Portal: Interview with C++ Guru Herb Sutter, Part 2--The Future of Concurrency
Avaya Article: Setting Up a SIP A/S Development Environment
IBM Article: How Cool Is Your Data Center?
Microsoft Article: Managing Virtual Machines with Microsoft System Center
HP eBook: Storage Networking , Part 1
Microsoft Article: Solving Data Center Complexity with Microsoft System Center Configuration Manager 2007
MORE WHITEPAPERS, EBOOKS, AND ARTICLES
Webcasts
Intel Video: Are Multi-core Processors Here to Stay?
On-Demand Webcast: Five Virtualization Trends to Watch
HP Video: Page Cost Calculator
Intel Video: APIs for Parallel Programming
HP Webcast: Storage Is Changing Fast - Be Ready or Be Left Behind
Microsoft Silverlight Video: Creating Fading Controls with Expression Design and Expression Blend 2
MORE WEBCASTS, PODCASTS, AND VIDEOS
Downloads and eKits
Sun Download: Solaris 8 Migration Assistant
Sybase Download: SQL Anywhere Developer Edition
Red Gate Download: SQL Backup Pro and free DBA Best Practices eBook
Red Gate Download: SQL Compare Pro 6
Iron Speed Designer Application Generator
MORE DOWNLOADS, EKITS, AND FREE TRIALS
Tutorials and Demos
How-to-Article: Preparing for Hyper-Threading Technology and Dual Core Technology
eTouch PDF: Conquering the Tyranny of E-Mail and Word Processors
IBM Article: Collaborating in the High-Performance Workplace
HP Demo: StorageWorks EVA4400
Intel Featured Algorhythm: Intel Threading Building Blocks--The Pipeline Class
Microsoft How-to Article: Get Going with Silverlight and Windows Live
MORE TUTORIALS, DEMOS AND STEP-BY-STEP GUIDES