Duplicate code smell

From CSSEMediaWiki
(Difference between revisions)
Jump to: navigation, search
m (Reverted edits by Ebybymic (Talk); changed back to last version by Matthew Harward)
 
(12 intermediate revisions by 6 users not shown)
Line 1: Line 1:
Duplicated code is the smelliest of the code smells. The book "Refactoring" by Martin Fowler states that: "If you see the same code structure in more than one place, you can be sure that your program will better if you find a way to unify them." "Refactoring" states that the simplest duplicated code problem is when you have the same expression in two methods of the same class. The best way to fix this bad code smell is to use the Extract Method as shown below.
+
Duplicated code is the smelliest of the code smells. The book ''Refactoring'' [[Martin Fowler 1999]] states that: "If you see the same code structure in more than one place, you can be sure that your program will be better if you find a way to unify them." [[Martin Fowler 1999]] states that the simplest duplicated code problem is when you have the same expression in two methods of the same class.
  
        printOwing() {
+
It is worth noting that occasionally what appears to be duplicated code is actually two different behaviours that will eventually evolve in different directions.
                printBanner();
+
       
+
                //print details
+
                System.out.println ("name: " + _name);
+
                System.out.println ("amount " + getOutstanding());
+
        }
+
  
becomes
+
'''Apply [[Extract Method]]'''
  
        void printOwing() {
 
                printBanner();
 
                printDetails(getOutstanding());
 
        }
 
 
        void printDetails (double outstanding) {
 
                System.out.println ("name: " + _name);
 
                System.out.println ("amount " + outstanding);
 
        }
 
  
 
== See also ==
 
== See also ==
 +
* [[Extract Method]]
 
* [[Don't repeat yourself]]
 
* [[Don't repeat yourself]]
 +
* [[Once and only once]]
 +
* [[Code smells]]
 +
* [[Refactoring]]
 +
 +
{{Template:CodeSmells}}
 +
 +
[[Category:Code smells]]

Latest revision as of 03:10, 25 November 2010

Duplicated code is the smelliest of the code smells. The book Refactoring Martin Fowler 1999 states that: "If you see the same code structure in more than one place, you can be sure that your program will be better if you find a way to unify them." Martin Fowler 1999 states that the simplest duplicated code problem is when you have the same expression in two methods of the same class.

It is worth noting that occasionally what appears to be duplicated code is actually two different behaviours that will eventually evolve in different directions.

Apply Extract Method


See also


Personal tools