SlideShare a Scribd company logo
1 of 28
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 refactor?
•   Summary
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
Coding Horror

•   Stress
•   Fear
•   Cargo cult programming
•   “Just in case” coding
•   Unusual software bugs (Heisenbug
    , Mandelbug, Schroedinbug… )
Code Example
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
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
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);
}
Composing Methods
2. Inline Method
int getRating() {
   return (moreThanFiveLateDeliveries()) ? 2 : 1;
}
boolean moreThanFiveLateDeliveries() {
   return _numberOfLateDeliveries > 5;
}



int getRating() {
   return (_numberOfLateDeliveries > 5) ? 2 : 1;
}
Managing temps
1. Inline Temp
double basePrice = anOrder.basePrice();
return (basePrice > 1000)




return (anOrder.basePrice() > 1000)
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;
   }
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
 }
Simplifying conditionals
1. 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);
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();
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
Moving Features between objects
•   Replace Method with Method Object
•   Extract/Inline Class
•   Pull Up/Down Field/Method
•   Extract Subclass/ Superclass/Interface
•   Collapse Hierarchy
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
Visual Studio 2008
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)
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?
Code smells
•   Duplicated Code
•   Long Method
•   Large Class
•   Switch Statements
•   Lazy Class
•   Speculative Generality
•   Temporary Field
•   Message Chains
•   …
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
Performance and Refactoring
• Performance optimization = obscure code
• Optimized for humans = slower code but
  easier tuning
• 10% optimized code is usually enough
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!?
Summary
1. Programming is hard and complex
2. (Clean) Code is very important
3. 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
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 next
     sledede Sinergije i       Sinergija conference, and it
    omogudava nam da           provides us with the means
oblikujemo 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

More Related Content

What's hot

Postman: An Introduction for Testers
Postman: An Introduction for TestersPostman: An Introduction for Testers
Postman: An Introduction for TestersPostman
 
Agile Apps with App Engine
Agile Apps with App EngineAgile Apps with App Engine
Agile Apps with App EngineCalvin Cheng
 
Hidden Treasure - TestComplete Script Extensions
Hidden Treasure - TestComplete Script ExtensionsHidden Treasure - TestComplete Script Extensions
Hidden Treasure - TestComplete Script ExtensionsSmartBear
 
Advantages of Rails Framework
Advantages of Rails FrameworkAdvantages of Rails Framework
Advantages of Rails FrameworkSathish Mariappan
 
Automate test-oim
Automate test-oimAutomate test-oim
Automate test-oimOim Trust
 
Automation testing of REST endpoints in a less coded way
Automation testing of REST endpoints in a less coded wayAutomation testing of REST endpoints in a less coded way
Automation testing of REST endpoints in a less coded wayAleh Struneuski
 
Automated testing in javascript
Automated testing in javascriptAutomated testing in javascript
Automated testing in javascriptMichael Yagudaev
 
Sencha Roadshow 2017: What's New in Sencha Test
Sencha Roadshow 2017: What's New in Sencha TestSencha Roadshow 2017: What's New in Sencha Test
Sencha Roadshow 2017: What's New in Sencha TestSencha
 
Sencha Roadshow 2017: Sencha Upgrades - The Good. The Bad. The Ugly - Eva Luc...
Sencha Roadshow 2017: Sencha Upgrades - The Good. The Bad. The Ugly - Eva Luc...Sencha Roadshow 2017: Sencha Upgrades - The Good. The Bad. The Ugly - Eva Luc...
Sencha Roadshow 2017: Sencha Upgrades - The Good. The Bad. The Ugly - Eva Luc...Sencha
 
Introduction to Bdd and cucumber
Introduction to Bdd and cucumberIntroduction to Bdd and cucumber
Introduction to Bdd and cucumberNibu Baby
 
Accelerate Quality with Postman - Basics
Accelerate Quality with Postman - BasicsAccelerate Quality with Postman - Basics
Accelerate Quality with Postman - BasicsKnoldus Inc.
 
Useful practices of creation automatic tests by using cucumber jvm
Useful practices of creation automatic tests by using cucumber jvmUseful practices of creation automatic tests by using cucumber jvm
Useful practices of creation automatic tests by using cucumber jvmAnton Shapin
 
QA Challenge Accepted 4.0 - Cypress vs. Selenium
QA Challenge Accepted 4.0 - Cypress vs. SeleniumQA Challenge Accepted 4.0 - Cypress vs. Selenium
QA Challenge Accepted 4.0 - Cypress vs. SeleniumLyudmil Latinov
 
Lessons learned: Choosing your documentation system
Lessons learned: Choosing your documentation systemLessons learned: Choosing your documentation system
Lessons learned: Choosing your documentation systemPronovix
 
