code refactoring

28
Code Refactoring Milan Vukoje www.vukoje.net

Upload: milan-vukoje

Post on 29-Jun-2015

607 views

Category:

Documents


2 download

DESCRIPTION

Presentation about code refactoring and importance of code quality

TRANSCRIPT

Page 1: Code Refactoring

Code Refactoring

Milan Vukojewww.vukoje.net

Page 2: Code Refactoring

Soprex

• SkfOffice2• SkfOffice3• Big5• Quality oriented• We are hiring…

Page 3: Code Refactoring

Agenda

• Why is (clean) code important?• Refactoring (definition and samples)• Tools• When to and when not to refactor?• Summary

Page 4: Code Refactoring

Is code important?

• Is construction relatively mechanical process?• Only activity that’s guaranteed to be done• 50-65% of overall effort• 50-75% of overall errors

Page 5: Code Refactoring

Coding Horror

• Stress• Fear• Cargo cult programming• “Just in case” coding• Unusual software bugs (Heisenbug ,

Mandelbug, Schroedinbug… )

Page 6: Code Refactoring

Code Example

Page 7: Code Refactoring

Technical Debt

– If you can get today's work done today, but you do it in such a way that you can't possibly get tomorrow's work done tomorrow, then you lose. – Kent Beck

• When software organization chooses a design or construction approach that's expedient in the short term but that increases complexity and is more costly in the long term.

• Unintentional and intentional debt

Page 8: Code Refactoring

Refactoring• Refactoring - a change made to the internal structure of software to

make it easier to understand and cheaper to modify without changing its observable behavior.

• Set of rules and techniques for enhancing code while reducing chances for error

• Refactoring: Improving the Design of Existing Code --Martin Fowler

Page 9: Code Refactoring

Composing Methods 1. Extract Method void printOwing(double amount) { printBanner();

//print details System.out.println ("name:" + _name); System.out.println ("amount" + amount); }

void printOwing(double amount) { printBanner(); printDetails(amount); }

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

Page 10: Code Refactoring

Composing Methods 2. Inline Method

int getRating() { return (moreThanFiveLateDeliveries()) ? 2 : 1; } boolean moreThanFiveLateDeliveries() { return _numberOfLateDeliveries > 5; }

int getRating() { return (_numberOfLateDeliveries > 5) ? 2 : 1; }

Page 11: Code Refactoring

Managing temps1. Inline Temp

double basePrice = anOrder.basePrice(); return (basePrice > 1000)

return (anOrder.basePrice() > 1000)

Page 12: Code Refactoring

Managing temps 2. Replace Temp with Query

double basePrice = _quantity * _itemPrice; if (basePrice > 1000) return basePrice * 0.95; else return basePrice * 0.98;

if (basePrice() > 1000) return basePrice() * 0.95; else return basePrice() * 0.98;... double basePrice() { return _quantity * _itemPrice; }

Page 13: Code Refactoring

Managing temps 3. Introduce Explaining Variable

if ( (platform.toUpperCase().indexOf("MAC") > -1) && (browser.toUpperCase().indexOf("IE") > -1) && wasInitialized() && resize > 0 ) { // do something }

final boolean isMacOs = platform.toUpperCase().indexOf("MAC") > -1; final boolean isIEBrowser = browser.toUpperCase().indexOf("IE") > -1; final boolean wasResized = resize > 0;

if (isMacOs && isIEBrowser && wasInitialized() && wasResized) { // do something }

Page 14: Code Refactoring

Simplifying conditionals1. Decompose Conditional

if (date.before (SUMMER_START) || date.after(SUMMER_END)) charge = quantity * _winterRate + _winterServiceCharge; else charge = quantity * _summerRate;

if (notSummer(date)) charge = winterCharge(quantity); else charge = summerCharge (quantity);

Page 15: Code Refactoring

Simplifying conditionals 2. Consolidate Duplicate Fragments

if (isSpecialDeal()) { total = price * 0.95; send(); } else { total = price * 0.98; send(); }

if (isSpecialDeal()) total = price * 0.95; else total = price * 0.98; send();

Page 16: Code Refactoring

Simplifying conditionals 3. Consolidate Conditional Expression

double disabilityAmount() { if (_seniority < 2) return 0; if (_monthsDisabled > 12) return 0; if (_isPartTime) return 0; // compute the disability amount

double disabilityAmount() { if (isNotEligableForDisability()) return 0; // compute the disability amount

Page 17: Code Refactoring

Moving Features between objects

• Replace Method with Method Object• Extract/Inline Class• Pull Up/Down Field/Method• Extract Subclass/ Superclass/Interface• Collapse Hierarchy

Page 18: Code Refactoring

Benefits• Less code – less bugs

• Readable business logic – better business domain understanding

• Self explaining code– Less documentation and faster changes

• Better design – Higher encapsulation and reusability– Cleaner concepts and structure

Page 19: Code Refactoring

Visual Studio 2008

Page 20: Code Refactoring

Need for refactoring • Why change something that works?

– We want programs that are easy to read, that have all logic specified in one and only one place, that do not allow changes to endanger existing behavior, and that allow conditional logic to be expressed as simply as possible. --Kent Beck

• Micro design - clear API and logical structures• Code evolution - Embracing change• Avoiding coding horror by managing complexity• Agile methods (XP, TDD, Scrum)

Page 21: Code Refactoring

When Should You Refactor?• Not having enough time usually is a sign that you need to do some

refactoring. – Martin Fowler

• Refactor all the time in little steps• Refactor when you:– add function– fix a bug – do a code review

• Refactoring and Unit Tests?

Page 22: Code Refactoring

Code smells

• Duplicated Code• Long Method • Large Class• Switch Statements • Lazy Class • Speculative Generality• Temporary Field• Message Chains• …

Page 23: Code Refactoring

When you shouldn’t refactor?Avoid refactoring:• Databases• Published interfaces• Code is so full of bugs that you cannot stabilize it• When you are very close to a deadline• When you are not sure

• Don’t overdo it (no silver bullet)– Perfect is the enemy of good, and good is what we want

Page 24: Code Refactoring

Performance and Refactoring

• Performance optimization = obscure code• Optimized for humans = slower code but

easier tuning• 10% optimized code is usually enough

Page 25: Code Refactoring

What Do I Tell My Manager?

• If the manager is quality oriented, then the thing to stress is the quality aspects.

• Tons of studies show that technical reviews are an important way to reduce bugs and thus speed up development.

• Don't tell!?

Page 26: Code Refactoring

Summary

1. Programming is hard and complex2. (Clean) Code is very important3. Refactoring can help you achieve clean code

and better design.4. Refactoring should be used wisely

1. Don’t over do it (no silver bullet)2. Know when not to refactor3. Changes must not cause new bugs

Page 27: Code Refactoring

Questions?

Milan Vukojewww.vukoje.net

[email protected]

Page 28: Code Refactoring

Molimo vas da popunite ankete!Please fill out the evaluations!

Vaše mišljenje čini osnovu sledeće Sinergije i

omogućava nam da oblikujemo sadržaj u skladu

sa Vašim željama.

Svi posetioci koji popune ankete ulaze u nagradnu

igru

Your opinion forms the next Sinergija conference, and it provides us with the means to shape its content to best

suit you.

All attendees that fill out the evaluations are taking part in drawing of special prizes