bad smell in codes 1

49
Bad smell in codes – Part 1 If it stinks change it. Presented By: Fuad Bin Omar Rashed Kibria [email protected] [email protected] www.code71.com www.code71.com

Upload: fuad-omar

Post on 10-May-2015

4.400 views

Category:

Technology


1 download

DESCRIPTION

This will help to understand the scope and ways to refactor you code.

TRANSCRIPT

Page 1: Bad Smell In Codes 1

Bad smell in codes – Part 1If it stinks change it.

Presented By:Fuad Bin Omar Rashed Kibria

[email protected] [email protected]

www.code71.com www.code71.com

Page 2: Bad Smell In Codes 1

Smells to be covered

•Duplicated code•Long method•Long parameter list•Divergent change•Shotgun surgery

Page 3: Bad Smell In Codes 1

Duplicated Code

Smell• Same code structure in more than

one place.

RefactorExtract method and invoke it from

both the places.

Page 4: Bad Smell In Codes 1

Extract Method

• You have a code fragment that can be grouped together.

• Turn the fragment into a method whose name explains the purpose of the method.

Page 5: Bad Smell In Codes 1

Extract Method (Contd.)

void printOwing()

{

printBanner();

//print details

System.out.println ("name: " + _name);

System.out.println ("amount " + getOutstanding());

}

Page 6: Bad Smell In Codes 1

Extract Method (Contd.)

void printOwing() { printBanner();printDetails(getOutstanding()); } void printDetails (double outstanding) { System.out.println ("name: " + _name);System.out.println ("amount " + outstanding);

}

Page 7: Bad Smell In Codes 1

Duplicated Code

Smell • same expression in two sibling

subclassesRefactor• Extract method in both classes.• Pull up field.

Page 8: Bad Smell In Codes 1

Pull Up Field

• Two subclasses have the same field.• Move the field to the superclass.

Page 9: Bad Smell In Codes 1

Pull Up Field (Contd.)

Page 10: Bad Smell In Codes 1

Duplicated Code

Smell• Code is similar but not the sameRefactor:• Use Extract Method toseparate the similar bits from the

different bits. • Use Form Template Method.

Page 11: Bad Smell In Codes 1

Form template method

• You have two methods in subclasses that perform similar steps in the same order, yet the steps are different.

• Get the steps into methods with the same signature, so that the original methods become the same. Then you can pull them up.

Page 12: Bad Smell In Codes 1

Form Template Method (Contd.)

Page 13: Bad Smell In Codes 1

Duplicated Code

Smell• Methods do the same thing with a

different algorithm Refactor:• Choose the clearer of the two

algorithms Use • Use Substitute Algorithm.

Page 14: Bad Smell In Codes 1

Substitute Algorithm

• You want to replace an algorithm with one that is clearer.

• Replace the body of the method with the new algorithm.

Page 15: Bad Smell In Codes 1

Substitute Algorithm(Contd.)

String foundPerson(String[] people)

{

for (int i = 0; i < people.length; i++)

{

if (people[i].equals ("Don")){ return "Don"; }

if (people[i].equals ("John")){ return "John"; }

if (people[i].equals ("Kent")){ return "Kent"; }

}

return "";

}

Page 16: Bad Smell In Codes 1

Substitute Algorithm (Contd.)

String foundPerson(String[] people)

{

List candidates = Arrays.asList(new String[] {"Don", "John", "Kent"});

for (int i=0; i<people.length; i++)

if (candidates.contains(people[i]))

return people[i]; return "";

}

Page 17: Bad Smell In Codes 1

Duplicated Code

Smell

• Duplicated code in two unrelated class.Refactor:

• Use Extract Class in one class.

• Use the new component to the other.

• Decide where the method makes sense.

Page 18: Bad Smell In Codes 1

Extract Class

• You have one class doing work that should be done by two.

• Create a new class and move the relevant fields and methods from the old class into the new class.

Page 19: Bad Smell In Codes 1

Extract Class (Contd.)

Page 20: Bad Smell In Codes 1

Long method

• Object program having short methods live best and longest.

• Little methods are the most valuable.• Longer methods are difficult to

understand.

Page 21: Bad Smell In Codes 1

Long method

• Give methods a good name.• Whenever you feel the need to comment

something make it a method.– Group of lines– Even if it is a single line– Even if method call is longer than code itself.–Method length is not the key here.–What the method does and how it does it is

important.

Page 22: Bad Smell In Codes 1

Long method

• Extract Method

Page 23: Bad Smell In Codes 1

Long method

SmellUse of temporary variable.RefactorReplace temp with query.

Page 24: Bad Smell In Codes 1