Rapid With Spring Roo
Rapid With Spring RooRapid With Spring Roo
Rapid With Spring RooMorten Lileng
 
Angular Libraries & NPM
 Angular Libraries & NPM Angular Libraries & NPM
Angular Libraries & NPMKnoldus Inc.
 
The Python in the Apple
The Python in the AppleThe Python in the Apple
The Python in the ApplezeroSteiner
 

What's hot (20)

Test Automation Framework with BDD and Cucumber
Test Automation Framework with BDD and CucumberTest Automation Framework with BDD and Cucumber
Test Automation Framework with BDD and Cucumber
 
Postman: An Introduction for Testers
Postman: An Introduction for TestersPostman: An Introduction for Testers
Postman: An Introduction for Testers
 
Agile Apps with App Engine
Agile Apps with App EngineAgile Apps with App Engine
Agile Apps with App Engine
 
Hidden Treasure - TestComplete Script Extensions
Hidden Treasure - TestComplete Script ExtensionsHidden Treasure - TestComplete Script Extensions
Hidden Treasure - TestComplete Script Extensions
 
Advantages of Rails Framework
Advantages of Rails FrameworkAdvantages of Rails Framework
Advantages of Rails Framework
 
Automate test-oim
Automate test-oimAutomate test-oim
Automate test-oim
 
Automation testing of REST endpoints in a less coded way
Automation testing of REST endpoints in a less coded wayAutomation testing of REST endpoints in a less coded way
Automation testing of REST endpoints in a less coded way
 
Automated testing in javascript
Automated testing in javascriptAutomated testing in javascript
Automated testing in javascript
 
SGCE 2015 REST APIs
SGCE 2015 REST APIsSGCE 2015 REST APIs
SGCE 2015 REST APIs
 
Sencha Roadshow 2017: What's New in Sencha Test
Sencha Roadshow 2017: What's New in Sencha TestSencha Roadshow 2017: What's New in Sencha Test
Sencha Roadshow 2017: What's New in Sencha Test
 
Sencha Roadshow 2017: Sencha Upgrades - The Good. The Bad. The Ugly - Eva Luc...
Sencha Roadshow 2017: Sencha Upgrades - The Good. The Bad. The Ugly - Eva Luc...Sencha Roadshow 2017: Sencha Upgrades - The Good. The Bad. The Ugly - Eva Luc...
Sencha Roadshow 2017: Sencha Upgrades - The Good. The Bad. The Ugly - Eva Luc...
 
Introduction to Bdd and cucumber
Introduction to Bdd and cucumberIntroduction to Bdd and cucumber
Introduction to Bdd and cucumber
 
Accelerate Quality with Postman - Basics
Accelerate Quality with Postman - BasicsAccelerate Quality with Postman - Basics
Accelerate Quality with Postman - Basics
 
Useful practices of creation automatic tests by using cucumber jvm
Useful practices of creation automatic tests by using cucumber jvmUseful practices of creation automatic tests by using cucumber jvm
Useful practices of creation automatic tests by using cucumber jvm
 
QA Challenge Accepted 4.0 - Cypress vs. Selenium
QA Challenge Accepted 4.0 - Cypress vs. SeleniumQA Challenge Accepted 4.0 - Cypress vs. Selenium
QA Challenge Accepted 4.0 - Cypress vs. Selenium
 
Lessons learned: Choosing your documentation system
Lessons learned: Choosing your documentation systemLessons learned: Choosing your documentation system
Lessons learned: Choosing your documentation system
 
Rapid With Spring Roo
Rapid With Spring RooRapid With Spring Roo
Rapid With Spring Roo
 
Angular Libraries & NPM
 Angular Libraries & NPM Angular Libraries & NPM
Angular Libraries & NPM
 
Automated Testing in DevOps
Automated Testing in DevOpsAutomated Testing in DevOps
Automated Testing in DevOps
 
The Python in the Apple
The Python in the AppleThe Python in the Apple
The Python in the Apple
 

Similar to Code Refactoring

Technical debt management strategies
Technical debt management strategiesTechnical debt management strategies
Technical debt management strategiesRaquel Pau
 
“One man” development process model
“One man” development process model“One man” development process model
“One man” development process modelSilicon Straits
 
Developing a Culture of Quality Code (Midwest PHP 2020)
Developing a Culture of Quality Code (Midwest PHP 2020)Developing a Culture of Quality Code (Midwest PHP 2020)
Developing a Culture of Quality Code (Midwest PHP 2020)Scott Keck-Warren
 
