Refactoring and its role in Test-Driven Development Miguel J. T. Pessoa Monteiro Escola Superior de Tecnologia de Castelo Branco.

Slides:



Advertisements
Similar presentations
12-Dec-14 Refactoring IV. Previously discussed bad smells Duplicated code — and other forms of redundancy Long method — use short methods that delegate.
Advertisements

Module 7. Simplifying Conditional Expressions Course: Refactoring.
Test-Driven Development and Refactoring CPSC 315 – Programming Studio.
You want me to do what??? Refactoring legacy applications aka : fixing someone else’s “bad” code Niel Zeeman Team Foundation Consulting
1 Software Maintenance and Evolution CSSE 575: Session 2, Part 2 Composing Methods Steve Chenoweth Office Phone: (812) Cell: (937)
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.
Test-Driven Development and Refactoring Project 3 Lecture 1 CPSC 315 – Programming Studio Fall 2009.
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.
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 5 CIS 6101 Software Processes and Metrics.
Advanced Programing practices
Refactoring Cristescu Marilena. Definitions Loose Usage: Reorganize a program(or something) As a noun: a change made to the internal structure of some.
Software Refactoring Part I: Introduction Bartosz Walter Advanced Object-Oriented Design Lecture 5.
Sadegh Aliakbary Sharif University of Technology Spring 2012.
Refactoring. Mathematics: Factor ● fac·tor – One of two or more quantities that divides a given quantity without a remainder, e.g., 2 and 3 are factors.
Refactoring - A disciplined approach to rework for better design.
Refactoring Improving the structure of existing code Refactoring1.
Small changes to code to improve it. Refactoring Defined A change made to the internal structure of software to make it easier to understand and cheaper.
Refactoring1 Refactoring DEPARTMENT OF COMPUTER SCIENCE AND SOFTWARE ENGINEERING CONCORDIA UNIVERSITY February 6, 2009.
SWE 316: Software Design and Architecture Objectives Lecture # 20 Improving the existing design: Refactoring SWE 316: Software Design and Architecture.
Refactoring An Automated Tool for the Tiger Language Leslie A Hensley
Refactoring1 Improving the structure of existing code.
Advanced Programming in Java
Introduction to Refactoring Jim Cooper Falafel Software.
Informatics 122 Software Design II
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 101 William C. Wake
Refactoring 2. Admin Blackboard Quiz Acknowledgements Material in this presentation was drawn from Martin Fowler, Refactoring: Improving the Design of.
REFACTORINGREFACTORING. Realities Code evolves substantially during development Requirements changes 1%-4% per month on a project Current methodologies.
NJIT 1 Test Driven Development and Refactoring Larman, Chapter 21.
Sadegh Aliakbary Sharif University of Technology Spring 2011.
Sadegh Aliakbary. Copyright ©2014 JAVACUP.IRJAVACUP.IR All rights reserved. Redistribution of JAVACUP contents is not prohibited if JAVACUP.
1 Software Maintenance and Evolution CSSE 575: Session 3, Part 3 Dealing with Generalization Steve Chenoweth Office Phone: (812) Cell: (937)
Refactoring Mehdi Einali Advanced Programming in Java 1.
SEG 4110 – Advanced Software Design and Reengineering Topic T Introduction to Refactoring.
Refactoring Advanced Software Engineering Dr Nuha El-Khalili.
Refactoring. Mathematics: Factor ● fac·tor – One of two or more quantities that divides a given quantity without a remainder, e.g., 2 and 3 are factors.
Refactoring1 Improving the structure of existing code.
Pertemuan 12 Refactoring Mata kuliah: T0144 – Advanced Topics in Software Engineering Tahun: 2010.
Refactoring. 2 Process of changing a software system in such a way that it does not alter the external behavior of the code, yet improves its internal.
Software Construction and Evolution - CSSE 375 Simplifying Conditionals Shawn & Steve.
Software Construction and Evolution - CSSE 375 Dealing with Generalization Steve and Shawn Left – In the 1990 movie “The Freshman,” Matthew Broderick,
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.
Module 9. Dealing with Generalization Course: Refactoring.
Code Refactoring Milan Vukoje Soprex SkfOffice2 SkfOffice3 Big5 Quality oriented We are hiring…
Catalog of Refactoring (1) Composing Methods. Code Smells Long methods Dubious temporary variables Dubious methods.
Refactoring (1). Software Evolution Cope with change Feature bloat Design decay Code duplications “Pattern time is refactoring time” Make future changes.
A (Very) Simple Example Consolidate duplicate conditional fragments if (isSpecialDeal()) { total = price * 0.95; send (); } else { total = price * 0.98;
Principles and examples
Advanced Programming in Java
Refactoring and Code Smells
SWEN-610 Foundations of Software Engineering
Software Construction and Evolution - CSSE 375 Composing Methods
بازآرایی برنامه Code Refactoring
Improving the structure of existing code
Refactoring and Code Smells
Advanced Programming Behnam Hatami Fall 2017.
Refactoring.
Refactoring and Code Smells
Advanced Programing practices
Refactoring and Code Smells
Refactoring.
Refactoring and Code Smells
Presentation transcript:

Refactoring and its role in Test-Driven Development Miguel J. T. Pessoa Monteiro Escola Superior de Tecnologia de Castelo Branco

2 Overview Characterisation of Refactoring Brief History of Refactoring Examples of refactoring steps How refactorings are performed When to refactor (code smells) Role of unit tests in refactoring Resources

3 Refactoring Tenet of Refactoring Program source code is a mechanism of communication between humans, not between the programmer and the computer.

4 public void add(Object element) { if(!readOnly) { int newSize = size + 1; if(newSize > elements.length) { Object[] newElements = new Object[elemnts.length + 10]; for(int i=0; i<size; i++) newElements[i] = elements[i]; elements = newElements; } elements[size++] = element; } public void add(Object element) { if(readOnly) return; if(atCapacity()) grow(); addElement(element); }  Intentionality is Important

5 Characterising Refactoring Martin Fowler: “a disciplined technique for restructuring an existing body of code, altering its internal structure without changing its external behaviour.”

6 Characterising Refactoring Martin Fowler: “Each transformation does little, but a sequence of transformations can produce a significant restructuring. Since each refactoring is small, it's less likely to go wrong”.

7 The “Two Hat” Metaphor Programmer always wearing one of 2 hats: The developer hat The refactoring hat If the task can be made easier if the code is structured differently, Programmer swaps hats and refactors for a while. Then he swaps hats again, and adds the functionality.

8 What is not Refactoring Adding new functionality is not refactoring Optimisation is not refactoring Changing code that does not compile is not refactoring (what would be the behaviour?)

9 Overview Characterisation of Refactoring Brief History of Refactoring Examples of refactoring steps How refactorings are performed When to refactor (code smells) Role of unit tests in refactoring Resources

10 Brief History of Refactoring Griswold W., Program restructuring as an aid to software maintenance. PhD thesis, University of Washington, USA, Opdyke W., Refactoring Object-Oriented Frameworks, Ph.D. Thesis, University of Illinois at Urbana-Champaign, USA, Roberts D., Brant J., Johnson R., A refactoring tool for smalltalk. Theory and Practice of Object Systems 3(4), pp. 253–263, 1997.

11 Brief History of Refactoring Advent of unit tests (e.g. xUnit) Made manual refactoring possible. Advent of Extreme Programming (XP) Test-driven development: Unit testing, Refactoring, Pair programming, etc. Martin Fowler’s book Promoted refactoring to buzzword status

12 Overview Characterisation of Refactoring Brief History of Refactoring Examples of refactoring steps How refactorings are performed When to refactor (code smells) Role of unit tests in refactoring Resources

13 Reverse Conditional You have a conditional that would be easier to understand if you reversed its sense. Reverse the sense of the conditional and reorder the conditional's clauses. if ( !isSummer( date ) ) charge = winterCharge( quantity ); else charge = summerCharge( quantity ); if ( isSummer( date ) ) charge = summerCharge( quantity ); else charge = winterCharge( quantity );

14 Rename Method The name of a method does not reveal its purpose. Change the name of the method.

15 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.

16 Pull Up Method You have methods with identical results on subclasses. Move them to the superclass.

17 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. void printOwing() { printBanner(); //print details System.out.println ("name: " + _name); System.out.println ("amount " + getOutstanding()); } void printOwing() { printBanner(); printDetails(getOutstanding()); } void printDetails (double outstanding) { System.out.println ("name: " + _name); System.out.println ("amount " + outstanding); }

18 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. void printOwing() { printBanner(); //print details System.out.println ("name: " + _name); System.out.println ("amount " + getOutstanding()); } void printOwing() { printBanner(); printDetails(getOutstanding()); } void printDetails (double outstanding) { System.out.println ("name: " + _name); System.out.println ("amount " + outstanding); }

19 Inline Method A method's body is just as clear as its name. Put the method's body into the body of its callers and remove the method. int getRating() { return (moreThanFiveLateDeliveries()) ? 2 : 1; } boolean moreThanFiveLateDeliveries() { return _numberOfLateDeliveries > 5; } int getRating() { return (_numberOfLateDeliveries > 5) ? 2 : 1; }

20 Inline Method A method's body is just as clear as its name. Put the method's body into the body of its callers and remove the method. int getRating() { return (moreThanFiveLateDeliveries()) ? 2 : 1; } boolean moreThanFiveLateDeliveries() { return _numberOfLateDeliveries > 5; } int getRating() { return (_numberOfLateDeliveries > 5) ? 2 : 1; } Opposite to Extract Method

21 Replace Conditional with Polymorphism You have a conditional that chooses different behavior depending on the type of an object. Move each leg of the conditional to an overriding method in a subclass. Make the original method abstract. double getSpeed() { switch (_type) { case EUROPEAN: return getBaseSpeed(); case AFRICAN: return getBaseSpeed() - getLoadFactor() * _numberOfCoconuts; case NORWEIGIAN_BLUE: return (_isNailed) ? 0 : getBaseSpeed(_voltage); } throw new RuntimeException ("Should be unreachable"); }

22 Replace Conditional with Polymorphism You have a conditional that chooses different behavior depending on the type of an object. Move each leg of the conditional to an overriding method in a subclass. Make the original method abstract.

23 Overview Characterisation of Refactoring Brief History of Refactoring Examples of refactoring steps How refactorings are performed When to refactor (code smells) Role of unit tests in refactoring Resources

24 How Refactorings are Performed Either manually or automatically. When done manually, it is always done in small steps (called refactorings). Larger refactorings are sequences of smaller ones

25 Manual Refactoring Manual refactoring steps should always be small, because: They are safer this way, because the steps are simpler It is easier to backtrack Pay attention to the mechanics: Mechanics should stress safety

26 How Refactorings are Performed When automatic support is available, it should be preferred, but only if the tool is really safe. Example: Rename Method Does it check for another method with the same name? Does it account for overloading? Does it account for overriding?

27 Overview Characterisation of Refactoring Brief History of Refactoring Examples of refactoring steps How refactorings are performed When to refactor (code smells) Role of unit tests in refactoring Resources

28 When to Refactor We should refactor when the code stinks. “If it stinks, change it.” Grandma Beck, discussing child-rearing philosophy

29 Refactoring and code smells Refactorings remove Bad Smells in the Code i.e., potential problems or flaws Some will be strong, some will be subtler Some smells are obvious, some aren’t Some smells mask other problems Some smells go away unexpectedly when we fix something else

30 Refactoring and code smells Examples of code smells: Duplicated Code, Large Class, Lazy Class, Long Method, Long Parameter List, Primitive Obsession, Speculative Generality, Temporary Field, Inappropriate Intimacy, Data Class, Refused Bequest, Comments,... Frequent cause: the paradigm shift problem

31 Refactoring and code smells Code smells motivate use of refactorings to remove them, e.g. Duplicated Code → Extract Method, Extract Class, Form Template Method,... Long Method → Extract Method, Replace Temp with Query, Introduce Parameter Object, Decompose Conditional,...

32 Overview Characterisation of Refactoring Brief History of Refactoring Examples of refactoring steps How refactorings are performed When to refactor (code smells) Role of unit tests in refactoring Resources

33 Unit Tests Essential prerequisite for refactoring: Solid tests (i.e. good unit test coverage) Tests warn programmers of problems if they unknowningly break other parts of the application Tests give an immediate/quick analysis of the effects of a change Therefore tests give Courage

34 Unit Tests Essential characteristic of unit tests: They must be automatic No need to see console outputs No need to specially prepare them to run They should independent of each other They should run often They should make it easy to run often (otherwise developers will stop running them) They must be fast

35 Unit Tests A test is not an unit test if: It talks to a database It communicates across a network It touches the file system Such tests are good, but not fast enough to run in a suite of thousands of tests

Ciclo RED-GREEN-REFACTOR Escrever um teste Compilar Corrigir os erros do compilador Correr os testes e ver a barra vermelha Escrever novo código Correr os testes e ver a barra verde Refabricar o código (e testar)

Fase RED Escrever um teste Compilar Corrigir os erros do compilador Correr os testes e ver a barra vermelha Escrever novo código Correr os testes e ver a barra verde Refabricar o código (e testar)

Fase RED Fase GREEN Escrever um teste Compilar Corrigir os erros do compilador Correr os testes e ver a barra vermelha Escrever novo código Correr os testes e ver a barra verde Refabricar o código (e testar)

Fase RED Fase GREEN Fase REFACTOR Escrever um teste Compilar Corrigir os erros do compilador Correr os testes e ver a barra vermelha Escrever novo código Correr os testes e ver a barra verde Refabricar o código (e testar)

40 Overview Characterisation of Refactoring Brief History of Refactoring Examples of refactoring steps How refactorings are performed When to refactor (code smells) Role of unit tests in refactoring Resources

41 Resources – TDD & refactoring Refactoring home page Refactoring mailing list at Yahoo groups.yahoo.com/group/refactoring/

42 test-driven development: A Practical Guide Dave Astels Prentice-Hall/Pearson Education, 2003 ISBN ___________________________ Test-Driven Development: By Example Kent Beck Addison-Wesley, 2003 ISBN Resources – TDD & refactoring

43 Refactoring: Improving the Design of Existing Code Martin Fowler Addison-Wesley, 1999 ISBN Resources – TDD & refactoring

44 Refactoring Workbook William Wake Addison-Wesley, 2003 ISBN Resources – TDD & refactoring

45 Refactoring to Patterns Joshua Kerievsky Addison-Wesley, 2004 ISBN Resources – TDD & refactoring

46 JUnit Recipes – Practical Methods for Programmer Testing J.B. Rainsberger Manning 2005 ISBN Resources – TDD & refactoring

47 Working Effectively with Legacy Code Michael Feathers Addison-Wesley, 2005 ISBN Resources – TDD & refactoring

48 Agile Java - Crafting Code with Test-Driven Development Jeff Langr Prentice Hall 2005 ISBN Resources – TDD & refactoring

49 Refactoring and its role in Test-Driven Development Questions? Miguel J. T. Pessoa Monteiro Escola Superior de Tecnologia de Castelo Branco