Replace temp with query

• You are using a temporary variable to hold the result of an expression.

• Extract the expression into a method. Replace all references to the temp with the expression. The new method can then be used in other methods

Page 25: Bad Smell In Codes 1

Replace temp with query

double basePrice = _quantity * _itemPrice;

if (basePrice > 1000)

return basePrice * 0.95;

else

return basePrice * 0.98;

Page 26: Bad Smell In Codes 1

Replace temp with query

if (basePrice() > 1000)

return basePrice() * 0.95;

else return basePrice() * 0.98;

...

...

double basePrice()

{

return _quantity * _itemPrice;

}

Page 27: Bad Smell In Codes 1

Long method

SmellMethods with long list of parameters.

RefactorIntroduce Parameter ObjectPreserve Whole ObjectMethod with method Object

Page 28: Bad Smell In Codes 1

Introduce Parameter Object

• You have a group of parameters that naturally go together.

• Replace them with an object.

Page 29: Bad Smell In Codes 1

Introduce Parameter Object

Page 30: Bad Smell In Codes 1

Preserve whole object

• You are getting several values from an object and passing these values as parameters in a method call.

• Send the whole object instead.

Page 31: Bad Smell In Codes 1

Preserve whole object

int low = daysTempRange().getLow();

int high = daysTempRange().getHigh(); withinPlan = plan.withinRange(low, high);

Page 32: Bad Smell In Codes 1

Preserve whole object

withinPlan = plan.withinRange(daysTempRange());

Page 33: Bad Smell In Codes 1

Replace method with method object

• You have a long method that uses local variables in such a way that you cannot apply Extract Method

• Turn the method into its own object so that all the local variables become fields on that object. You can then decompose the method into other methods on the same object.

Page 34: Bad Smell In Codes 1

Replace method with method object

class Order

{

double price()

{

double primaryBasePrice;

double secondaryBasePrice;

double tertiaryBasePrice;

// long computation;

}

}

Page 35: Bad Smell In Codes 1

Replace method with method object

Page 36: Bad Smell In Codes 1

Long method

Smell • Too many conditions and loopsRefactor• With loops, extract the loop and the

code within the loop into its own method.

• Use Decompose Conditional.

Page 37: Bad Smell In Codes 1

Decompose Conditional

• You have a complicated conditional (if-then-else) statement.

• Extract methods from the condition, then part, and else parts

Page 38: Bad Smell In Codes 1

Decompose Conditionalif (date.before (SUMMER_START) || date.after(SUMMER_END))

charge = quantity * _winterRate + _winterServiceCharge;

else

charge = quantity * _summerRate;

Page 39: Bad Smell In Codes 1

Decompose Conditionalif (notSummer(date))

charge = winterCharge(quantity);

else

charge = summerCharge (quantity);

Page 40: Bad Smell In Codes 1

Long Parameter List

Smell

• A method call requires passing long list of parameters.

Refactor

• Use Replace Parameter with Method, Preserve whole object or Introduce Parameter Object.

Page 41: Bad Smell In Codes 1

Replace Parameter With Method

int basePrice = _quantity * _itemPrice; discountLevel = getDiscountLevel(); double finalPrice = discountedPrice (basePrice,discountLevel);

int basePrice = _quantity * _itemPrice; double finalPrice = discountedPrice(basePrice);

Page 42: Bad Smell In Codes 1

Divergent Change

Smell

• One class is commonly changed in different ways for different reasons.

Refactor

• Use Extract class by identifying everything that changes for a particular cause and put them all together.

Page 43: Bad Smell In Codes 1

Shotgun SurgerySmell• A small changes in the code force changes in different classes.

Refactor• Use Move Method and Move Field to put all the changes into

a single class.• If no current class looks like a good candidate, create one.• use Inline Class to bring a whole bunch of behavior together.

Page 44: Bad Smell In Codes 1

Move Method

• A method is, or will be, using or used by more features of another class than the class on which it is defined.

• Create a new method with a similar body in the class it uses most. Either turn the old method into a simple delegation, or remove it altogether.

Page 45: Bad Smell In Codes 1

Introduce Parameter Object

Page 46: Bad Smell In Codes 1

Move Field

• A field is, or will be, used by another class more than the class on which it is defined.

• Create a new field in the target class, and change all its users.

Page 47: Bad Smell In Codes 1

Introduce Parameter Object

Page 48: Bad Smell In Codes 1

To be continued..

Page 49: Bad Smell In Codes 1

References

1. Refactoring: Improving the Design of Existing Code By Martin Fowler, Kent Beck, John Brant, William Opdyke, Don Roberts

2. www.refactoring.com