Principles and examples

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

About Me – Frank Xu Education ▫ North Dakota State University  Ph.D. in Software Engineering ▫ Towson University  MS in Computer Science ▫ Southeast.
© 2010 Shawn A. Bohner Software Construction and Evolution - CSSE 375 Even more Bad Smells in Code Shawn & Steve Q1 Shawn & Steve Hint 
You want me to do what??? Refactoring legacy applications aka : fixing someone else’s “bad” code Niel Zeeman Team Foundation Consulting
Gregor Gisler-Merz BrownBag Session Refactoring.
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)
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.
REFACTORING Improving the Design of Existing Code Atakan Şimşek e
Leiden University. The university to discover. Leiden University. The university to discover. Leiden University. The university to discover. Software Engineering.
Maintenance Refactoring and Code Smells. Where are we? Over the semester we have talked about Software Engineering. The overall goal of software engineering.
What is Refactoring? CSE301 University of Sunderland Harry R. Erwin, PhD.
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.
Refactoring. Refactoring is a step in the software design process.
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.
Refactoring (continued) Source: "Refactoring: Improving the Design of Existing Code", Martin Fowler.
SWE 316: Software Design and Architecture Objectives Lecture # 20 Improving the existing design: Refactoring SWE 316: Software Design and Architecture.
When and How to Refactor? Refactoring Patterns Alexander Vakrilov Telerik Corporation Senior Developer and Team Leader.
Best Practices. Contents Bad Practices Good Practices.
Refactoring1 Improving the structure of existing code.
The effectiveness of refactoring based on a compatibility testing taxonomy and a dependency graph Steve Counsell and Robert Hierons, Brunel University,
Refactoring Deciding what to make a superclass or interface is difficult. Some of these refactorings are helpful. Some research items include Inheritance.
Introduction to Refactoring Jim Cooper Falafel Software.
Informatics 122 Software Design II
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 and such ● (Side note) Specialization ● Key terms ● Abstraction, state, persistence and association and their relationship to software development.
Refactoring: Code Smells. Admin Notes REGISTER FOR BLACKBOARD Watch blackboard site for updates on class as hurricane season approaches.
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.
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.
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.
1 Software Maintenance and Evolution CSSE 575: Session 2, Part 1 Refactoring Principles Steve Chenoweth Office Phone: (812) Cell: (937)
Software Construction and Evolution - CSSE 375 Making Method Calls Simpler Shawn and Steve Below – “Be the character!” The late acting teacher Lee Strasberg.
1 Software Maintenance and Evolution CSSE 575: Session 3, Part 3 Dealing with Generalization Steve Chenoweth Office Phone: (812) Cell: (937)
SEG 4110 – Advanced Software Design and Reengineering Topic T Introduction to Refactoring.
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.
CSSE 375 Organizing Data – Part 1 Shawn and Steve Q1.
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.
ICONFINDER ICONFINDER Founded Django based web application -PostgreSQL -Elasticsearch -Amazon Elastic Compute.
A (Very) Simple Example Consolidate duplicate conditional fragments if (isSpecialDeal()) { total = price * 0.95; send (); } else { total = price * 0.98;
Module Road Map Refactoring Why Refactoring? Examples
Steve Chenoweth Office Phone: (812) Cell: (937)
Steve Chenoweth Office Phone: (812) Cell: (937)
Refactoring and Code Smells
Software Construction and Evolution - CSSE 375 Composing Methods
بازآرایی برنامه Code Refactoring
Code Smells 1.
Improving the structure of existing code
Refactoring and Code Smells
Advanced Programming Behnam Hatami Fall 2017.
Refactoring.
Refactoring and Code Smells
Refactoring.
Refactoring and Code Smells
Presentation transcript:

Principles and examples Refactoring Principles and examples

The goals of a module Functionality The reason for the module's existance Changeability Most modules change during their lifetime If it is hard to change, it is broken and should be fixed Communicatability Modules are read by developers If a developer cannot understand what is happening without serious analysis and pondering, the module is broken and should be fixed

Definitions of refactoring Altering the internal structure without affecting the external behavior Robert C. Martin A change made to the internal structure of sofware to make it easier to understand and chepaer to modify without changing its observable behavior Martin Fowler To restructure software by applying a series of refactorings without changing its observable form

Why refactor? Refactoring improves the design of software Designs decay over changes Code loses its structure Negative spiral Reducing the amount of code Less code is always better Refactoring makes software easier to understand Other people can easier understand well-structured code You, yourself can easier understand well-structured code Refactoring helps you find bugs Understanding code makes it easier to see problems and errors “I'm not a great programmer, I'm just a good programmer with great habits” Kent Beck Refactoring helps you program faster Good design makes it easier to develop faster

When refactor? Refactor when you add function Refactor first Add new functionality then (in a “green” mode)‏ Refactor when you fix a bug Obviously the code wasn't good enough to see the bug in the first place Refactor when doing code reviews It might be clear to you, but not to others Pair programming is code review

Bad smells in code Duplicated code Long method Large class Long parameter list Divergent change Shotgun surgery Feature envy Data clumps Primitive obsession Switch statements Parallel inheritance structures Lazy class Speculative generality Temporary field Message chains Middle man Inappropriate intimacy Alternative classes with different interfaces Incomplete library class Data class Refused bequest Comments

Bad smells and how to sniff them out Duplicated code Same code more than once Long method Too many LOC Large class Too many instance variables Long parameter list Usually bad in an OO environment Divergent change Many changes affect same class Shotgun surgery One change alters many classes Feature envy A method often accesses another class's data Data clumps Data that always is used in clumps shuold be together Primitive obsession Too much use of built-in types Switch statements In OO, inheritance is preferred Parallel inheritance structures ??

Bad smells and how to sniff them out (cont'd)‏ Lazy class Classes that don't do much Speculative generality Hooks for possible future additions Temporary field Instance variables that are only used occasionally Message chains t.get().get().get().get()‏ Middle man Delegating to much Inappropriate intimacy Classes peek and poke at private parts Alternative classes with different interfaces Methods do the same, but have different names Incomplete library class You only use parts of a library Data class Data + get + set only Refused bequest Subclasses only uses parts of what is inherited Comments Might be there because the code is impossible to understand without them

Refactorings Patterns for refactoring code Name Summary Motivation Mechanics Examples

Composing methods Extract method Block of code --> method Inline method Method --> block of code Inline temp Remove temp variable Replace temp with query method Removing temp variables, making their computation a method Replace method with method object Complicated method --> object with several methods Introduce explaining variable Complex expressions are easier to understand with some variables with good names Split temporary variable Don't use same variable for different semantics

Composing methods (cont'd)‏ Remove assignments to parameters Instead of changing a parameters value, copy it and change Substitute algorithm Bad algorithm --> good algorithm

Moving features between objects Move methods a.method() --> b.method()‏ Move field a.aField --> b.aField Extract class One class with two responsibilities --> two classes with one resp. each Inline class Two classes with one resp. each --> One class with two responsibilities Hide delegate a.getB().getC() --> a.getC()‏ Remove middle man a.getC() --> a.getB.getC()‏

Organizing data Self encapsluate field Getters for private data in own class Replace data with object Dumb data --> articluate object Change value to reference Factory method Change reference to value opposite Replace array with object a[0]=”name”, a[1]=”address” --> o.name(“name”), o.address(“address”)‏ Replace magic number with symbolic constant 9.81 --> Gravitation =9.81 Encapsulate field public int x --> private int x, getx, setx

Making method calls simpler Rename method Unreadable --> readable Add parameter method() --> method(param)‏ Remove parameter method(param) --> method() Separate query from modifier Procedure vs function Parametereize method multiplyByTen, multiplyByFive --> multiply(factor)‏ Preserve whole object f(o.getX()), g(o.getY()) --> fg(o)‏

Making method calls simpler (cont'd)‏ Introduce parameter object printdate(year, month, day) --> printdate(dateobject)‏ Replace parameter with method o.doStuff(thing, getSomething()) --> o.doStuff(thing)‏ Replace parameter with explicit methods setvalue(whatToSet, value) --> setvalue1, setvalue2 Remove setting method o.initializeX() --> done in constructor Hide method Make methods not used by others private Encapsulate downcast a = (realType) b.getStuff() --> a = b.getrealStuff()‏ Replace exception with test Test before is better than test after

Dealing with generalization Pull up field Subclasses have same field --> superclass has it instead Pull up method dito Push down field Some subclasses uses a field i superclass --> put them there Push down method Dito Extract superclass Two classes have something in common --> put in superclass and subclass both from it Extract interface Parts of classes common --> make it an interface Collapse hierarchy Subclass and superclass are similar --> make them one

Dealing with generalization Replace inheritance with delegation Only parts of superclass is used --> delegate instead Replace delegation with inheritance To many delegation methods to same object --> super/subclass