Improving Code Quality Through Effective Review Process
Improving Code Quality Through Effective  Review ProcessImproving Code Quality Through Effective  Review Process
Improving Code Quality Through Effective Review ProcessDr. Syed Hassan Amin
 
Continuous delivery @wcap 5-09-2013
Continuous delivery   @wcap 5-09-2013Continuous delivery   @wcap 5-09-2013
Continuous delivery @wcap 5-09-2013David Funaro
 
Code Review
Code ReviewCode Review
Code ReviewRavi Raj
 
Introducing systems analysis, design & development Concepts
Introducing systems analysis, design & development ConceptsIntroducing systems analysis, design & development Concepts
Introducing systems analysis, design & development ConceptsShafiul Azam Chowdhury
 
A modern architecturereview–usingcodereviewtools-ver-3.5
A modern architecturereview–usingcodereviewtools-ver-3.5A modern architecturereview–usingcodereviewtools-ver-3.5
A modern architecturereview–usingcodereviewtools-ver-3.5SSW
 
How I Learned to Stop Worrying and Love Legacy Code - Ox:Agile 2018
How I Learned to Stop Worrying and Love Legacy Code - Ox:Agile 2018How I Learned to Stop Worrying and Love Legacy Code - Ox:Agile 2018
How I Learned to Stop Worrying and Love Legacy Code - Ox:Agile 2018Mike Harris
 
Viktor Turskyi "Effective NodeJS Application Development"
Viktor Turskyi "Effective NodeJS Application Development"Viktor Turskyi "Effective NodeJS Application Development"
Viktor Turskyi "Effective NodeJS Application Development"Fwdays
 
TDD and Related Techniques for Non Developers (2012)
TDD and Related Techniques for Non Developers (2012)TDD and Related Techniques for Non Developers (2012)
TDD and Related Techniques for Non Developers (2012)Peter Kofler
 
MODEL-DRIVEN ENGINEERING (MDE) in Practice
MODEL-DRIVEN ENGINEERING (MDE) in PracticeMODEL-DRIVEN ENGINEERING (MDE) in Practice
MODEL-DRIVEN ENGINEERING (MDE) in PracticeHussein Alshkhir
 
Extreme Programming Talk Wise Consulting Www.Talkwiseconsulting
Extreme  Programming    Talk Wise  Consulting   Www.TalkwiseconsultingExtreme  Programming    Talk Wise  Consulting   Www.Talkwiseconsulting
Extreme Programming Talk Wise Consulting Www.Talkwiseconsultingtalkwiseone
 
Extreme programming talk wise consulting - www.talkwiseconsulting
Extreme programming   talk wise consulting - www.talkwiseconsultingExtreme programming   talk wise consulting - www.talkwiseconsulting
Extreme programming talk wise consulting - www.talkwiseconsultingtalkwiseone
 
Advanced web application architecture - Talk
Advanced web application architecture - TalkAdvanced web application architecture - Talk
Advanced web application architecture - TalkMatthias Noback
 

Similar to Code Refactoring (20)

Technical debt management strategies
Technical debt management strategiesTechnical debt management strategies
Technical debt management strategies
 
“One man” development process model
“One man” development process model“One man” development process model
“One man” development process model
 
Raising the Bar
Raising the BarRaising the Bar
Raising the Bar
 
Developing a Culture of Quality Code (Midwest PHP 2020)
Developing a Culture of Quality Code (Midwest PHP 2020)Developing a Culture of Quality Code (Midwest PHP 2020)
Developing a Culture of Quality Code (Midwest PHP 2020)
 
Improving Code Quality Through Effective Review Process
Improving Code Quality Through Effective  Review ProcessImproving Code Quality Through Effective  Review Process
Improving Code Quality Through Effective Review Process
 
Continuous delivery @wcap 5-09-2013
Continuous delivery   @wcap 5-09-2013Continuous delivery   @wcap 5-09-2013
Continuous delivery @wcap 5-09-2013
 
Code Review
Code ReviewCode Review
Code Review
 
Introducing systems analysis, design & development Concepts
Introducing systems analysis, design & development ConceptsIntroducing systems analysis, design & development Concepts
Introducing systems analysis, design & development Concepts
 
A modern architecturereview–usingcodereviewtools-ver-3.5
A modern architecturereview–usingcodereviewtools-ver-3.5A modern architecturereview–usingcodereviewtools-ver-3.5
A modern architecturereview–usingcodereviewtools-ver-3.5
 
How I Learned to Stop Worrying and Love Legacy Code - Ox:Agile 2018
How I Learned to Stop Worrying and Love Legacy Code - Ox:Agile 2018How I Learned to Stop Worrying and Love Legacy Code - Ox:Agile 2018
How I Learned to Stop Worrying and Love Legacy Code - Ox:Agile 2018
 
