Code Refactoring                Milan Vukoje              www.vukoje.net
Soprex•   SkfOffice2•   SkfOffice3•   Big5•   Quality oriented•   We are hiring…
Agenda•   Why is (clean) code important?•   Refactoring (definition and samples)•   Tools•   When to and when not to refac...
Is code important?•   Is construction relatively mechanical process?•   Only activity that’s guaranteed to be done•   50-6...
Coding Horror•   Stress•   Fear•   Cargo cult programming•   “Just in case” coding•   Unusual software bugs (Heisenbug    ...
Code Example
Technical Debt– If you can get todays work done today, but you do it  in such a way that you cant possibly get tomorrows  ...
Refactoring• Refactoring - a change made to the internal structure of software to  make it easier to understand and cheape...
Composing Methods1. Extract Methodvoid printOwing(double amount) {  printBanner();    //print details    System.out.printl...
Composing Methods2. Inline Methodint getRating() {   return (moreThanFiveLateDeliveries()) ? 2 : 1;}boolean moreThanFiveLa...
Managing temps1. Inline Tempdouble basePrice = anOrder.basePrice();return (basePrice > 1000)return (anOrder.basePrice() > ...
Managing temps2. Replace Temp with Query  double basePrice = _quantity * _itemPrice;  if (basePrice > 1000)      return ba...
Managing temps3. Introduce Explaining Variableif ( (platform.toUpperCase().indexOf("MAC") > -1) &&     (browser.toUpperCas...
Simplifying conditionals1. Decompose Conditional if (date.before (SUMMER_START) || date.after(SUMMER_END))    charge = qua...
Simplifying conditionals2. Consolidate Duplicate Fragments if (isSpecialDeal()) {    total = price * 0.95;    send(); } el...
Simplifying conditionals3. Consolidate Conditional Expressiondouble disabilityAmount() {  if (_seniority < 2) return 0;  i...
Moving Features between objects•   Replace Method with Method Object•   Extract/Inline Class•   Pull Up/Down Field/Method•...
Benefits• Less code  – less bugs• Readable business logic  – better business domain understanding• Self explaining code  –...
Visual Studio 2008
Need for refactoring• Why change something that works?    – We want programs that are easy to read, that have all logic   ...
When Should You Refactor?• Not having enough time usually is a sign that you need to do some  refactoring. – Martin Fowler...
Code smells•   Duplicated Code•   Long Method•   Large Class•   Switch Statements•   Lazy Class•   Speculative Generality•...
When you shouldn’t refactor?Avoid refactoring:• Databases• Published interfaces• Code is so full of bugs that you cannot s...
Performance and Refactoring• Performance optimization = obscure code• Optimized for humans = slower code but  easier tunin...
What Do I Tell My Manager?• If the manager is quality oriented, then the thing to  stress is the quality aspects.• Tons of...
Summary1. Programming is hard and complex2. (Clean) Code is very important3. Refactoring can help you achieve clean code  ...
Questions?                   Milan Vukoje               www.vukoje.net             vukoje@gmail.com
Molimo vas da popunite ankete!      Please fill out the evaluations!Vaše mišljenje čini osnovu    Your opinion forms the n...
Upcoming SlideShare
Loading in …5
×

Code Refactoring

858 views

Published on

Presentation about code refactoring and importance of code quality

0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
858
On SlideShare
0
From Embeds
0
Number of Embeds
10
Actions
Shares
0
Downloads
15
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide
  • Kod je bitan i organizacijama i programerima
  • Heisenbug - bug that disappears or alters its characteristics when an attempt is made to study it.Mandelbug - bug whose causes are so complex that its behavior appears chaotic.Schroedinbug - bug that manifests only after someone reading source code or using the program in an unusual way notices that it never should have worked in the first place.
  • Scrum - make up issuesMS Soprex.SCA.Controls
  • 2 x bolji programerRazdeli knjigePostoji i prevedena knjiga, jako povoljna ali je prevod diskutabilan
  • You have a code fragment that can be grouped together.Turn the fragment into a method whose name explains the purpose of the methodAkose dovoljno dobro uradi komentari postaju suvisni
  • A method&apos;s body is just as clear as its name.Put the method&apos;s body into the body of its callers and remove the method. Sveje relativno, ne postoje uvek ispravna resenjaNe treba biti ekstrmenaNajveca kohezija – jedna klasa jedan metodNajmanje kaplovanje – jedan tip ne zna ni za jedan drugi
  • You have a temp that is assigned to once with a simple expression, and the temp is getting in the way of other refactorings. Replace all references to that temp with the expression. encourage longer methods
  • 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.Performanse?
  • You have a complicated expression.Put the result of the expression, or parts of the expression, in a temporary variable with a name that explains the purpose.Replace Magic Number with Symbolic Constant
  • You have a complicated conditional (if-then-else) statement.Extract methods from the condition, then part, and else parts.
  • The same fragment of code is in all branches of a conditional expression.Move it outside of the expression.
  • You have a sequence of conditional tests with the same result.Combine them into a single conditional expression and extract it.
  • 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.
  • Iako problemi deluju mali, veoma brzo se skupe
  • F12, Shif + F12Class diagramVS 2010Code Rush – better automatization
  • XP – no upfront designTDD – red, green, refactorScrum – make up user stories, educating management about refactoringSvako moze da napise kod koji masina moze da procita, ali ne i kod koji moze da procita covek
  • Databases - (reused structures across applications, problematic data migration)Problematic code - Code has to work mostly correctly before you refactor Rewriting from scratch instead
  • Changes that improve performance usually make the program harder to work with. Refactoring make software go more slowly, but it also makes tuning easier. If you optimize all the code equally, you end up with 90 percent of the optimizations wasted, because you are optimizing code that isn&apos;t run much.
  • Code Refactoring

    1. 1. Code Refactoring Milan Vukoje www.vukoje.net
    2. 2. Soprex• SkfOffice2• SkfOffice3• Big5• Quality oriented• We are hiring…
    3. 3. Agenda• Why is (clean) code important?• Refactoring (definition and samples)• Tools• When to and when not to refactor?• Summary
    4. 4. 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
    5. 5. Coding Horror• Stress• Fear• Cargo cult programming• “Just in case” coding• Unusual software bugs (Heisenbug , Mandelbug, Schroedinbug… )
    6. 6. Code Example
    7. 7. Technical Debt– If you can get todays work done today, but you do it in such a way that you cant possibly get tomorrows work done tomorrow, then you lose. – Kent Beck• When software organization chooses a design or construction approach thats expedient in the short term but that increases complexity and is more costly in the long term.• Unintentional and intentional debt
    8. 8. 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
    9. 9. Composing Methods1. Extract Methodvoid 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);}
    10. 10. Composing Methods2. Inline Methodint getRating() { return (moreThanFiveLateDeliveries()) ? 2 : 1;}boolean moreThanFiveLateDeliveries() { return _numberOfLateDeliveries > 5;}int getRating() { return (_numberOfLateDeliveries > 5) ? 2 : 1;}
    11. 11. Managing temps1. Inline Tempdouble basePrice = anOrder.basePrice();return (basePrice > 1000)return (anOrder.basePrice() > 1000)
    12. 12. Managing temps2. 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; }
    13. 13. Managing temps3. Introduce Explaining Variableif ( (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 }
    14. 14. 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);
    15. 15. Simplifying conditionals2. 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();
    16. 16. Simplifying conditionals3. Consolidate Conditional Expressiondouble disabilityAmount() { if (_seniority < 2) return 0; if (_monthsDisabled > 12) return 0; if (_isPartTime) return 0; // compute the disability amountdouble disabilityAmount() { if (isNotEligableForDisability()) return 0; // compute the disability amount
    17. 17. Moving Features between objects• Replace Method with Method Object• Extract/Inline Class• Pull Up/Down Field/Method• Extract Subclass/ Superclass/Interface• Collapse Hierarchy
    18. 18. 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
    19. 19. Visual Studio 2008
    20. 20. 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)
    21. 21. 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?
    22. 22. Code smells• Duplicated Code• Long Method• Large Class• Switch Statements• Lazy Class• Speculative Generality• Temporary Field• Message Chains• …
    23. 23. 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
    24. 24. Performance and Refactoring• Performance optimization = obscure code• Optimized for humans = slower code but easier tuning• 10% optimized code is usually enough
    25. 25. 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.• Dont tell!?
    26. 26. Summary1. 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 refactor 3. Changes must not cause new bugs
    27. 27. Questions? Milan Vukoje www.vukoje.net vukoje@gmail.com
    28. 28. Molimo vas da popunite ankete! Please fill out the evaluations!Vaše mišljenje čini osnovu Your opinion forms the next sledede Sinergije i Sinergija conference, and it omogudava nam da provides us with the meansoblikujemo sadržaj u skladu to shape its content to best sa Vašim željama. suit you.Svi posetioci koji popune All attendees that fill out the ankete ulaze u nagradnu evaluations are taking part igru in drawing of special prizes

    ×