Refactoring MSO 08/09, WP. What is refactoring ?  Refactoring is the act of transforming the internal structure of a program while preserving its observable.

Slides:



Advertisements
Similar presentations
Programming Paradigms and languages
Advertisements

Clean code. Motivation Total cost = the cost of developing + maintenance cost Maintenance cost = cost of understanding + cost of changes + cost of testing.
Refactoring and Code Smells
Refactoring Overview  What is refactoring?  What are four good reasons to refactor?  When should you refactor?  What is a bad smell (relative to refactoring.
Software Construction and Evolution - CSSE 375 Bad Smells in Code Shawn Bohner & Steve Chenoweth.
1 Software Maintenance and Evolution CSSE 575: Session 1, Part 4 Even more Bad Smells in Code Steve Chenoweth Office Phone: (812) Cell: (937)
1 Programming for Engineers in Python Autumn Lecture 5: Object Oriented Programming.
Introduction to Refactoring Excerpted from ‘What is Refactoring?’ by William C. Wake and Refactoring: Improving the Design of Existing Code by Martin Fowler.
George Blank University Lecturer. REFACTORING Improving the Design of Existing Code Supplement to Ian Sommerville, Software Engineering, Chapter 20 Prepared.
XP and Refactoring David Talby. Development Methodologies The Software Crisis – 84% of software projects are not on time – 31% of software projects never.
25-Jun-15 Refactoring III. General philosophy A refactoring is just a way of rearranging code Refactorings are used to solve problems If there’s no problem,
REFACTORING Improving the Design of Existing Code Atakan Şimşek e
13-Jul-15 Refactoring II. Books Design Patterns is the classic book by Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides Basically a catalog.
Maintenance Refactoring and Code Smells. Where are we? Over the semester we have talked about Software Engineering. The overall goal of software engineering.
REFACTORING Lecture 4. Definition Refactoring is a process of changing the internal structure of the program, not affecting its external behavior and.
Advanced Programing practices
Software Refactoring Part I: Introduction Bartosz Walter Advanced Object-Oriented Design Lecture 5.
Designing classes How to write classes in a way that they are easily understandable, maintainable and reusable 3.0.
Sadegh Aliakbary Sharif University of Technology Spring 2012.
CSC 395 – Software Engineering Lecture 12: Reusability –or– Programming was Bjarne Again.
Partitioning and Layering Fundamentals. The Basic Problem Change is a fact of life RequirementsTechnologies Bug Fixes Software Must Adapt.
Refactoring - A disciplined approach to rework for better design.
Software Engineering 1 Object-oriented Analysis and Design Chap 21 Test-Driven Development and Refactoring.
Refactoring Improving the structure of existing code Refactoring1.
17-Oct-15 Refactoring. 2 Refactoring is: restructuring (rearranging) code......in a series of small, semantics-preserving transformations (i.e. the code.
Testing. 2 Overview Testing and debugging are important activities in software development. Techniques and tools are introduced. Material borrowed here.
Refactoring (continued) Source: "Refactoring: Improving the Design of Existing Code", Martin Fowler.
Refactoring1 Refactoring DEPARTMENT OF COMPUTER SCIENCE AND SOFTWARE ENGINEERING CONCORDIA UNIVERSITY February 6, 2009.
Best Practices. Contents Bad Practices Good Practices.
Refactoring1 Improving the structure of existing code.
Alcatel-Lucent CDC Workshop, Coaching & Knowledge Transfer Coding.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
Incremental Design Why incremental design? Goal of incremental design Tools for incremental design  UML diagrams  Design principles  Design patterns.
Software Engineering CS3003 Lecture 4 Code bad smells and refactoring.
Refactoring. Refactoring Overview  What is refactoring?  What are four good reasons to refactor?  When should you refactor?  What is a bad smell (relative.
Refactoring 2. Admin Blackboard Quiz Acknowledgements Material in this presentation was drawn from Martin Fowler, Refactoring: Improving the Design of.
Refactoring II Dealing with Polymorphism. Switch in Rental Switches on Movie! class Rental … public double getCharge() { double result = 0; switch (getMovie().getPriceCode()){
Module 3. Smells Between Classes Course: Refactoring.
CS5103 Software Engineering Lecture 02 More on Software Process Models.
Sadegh Aliakbary Sharif University of Technology Spring 2011.
ANU COMP2110 Software Design in 2003 Lecture 10Slide 1 COMP2110 Software Design in 2004 Lecture 12 Documenting Detailed Design How to write down detailed.
Refactoring1 Improving the structure of existing code.
CSSE 375 Organizing Data – Part 1 Shawn and Steve Q1.
Refactoring. DCS – SWC 2 Refactoring ”A change made to the internal structure of software to make it easier to understand and cheaper to modify without.
CS223: Software Engineering Lecture 18: The XP. Recap Introduction to Agile Methodology Customer centric approach Issues of Agile methodology Where to.
CSHenrik Bærbak Christensen1 Flexibility and Maintainability And their metrics: coupling and cohesion.
Software Engineering 1 Object-oriented Analysis and Design Applying UML and Patterns An Introduction to Object-oriented Analysis and Design and Iterative.
A (Very) Simple Example Consolidate duplicate conditional fragments if (isSpecialDeal()) { total = price * 0.95; send (); } else { total = price * 0.98;
Implementation Topics Describe –Characteristics of good implementations –Best practices to achieve them Understand role of comments Learn debugging techniques.
Principles and examples
Module Road Map Refactoring Why Refactoring? Examples
Why We Refactor? Confessions of GitHub Contributors
Refactoring II 21-Sep-18.
Refactoring and Code Smells
Refactoring III 27-Nov-18.
Code Smells 1.
Improving the structure of existing code
Refactoring and Code Smells
Refactoring III 25-Dec-18.
Refactoring II 5-Feb-19.
DESIGN PATTERNS : State Pattern
Refactoring.
SOEN 343 Software Design Computer Science and Software Engineering Department Concordia University Fall 2004 Instructor: Patrice Chalin.
Refactoring and Code Smells
Advanced Programing practices
Refactoring and Code Smells
Assertions References: internet notes; Bertrand Meyer, Object-Oriented Software Construction; 4/25/2019.
Refactoring.
Chapter 9: Implementation
Refactoring and Code Smells
Presentation transcript:

Refactoring MSO 08/09, WP

What is refactoring ?  Refactoring is the act of transforming the internal structure of a program while preserving its observable behavior.  The main motivation is to improve the 'quality' of your program:  improve its readability  make it less error prone  improve modularity and extensibility 2

Systematic refactoring 3  Idea: rely on a set of small-step changes that are easy to understand and evidently correct. Do refactoring as a series of such steps.  Fowler’s book (1999) contains a catalogue of refactoring steps.  See also

Objective & plan  To make you aware of these concepts from software development: Refactoring, bad smell, antipattern  We’ll discuss some examples.  Consult your Web-resource for the full catallogues:    Buy the books “Refactoring” and “Antipatterns” as reference for you when you latter develop your software. 4

Systematic refactoring  Automated support by IDEs, e.g. in Eclipse. for a small subset of Fowler's refactoring.  No formal proof of the correctness (on-going research).  Current practice:  Relies on common sense.  Prepare a good set of tests; between the steps, do testing to check that you indeed don't change the program functionalities, nor introduce new bugs. 5

"introduce assertion" 6 class ApplicationLogic{... addSubscription(Customer c, Service s) { // c and s should not be null Subscription scr = new Subscription(c,s) ; c.subscriptions.add(scr) ; subscriptions.add(scr) ; } assert c!=null && s!=null less error prone

"extract method" 7 class Customer {... print() { println("name " + name) ; // calculate total weekly cost double c = 0 ; for (Subscription s : subscriptions) c += s.service.price() ; c = c/52.0 ; println("Weekly cost = " + (int) c ) } double total_weeklycost() { double c = 0 ; for (Subscription s : subscriptions) c += s.service.price() ; return c/52.0 }

"extract method" 8 class Customer {... print() { println("name " + name) double c = total_weeklycost() println("Weekly cost = " + (int) c ) } double total_weeklycost() { double c = 0 ; for (Subscription s : subscriptions) c += s.service.price() ; return c/52.0 } improve readability

"extract method"  Consider again the original Customer class.  We want a new feature: VIP customers. They get discounts  influence their price  you have to adapt "print" too. 9 Customer print() Customer print() VIP Solution 1 You have to rewrite print in VIP, probably with lots of code duplication. Customer print() total_weeklycost() Customer print() total_weeklycost() VIP Solution 2 extract method improve modularity & extensibility

"move method" 10 class Service { boolean isBigSpender(Customer c) { if (c.total_weeklycost() < 1000) return false for (Subscription scr : c.subscriptions) if (scr.service == this) return true return false } class Customer { boolean isBigSpender(Service s) { if (total_weeklycost() < 1000) return false for (Subscription scr : subscriptions) if (scr.service == s) return true return false } class Customer { boolean isBigSpender(Service s) { if (total_weeklycost() < 1000) return false for (Subscription scr : subscriptions) if (scr.service == s) return true return false } class Service { boolean isBigSpender(Customer c) { return c.isBigSpender(this) } class Service { boolean isBigSpender(Customer c) { return c.isBigSpender(this) } reduce coupling  less error prone

"Hide delegate" 11 class Customer { double total_weeklycost() { double c = 0 ; for (Subscription s : subscriptions) c += s.service.price() ; return c/52.0 } Customer Subscription Service price() Service price() 0..* Customer Subscription price() Subscription price() Service price() Service price() 0..* hide delegate s.price() reduce coupling

However...  Refactoring tends to add indirection  (small) run-time overhead  a "logic" that was centralized can become scattered  Refactoring may change a class "interface"  E.g. "move field", "remove parameter"  Problem if you have a client that is beyond your reach.  Don't publish your packages too early? 12

Bad smells  ‘If it stinks, change it’ (user manual for babies)  A 'bad smell' describes a set of characteristics indicating that refactoring may be wise.  Fowler has a list of smells in his book. See also the list in MSO website. 13

Bad smells  (Substantial) duplication of code  Overly long method  Overly large class  Too many attributes in a class  Method with lots of parameters ... etc. See the list in MSO website. We'll discuss some selected examples. 14

Bad smell : shotgun surgery  You need to change a feature but are forced to do this in many places. 15 Customer print() Customer print() Service print() Service print() E.g. you want to change how the Company logo is printed, but is forced to change the "print" method of both Customer and Service to do this. Let's try refactoring : 1."extract method" 2."extract superclass" 3."replace inheritance with delegation" CompanyLogo printlogo() CompanyLogo printlogo()

Bad smell : primitive obsession  You use a primitive type for representing a 'concept'. Example: 16 Customer name : String String Then at some point you need a method to validate an . Where to put this method? Customer name : String validate() We'll do "replace data with object" refactoring:

Bad smell: switch statement  This is not to say that "switch" is bad; but consider this example: 17 switch (customer.code) { VIP : registrationfee = 2000 ; break ; PREMIUM : registrationfee = 1500 ; break ; default : registrationfee = 1000 ; }... switch (customer.code) { VIP : discount =.3 ; break ; PREMIUM : discount = 0.1 ; break ; default : discount = 0 ; }

Anti patterns 18  Help! Another caltalogue of “nasties” ??  Anti pattern:  pattern that initially appears beneficial, but ultimately produces more problems than benefits.  it has a (refactoring) solution.  Brown et al: “AntiPatterns: Refactoring Software, Architectures, and Projects in Crisis”, 1998.

Antipattern at different levels  “paralysis by analysis” (management level) Let’s allocate lots of effrot to do good design! But you over do it  blocking the implementation phase. Or ending up writing design documents with unproportional add-value.  Solution: turn the process to be more agile. 19 A single big cycle of design-implement-test Several smaller cycles of design-implement-test

Antipattern at different levels  “Softwarebloat” (design level) You want to reach out to a wide spectrum of users. To make them all happy you add LOTS of features.  Big software  expensive to maintain.  Use lots of resources, and slow.  Solution: make features to be plugable. 20

“Blob” antipattern (code level)  Lots of functionalities are coded into one class, e.g. because:  that’s the simplest way of coding them at the moment  the programmer lacks OO experience  Problem: long term modularity and extensibility  Solution: Fowler’s refactoring 21

Blob, example 22 Library fineRate: float borrowings:... doInventory() checkOut(Book, Client) checkIn(Book) add(Book) delete(Book) printCatalog() searchCatalog(String): Book edit(Book) print(Book) add(Client) booksBorrowed(Client): Set... currentBorrower(Book): Client printCard(Client) calculateFine(Client): float Book author: String title: String id: String Client name: String address id: String 0..*

“Object Orgy” antipattern (code level)  Free access to an object’s (of class C) internal state, e.g. because: Convenient for other classes that use C.  Problem: As your software grows, the logic becomes increasingly defragmented  hard to maintain.  Solution: refactor. 23 Library + fineRate: float + borrowings: Map > + clients : Set + books : Set doInventory() checkOut(Book, Client) checkIn(Book) add(Book) delete(Book) printCatalog() searchCatalog(String): Book edit(Book) print(Book) add(Client) booksBorrowed(Client): Set currentBorrower(Book): Client printCard(Client) calculateFine(Client): float

Final note on refactoring  Use smartly  don’t do it obsessively  blocking the actual work.  Plan ahead  pre-allocate resources for refactoring  When your software starts to smell really bad, you’re in urgent need to refactor.  Hey, I have pre-allocated resources, Yay!  When not to refactor  If the code is still unstable  Shortly before a hard deadline  If it is more efficient to just redo from scratch 24