Viktor Turskyi "Effective NodeJS Application Development"
Viktor Turskyi "Effective NodeJS Application Development"Viktor Turskyi "Effective NodeJS Application Development"
Viktor Turskyi "Effective NodeJS Application Development"
 
Tdd is not about testing
Tdd is not about testingTdd is not about testing
Tdd is not about testing
 
TDD and Related Techniques for Non Developers (2012)
TDD and Related Techniques for Non Developers (2012)TDD and Related Techniques for Non Developers (2012)
TDD and Related Techniques for Non Developers (2012)
 
MODEL-DRIVEN ENGINEERING (MDE) in Practice
MODEL-DRIVEN ENGINEERING (MDE) in PracticeMODEL-DRIVEN ENGINEERING (MDE) in Practice
MODEL-DRIVEN ENGINEERING (MDE) in Practice
 
Tech talks#6: Code Refactoring
Tech talks#6: Code RefactoringTech talks#6: Code Refactoring
Tech talks#6: Code Refactoring
 
Extreme Programming Talk Wise Consulting Www.Talkwiseconsulting
Extreme  Programming    Talk Wise  Consulting   Www.TalkwiseconsultingExtreme  Programming    Talk Wise  Consulting   Www.Talkwiseconsulting
Extreme Programming Talk Wise Consulting Www.Talkwiseconsulting
 
Extreme programming talk wise consulting - www.talkwiseconsulting
Extreme programming   talk wise consulting - www.talkwiseconsultingExtreme programming   talk wise consulting - www.talkwiseconsulting
Extreme programming talk wise consulting - www.talkwiseconsulting
 
Usable Software Design
Usable Software DesignUsable Software Design
Usable Software Design
 
Advanced web application architecture - Talk
Advanced web application architecture - TalkAdvanced web application architecture - Talk
Advanced web application architecture - Talk
 
Agile
AgileAgile
Agile
 

Code Refactoring

  • 1. Code Refactoring Milan Vukoje www.vukoje.net
  • 2. Soprex • SkfOffice2 • SkfOffice3 • Big5 • Quality oriented • We are hiring…
  • 3. Agenda • Why is (clean) code important? • Refactoring (definition and samples) • Tools • When to and when not to refactor? • Summary
  • 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. Coding Horror • Stress • Fear • Cargo cult programming • “Just in case” coding • Unusual software bugs (Heisenbug , Mandelbug, Schroedinbug… )
  • 7. 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
  • 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. 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); }
  • 10. Composing Methods 2. Inline Method int getRating() { return (moreThanFiveLateDeliveries()) ? 2 : 1; } boolean moreThanFiveLateDeliveries() { return _numberOfLateDeliveries > 5; } int getRating() { return (_numberOfLateDeliveries > 5) ? 2 : 1; }
  • 11. Managing temps 1. Inline Temp double basePrice = anOrder.basePrice(); return (basePrice > 1000) return (anOrder.basePrice() > 1000)
  • 12. 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; }
  • 13. 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 }
  • 14. Simplifying conditionals 1. 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. 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();
  • 16. 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
  • 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. 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
  • 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. 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. Code smells • Duplicated Code • Long Method • Large Class • Switch Statements • Lazy Class • Speculative Generality • Temporary Field • Message Chains • …
  • 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. Performance and Refactoring • Performance optimization = obscure code • Optimized for humans = slower code but easier tuning • 10% optimized code is usually enough
  • 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. • Don't tell!?
  • 26. Summary 1. Programming is hard and complex 2. (Clean) Code is very important 3. 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. Questions? Milan Vukoje www.vukoje.net vukoje@gmail.com
  • 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 means oblikujemo 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

Editor's Notes

  1. Kod je bitan i organizacijama i programerima
  2. 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.
  3. Scrum - make up issuesMS Soprex.SCA.Controls
  4. 2 x bolji programerRazdeli knjigePostoji i prevedena knjiga, jako povoljna ali je prevod diskutabilan
  5. 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
  6. 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
  7. 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
  8. 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?
  9. 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
  10. You have a complicated conditional (if-then-else) statement.Extract methods from the condition, then part, and else parts.
  11. The same fragment of code is in all branches of a conditional expression.Move it outside of the expression.
  12. You have a sequence of conditional tests with the same result.Combine them into a single conditional expression and extract it.
  13. 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.
  14. Iako problemi deluju mali, veoma brzo se skupe
  15. F12, Shif + F12Class diagramVS 2010Code Rush – better automatization
  16. 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
  17. Databases - (reused structures across applications, problematic data migration)Problematic code - Code has to work mostly correctly before you refactor Rewriting from scratch instead
  18. 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.