SlideShare una empresa de Scribd logo
1 de 44
step-by-step
This is not a work of fiction. 
Design Flaws and Bugs are neither the product of the author's imagination nor 
used fictitiously. 
Any resemblance to real legacy projects is entirely non coincidental.
Uses many attributes from external classes 
Is excessively large and complex 
Is very non-cohesive
Data and behavior that acts on that data belong together. When a method makes 
too many calls to other classes to obtain data or functionality, Feature Envy is in 
the air. 
4 methods are affected by this design flaw
All methods are envy on Policy Details Extended form datas
This is a Context Object and its role is to encapsulate state in a protocol 
independent way. 
This Design Flow doesn't harm the application and can be ignored 
POST /path/policy.do HTTP/1.0 
User-Agent: HTTPTool/1.0 
Content-Type: application/x-www-form-urlencoded 
Content-Length: 532 
policyType=1&eCommerceSys=153 
SubBrokers DelegatedAuthorities ... 
PolicyDetailsForm 
PolicyDetailsExtendedForm 
- policyState 
- policyTypeId 
- billCoding 
- manualAdjustable 
- referringAgent 
- ... 
Categories eCommerceSystems Underwriters
This is the MAJOR design flow found in this class. The Long Methods with very 
high cyclomatic complexity make the code hard to understand, maintain and test. 
105 + 98 + 76 + 30 + 11 + 10 + 10 + … = 350 ~ 400
1. Orchestrates Business Services (3) 
«ApplicationController» 
RequestProcessor 
«Command» 
Action 
«PresentationModel» 
ActionForm 
«POJO» 
BusinessService 
«JSP» 
View 
View Helper 
«Domain Model» 
Policy 
adapt 
use 
0..* 
manage 
access 
1..* 
populate 
invoke 
dispatch 
creates 1 
2 3 
4 
5 
6 
7 
POST /path/policy.do HTTP/1.0 
User-Agent: HTTPTool/1.0 
policyType=1&transType=newPolicy
2. Provides Presentation Model initialization - policy type specific business rules are 
applied - New Policy, Init
3. Provides Presentation Model validation - policy type specific business rules are 
applied - Save, Decline Quote, New Coverage, Apply 
SubBrokers DelegatedAuthorities ... 
PolicyDetailsForm 
PolicyDetailsExtendedForm 
- policyState 
- policyTypeId 
- billCoding 
- manualAdjustable 
- referringAgent 
- ... 
Categories eCommerceSystems Underwriters
4. Populates the Domain Model using the values provided by Presentation Model – 
some values are copied others are derived using policy type specific business rules - 
Save, Decline Quote, New Coverage, Set WIP Data , Apply
60 
50 
40 
30 
20 
10 
0 
PolicyDetailsExtendedAction 
number of commits per year 
commits 
2008 2009 2010 2011 2012 2013 2014
Refactoring is the 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 structure.
4 Rules to keep in mind when refactoring code: 
 It passes ALL the tests (preserve its external behavior) 
 It minimizes duplication in all its forms 
 It expresses its intent clearly to the reader 
 It removes unnecessary element
It passes ALL the tests (preserve its external behavior) 
0,0% 7.631 
Number of execution paths 
• One unit test case in 3 minutes 
• One man day (6 hours) = 120 branches covered per day 
• 7631 / 120 ~ 64 days 
• 5 day per week = 13 weeks 
TOTAL: 3+ months
It allows for quick production of reliable non regression tests to facilitate code 
refactoring.
 Generate enough pseudo-random data 
 Use a code coverage data
if (PolicyTypes.isUKPolicyType(policy.getPolicyTypeId().intValue()) 
|| _form.getStatus() == Status.RENEWING) { 
if (_form.getWinsArpCode().equals("Y")) { 
policy.setBookedStatus(BookingStatus.ELIGIBLE_FOR_AUTOBOOKING_HELD); 
} else if (_form.getWinsArpCode().equals("C")) { 
policy.setBookedStatus(BookingStatus.FORCED_INVITE); 
} else if (_form.getWinsArpCode().equals("E")) { 
policy.setBookedStatus(BookingStatus.ELIGIBLE_FOR_AUTOBOOKING); 
} 
} 
1 
1 {UK/Travel=1, IT/Travel=7} 
2 
2 {RENEWING=W,NEW=N} 
3 
3 {Y,C,E}
1 7 
Y Y Y Y C C C C E E E E 
T 
ValuesGenerator 
+ ValuesGenerator(List<T>) 
+ getNextValue() : T 
PolicyTypeGenerator 
+ getNextValue() : int 
FormStatusGenerator 
+ getNextValue() : char 
1 
FormWinsArpCodeGenerator 
+ getNextValue() : String 
W W N N 
2 
3 
1 7 1 7 1 7 1 7 1 7 1 7 
W W N N W W N N W W N N 
Y Y Y Y C C C C E E E E 
12
Find a way to capture the output of the system without changing the production 
code 
Direct output 
 HttpSession (Domain Model) 
 Presentation Model 
 HttpRequest 
 Computed ActionForward 
 Thrown Exceptions 
Indirect output 
 Errors sent by email to operation team
 Use a non intrusive solution - the existing code should not be modified 
 Non Serializable objects must be serialized too 
 Persist the output into a human readable format 
 Provide a mechanism to omit some fields 
Current date/time populated somewhere by one of the SUT indirect colaborators 
Error stack 
serializer.registerOmitField(Policy.class, “creationDate"); 
serializer.registerOmitField(Policy.class, "lastModifiedDate"); 
serializer.registerOmitField(Throwable.class, "stackTrace"); 
framework: XStream
Number of execution paths 
98,0%
Missing return statement 
zoneReferred value is computed but not used – always returns 0 b.c.
Dead Code 
the second branch is unreachable because the 
generateDynamicList variable is hardcoded to true
Unnecessary null check 
if the address is null, a new address is 
created on the fly.
Policy Type is used to implement business rules variations for all 3 responsibilities: 
 initialize 
 validate 
 save 
32 
Accident / Travel ITA 2010
Method body Method body Common to ALL 
COUNTRY specific 
YEAR / TYPE specific 
> 1k
Common to ALL 
Policies 
Common to a 
specific COUNTRY 
Specific by YEAR / 
TYPE 
ALL 
IT 
2010/Travel 2012/Travel 
UK 
2010/Accident 
RESPONSIBILITIES 
I 
N 
I 
T 
I 
A 
L 
I 
Z 
E 
V 
A 
L 
I 
D 
A 
T 
E 
S 
A 
V 
E
 Single Responsibility Principle 
 Open for Extension Close for Modification 
 Group together things that change together
InitializationRulesFactory 
+ getRulesForPolicyType() : InitializationRules 
asks 
provides 
PolicyAction 
# initialize() : void 
# validate() : void 
«interface» 
InitializationRules 
use 
+ initialize() : void 
CommonInitializationRules 
+ initialize() : void 
DEUInitializationRules 
+ initialize() : void 
UKInitializationRules 
+ initialize() : void 
UK2012InitializationRules 
+ initialize() : void 
ValidationRulesFactory 
+ getRulesForPolicyType() : ValidationRules 
«interface» 
ValidationRules 
+ validate() : void 
CommonValidationRules 
+ validate() : void 
UKValidationRules 
+ validate() : void 
DEUValidationRules 
+ validate() : void 
UK2012ValidationRules 
+ validate() : void 
UK2014ValidationRules 
+ validate() : void 
use 
asks 
provides
red 
green 
refactor 
commit 
green 
revert
A. Extract ALL initialization rules into a new Class 
The refactoring steps are depicted below 
 Use Extract Class and create a new class to express the split-off responsibilities 
 Use Move Field on each relevant field 
 Use Move Method to move method over from old class to new one 
 Use Replace constructor with Factory Method and create a new dedicated class 
responsible to provide the right subclass of InitializePolicyFormService based on 
Policy Type. In this way we separate the instantiation responsibility from 
initialization responsibility.
B. Extract NDL specific initialization rules into a new Subclass that extends the 
Class created above 
The refactoring steps are depicted below 
 Use Extract Subclass and define a new subclass that hosts the specific NDL 
initialization rules 
 Use Push Down Method on methods specific to NDL. 
 Copy methods that contains conditional logic specific to NDL and simplify the 
method preserving only the conditional leg relevant for NDL context. Make the 
original method protected 
 Update the Factory Class to return this subclass if Policy Type belongs to NDL
C. Refactor the Factory Method 
 Use Replace conditional dispatcher with Command 
D. Repeat steps (B) and (C) for each Country / Year / Policy Type.
Refactoring Improves the Design of Software 
 Without refactoring, the design of the program will decay (people change code to 
realize short-term goals without a full comprehension of the design) 
 Loss of the structure of code has a cumulative effect (the harder it is to see the 
design in the code, the harder it is to preserve it)
Books 
 http://www.amazon.com/Refactoring-Improving-Design-Existing-Code/dp/0201485672 
 http://www.amazon.com/Refactoring-Patterns-Joshua-Kerievsky/dp/0321213351 
Articles 
 http://java.dzone.com/articles/testing-legacy-code-golden 
 http://blog.adrianbolboaca.ro/2014/05/legacy-coderetreat-golden-master/ 
 http://martinsson-johan.blogspot.fr/2014/01/golden-master-and-legacy-few-insights.html 
Tools 
 http://approvaltests.sourceforge.net/ 
 http://xstream.codehaus.org/

Más contenido relacionado

Similar a Refactoring legacy code: step-by-step examples

Biz Talk Demo slideshare
Biz Talk Demo slideshareBiz Talk Demo slideshare
Biz Talk Demo slideshareerios
 
How We Built the Private AppExchange App (Apex, Visualforce, RWD)
How We Built the Private AppExchange App (Apex, Visualforce, RWD)How We Built the Private AppExchange App (Apex, Visualforce, RWD)
How We Built the Private AppExchange App (Apex, Visualforce, RWD)Salesforce Developers
 
Design patterns fast track
Design patterns fast trackDesign patterns fast track
Design patterns fast trackBinu Bhasuran
 
01_Enterprise_Applications_RIO.ppt
01_Enterprise_Applications_RIO.ppt01_Enterprise_Applications_RIO.ppt
01_Enterprise_Applications_RIO.pptPonnieaswari M.S
 
Sample_Data_and_Data_Modules
Sample_Data_and_Data_ModulesSample_Data_and_Data_Modules
Sample_Data_and_Data_ModulesMichael Cook
 
Notes how to work with variables, constants and do calculations
Notes how to work with variables, constants and do calculationsNotes how to work with variables, constants and do calculations
Notes how to work with variables, constants and do calculationsWilliam Olivier
 
Making Your Apex and Visualforce Reusable
Making Your Apex and Visualforce ReusableMaking Your Apex and Visualforce Reusable
Making Your Apex and Visualforce ReusableSalesforce Developers
 
DIGITAL TWIN FRAMEWORK FOR SUPPLYCHAIN PROCESS
DIGITAL TWIN FRAMEWORK FOR SUPPLYCHAIN PROCESSDIGITAL TWIN FRAMEWORK FOR SUPPLYCHAIN PROCESS
DIGITAL TWIN FRAMEWORK FOR SUPPLYCHAIN PROCESSIRJET Journal
 
Documentation on bigmarket copy
Documentation on bigmarket   copyDocumentation on bigmarket   copy
Documentation on bigmarket copyswamypotharaveni
 
Enterprise Library 3.0 Policy Injection Applicatoin Block
Enterprise Library 3.0 Policy Injection Applicatoin BlockEnterprise Library 3.0 Policy Injection Applicatoin Block
Enterprise Library 3.0 Policy Injection Applicatoin Blockmcgurk
 
Impact of cloud services on software development life
Impact of cloud services on software development life Impact of cloud services on software development life
Impact of cloud services on software development life Mohamed M. Yazji
 
Overview of entity framework by software outsourcing company india
Overview of entity framework by software outsourcing company indiaOverview of entity framework by software outsourcing company india
Overview of entity framework by software outsourcing company indiaJignesh Aakoliya
 
Hipercept Presentation at IGlobal\'s Private Equity Summit
Hipercept Presentation at IGlobal\'s Private Equity SummitHipercept Presentation at IGlobal\'s Private Equity Summit
Hipercept Presentation at IGlobal\'s Private Equity SummitHCohen
 
Cognitivo - Tackling the enterprise data quality challenge
Cognitivo - Tackling the enterprise data quality challengeCognitivo - Tackling the enterprise data quality challenge
Cognitivo - Tackling the enterprise data quality challengeAlan Hsiao
 
Generically Call External Classes from Managed Packages
Generically Call External Classes from Managed PackagesGenerically Call External Classes from Managed Packages
Generically Call External Classes from Managed PackagesSalesforce Developers
 
IRJET- Training and Placement Database Management System
IRJET- Training and Placement Database Management SystemIRJET- Training and Placement Database Management System
IRJET- Training and Placement Database Management SystemIRJET Journal
 
Vpd Virtual Private Database By Saurabh
Vpd   Virtual Private Database By SaurabhVpd   Virtual Private Database By Saurabh
Vpd Virtual Private Database By Saurabhguestd83b546
 
MaxTECH Technical Training Presentation from MaximoWorld 2018
MaxTECH Technical Training Presentation from MaximoWorld 2018MaxTECH Technical Training Presentation from MaximoWorld 2018
MaxTECH Technical Training Presentation from MaximoWorld 2018Helen Fisher
 
BIG MART SALES PREDICTION USING MACHINE LEARNING
BIG MART SALES PREDICTION USING MACHINE LEARNINGBIG MART SALES PREDICTION USING MACHINE LEARNING
BIG MART SALES PREDICTION USING MACHINE LEARNINGIRJET Journal
 

Similar a Refactoring legacy code: step-by-step examples (20)

Biz Talk Demo slideshare
Biz Talk Demo slideshareBiz Talk Demo slideshare
Biz Talk Demo slideshare
 
How We Built the Private AppExchange App (Apex, Visualforce, RWD)
How We Built the Private AppExchange App (Apex, Visualforce, RWD)How We Built the Private AppExchange App (Apex, Visualforce, RWD)
How We Built the Private AppExchange App (Apex, Visualforce, RWD)
 
Design patterns fast track
Design patterns fast trackDesign patterns fast track
Design patterns fast track
 
01_Enterprise_Applications_RIO.ppt
01_Enterprise_Applications_RIO.ppt01_Enterprise_Applications_RIO.ppt
01_Enterprise_Applications_RIO.ppt
 
Sample_Data_and_Data_Modules
Sample_Data_and_Data_ModulesSample_Data_and_Data_Modules
Sample_Data_and_Data_Modules
 
Notes how to work with variables, constants and do calculations
Notes how to work with variables, constants and do calculationsNotes how to work with variables, constants and do calculations
Notes how to work with variables, constants and do calculations
 
Making Your Apex and Visualforce Reusable
Making Your Apex and Visualforce ReusableMaking Your Apex and Visualforce Reusable
Making Your Apex and Visualforce Reusable
 
DIGITAL TWIN FRAMEWORK FOR SUPPLYCHAIN PROCESS
DIGITAL TWIN FRAMEWORK FOR SUPPLYCHAIN PROCESSDIGITAL TWIN FRAMEWORK FOR SUPPLYCHAIN PROCESS
DIGITAL TWIN FRAMEWORK FOR SUPPLYCHAIN PROCESS
 
Documentation on bigmarket copy
Documentation on bigmarket   copyDocumentation on bigmarket   copy
Documentation on bigmarket copy
 
Enterprise Library 3.0 Policy Injection Applicatoin Block
Enterprise Library 3.0 Policy Injection Applicatoin BlockEnterprise Library 3.0 Policy Injection Applicatoin Block
Enterprise Library 3.0 Policy Injection Applicatoin Block
 
Impact of cloud services on software development life
Impact of cloud services on software development life Impact of cloud services on software development life
Impact of cloud services on software development life
 
Overview of entity framework by software outsourcing company india
Overview of entity framework by software outsourcing company indiaOverview of entity framework by software outsourcing company india
Overview of entity framework by software outsourcing company india
 
Hipercept Presentation at IGlobal\'s Private Equity Summit
Hipercept Presentation at IGlobal\'s Private Equity SummitHipercept Presentation at IGlobal\'s Private Equity Summit
Hipercept Presentation at IGlobal\'s Private Equity Summit
 
Print report
Print reportPrint report
Print report
 
Cognitivo - Tackling the enterprise data quality challenge
Cognitivo - Tackling the enterprise data quality challengeCognitivo - Tackling the enterprise data quality challenge
Cognitivo - Tackling the enterprise data quality challenge
 
Generically Call External Classes from Managed Packages
Generically Call External Classes from Managed PackagesGenerically Call External Classes from Managed Packages
Generically Call External Classes from Managed Packages
 
IRJET- Training and Placement Database Management System
IRJET- Training and Placement Database Management SystemIRJET- Training and Placement Database Management System
IRJET- Training and Placement Database Management System
 
Vpd Virtual Private Database By Saurabh
Vpd   Virtual Private Database By SaurabhVpd   Virtual Private Database By Saurabh
Vpd Virtual Private Database By Saurabh
 
MaxTECH Technical Training Presentation from MaximoWorld 2018
MaxTECH Technical Training Presentation from MaximoWorld 2018MaxTECH Technical Training Presentation from MaximoWorld 2018
MaxTECH Technical Training Presentation from MaximoWorld 2018
 
BIG MART SALES PREDICTION USING MACHINE LEARNING
BIG MART SALES PREDICTION USING MACHINE LEARNINGBIG MART SALES PREDICTION USING MACHINE LEARNING
BIG MART SALES PREDICTION USING MACHINE LEARNING
 

Más de Endava

Agility Beyond the Development Team
Agility Beyond the Development TeamAgility Beyond the Development Team
Agility Beyond the Development TeamEndava
 
Marketplace Innovation Report | Q3, 2016
Marketplace Innovation Report | Q3, 2016Marketplace Innovation Report | Q3, 2016
Marketplace Innovation Report | Q3, 2016Endava
 
Marketplace Innovation Report | Q2, 2016
Marketplace Innovation Report | Q2, 2016Marketplace Innovation Report | Q2, 2016
Marketplace Innovation Report | Q2, 2016Endava
 
What Is The Right Digital Transformation Formula? | Endava Executive Network,...
What Is The Right Digital Transformation Formula? | Endava Executive Network,...What Is The Right Digital Transformation Formula? | Endava Executive Network,...
What Is The Right Digital Transformation Formula? | Endava Executive Network,...Endava
 
Marketplace Innovation Report | Q4, 2015
Marketplace Innovation Report | Q4, 2015Marketplace Innovation Report | Q4, 2015
Marketplace Innovation Report | Q4, 2015Endava
 
Marketplace Innovation report Q2 2015
Marketplace Innovation report Q2 2015Marketplace Innovation report Q2 2015
Marketplace Innovation report Q2 2015Endava
 
Transforming payments for the digital future
Transforming payments for the digital futureTransforming payments for the digital future
Transforming payments for the digital futureEndava
 
Marketplace Innovation Report | Q3, 2014
Marketplace Innovation Report | Q3, 2014Marketplace Innovation Report | Q3, 2014
Marketplace Innovation Report | Q3, 2014Endava
 
LogiLogicless UI prototyping with Node.js | SuperSpeaker@CodeCamp Iasi, 2014
LogiLogicless UI prototyping with Node.js | SuperSpeaker@CodeCamp Iasi, 2014LogiLogicless UI prototyping with Node.js | SuperSpeaker@CodeCamp Iasi, 2014
LogiLogicless UI prototyping with Node.js | SuperSpeaker@CodeCamp Iasi, 2014Endava
 
Continuos integration with Jenkins for iOS | SuperSpeakers@CodeCamp Iasi, 2014
Continuos integration with Jenkins for iOS | SuperSpeakers@CodeCamp Iasi, 2014Continuos integration with Jenkins for iOS | SuperSpeakers@CodeCamp Iasi, 2014
Continuos integration with Jenkins for iOS | SuperSpeakers@CodeCamp Iasi, 2014Endava
 
Click’n’Deploy | SuperSpeakers @CodeCamp Iasi, 2014
Click’n’Deploy | SuperSpeakers @CodeCamp Iasi, 2014Click’n’Deploy | SuperSpeakers @CodeCamp Iasi, 2014
Click’n’Deploy | SuperSpeakers @CodeCamp Iasi, 2014Endava
 
Marketplace Innovation Report | Q2 2014
Marketplace Innovation Report | Q2 2014 Marketplace Innovation Report | Q2 2014
Marketplace Innovation Report | Q2 2014 Endava
 
Innovation in Mobile Payments
Innovation in Mobile PaymentsInnovation in Mobile Payments
Innovation in Mobile PaymentsEndava
 
Marketplace Innovation Report | Q1 2014
Marketplace Innovation Report | Q1 2014Marketplace Innovation Report | Q1 2014
Marketplace Innovation Report | Q1 2014Endava
 
Endava Marketplace Innovation Q4 2013
Endava Marketplace Innovation Q4 2013Endava Marketplace Innovation Q4 2013
Endava Marketplace Innovation Q4 2013Endava
 
Endava Marketplace Innovation Q3 2013
Endava Marketplace Innovation Q3 2013Endava Marketplace Innovation Q3 2013
Endava Marketplace Innovation Q3 2013Endava
 
Darwin Agile and The Dinosaurs
Darwin Agile and The DinosaursDarwin Agile and The Dinosaurs
Darwin Agile and The DinosaursEndava
 
Have you ever seen a BA?
Have you ever seen a BA?Have you ever seen a BA?
Have you ever seen a BA?Endava
 
Endava @ CodeCamp Cluj - SharePoint 2010 for business needs by Levente Veres
Endava @ CodeCamp Cluj  - SharePoint 2010 for business needs by Levente VeresEndava @ CodeCamp Cluj  - SharePoint 2010 for business needs by Levente Veres
Endava @ CodeCamp Cluj - SharePoint 2010 for business needs by Levente VeresEndava
 
Endava Career Days Iasi Jan 2012 - Looking Inside the Scrum
Endava Career Days Iasi Jan 2012  - Looking Inside the ScrumEndava Career Days Iasi Jan 2012  - Looking Inside the Scrum
Endava Career Days Iasi Jan 2012 - Looking Inside the ScrumEndava
 

Más de Endava (20)

Agility Beyond the Development Team
Agility Beyond the Development TeamAgility Beyond the Development Team
Agility Beyond the Development Team
 
Marketplace Innovation Report | Q3, 2016
Marketplace Innovation Report | Q3, 2016Marketplace Innovation Report | Q3, 2016
Marketplace Innovation Report | Q3, 2016
 
Marketplace Innovation Report | Q2, 2016
Marketplace Innovation Report | Q2, 2016Marketplace Innovation Report | Q2, 2016
Marketplace Innovation Report | Q2, 2016
 
What Is The Right Digital Transformation Formula? | Endava Executive Network,...
What Is The Right Digital Transformation Formula? | Endava Executive Network,...What Is The Right Digital Transformation Formula? | Endava Executive Network,...
What Is The Right Digital Transformation Formula? | Endava Executive Network,...
 
Marketplace Innovation Report | Q4, 2015
Marketplace Innovation Report | Q4, 2015Marketplace Innovation Report | Q4, 2015
Marketplace Innovation Report | Q4, 2015
 
Marketplace Innovation report Q2 2015
Marketplace Innovation report Q2 2015Marketplace Innovation report Q2 2015
Marketplace Innovation report Q2 2015
 
Transforming payments for the digital future
Transforming payments for the digital futureTransforming payments for the digital future
Transforming payments for the digital future
 
Marketplace Innovation Report | Q3, 2014
Marketplace Innovation Report | Q3, 2014Marketplace Innovation Report | Q3, 2014
Marketplace Innovation Report | Q3, 2014
 
LogiLogicless UI prototyping with Node.js | SuperSpeaker@CodeCamp Iasi, 2014
LogiLogicless UI prototyping with Node.js | SuperSpeaker@CodeCamp Iasi, 2014LogiLogicless UI prototyping with Node.js | SuperSpeaker@CodeCamp Iasi, 2014
LogiLogicless UI prototyping with Node.js | SuperSpeaker@CodeCamp Iasi, 2014
 
Continuos integration with Jenkins for iOS | SuperSpeakers@CodeCamp Iasi, 2014
Continuos integration with Jenkins for iOS | SuperSpeakers@CodeCamp Iasi, 2014Continuos integration with Jenkins for iOS | SuperSpeakers@CodeCamp Iasi, 2014
Continuos integration with Jenkins for iOS | SuperSpeakers@CodeCamp Iasi, 2014
 
Click’n’Deploy | SuperSpeakers @CodeCamp Iasi, 2014
Click’n’Deploy | SuperSpeakers @CodeCamp Iasi, 2014Click’n’Deploy | SuperSpeakers @CodeCamp Iasi, 2014
Click’n’Deploy | SuperSpeakers @CodeCamp Iasi, 2014
 
Marketplace Innovation Report | Q2 2014
Marketplace Innovation Report | Q2 2014 Marketplace Innovation Report | Q2 2014
Marketplace Innovation Report | Q2 2014
 
Innovation in Mobile Payments
Innovation in Mobile PaymentsInnovation in Mobile Payments
Innovation in Mobile Payments
 
Marketplace Innovation Report | Q1 2014
Marketplace Innovation Report | Q1 2014Marketplace Innovation Report | Q1 2014
Marketplace Innovation Report | Q1 2014
 
Endava Marketplace Innovation Q4 2013
Endava Marketplace Innovation Q4 2013Endava Marketplace Innovation Q4 2013
Endava Marketplace Innovation Q4 2013
 
Endava Marketplace Innovation Q3 2013
Endava Marketplace Innovation Q3 2013Endava Marketplace Innovation Q3 2013
Endava Marketplace Innovation Q3 2013
 
Darwin Agile and The Dinosaurs
Darwin Agile and The DinosaursDarwin Agile and The Dinosaurs
Darwin Agile and The Dinosaurs
 
Have you ever seen a BA?
Have you ever seen a BA?Have you ever seen a BA?
Have you ever seen a BA?
 
Endava @ CodeCamp Cluj - SharePoint 2010 for business needs by Levente Veres
Endava @ CodeCamp Cluj  - SharePoint 2010 for business needs by Levente VeresEndava @ CodeCamp Cluj  - SharePoint 2010 for business needs by Levente Veres
Endava @ CodeCamp Cluj - SharePoint 2010 for business needs by Levente Veres
 
Endava Career Days Iasi Jan 2012 - Looking Inside the Scrum
Endava Career Days Iasi Jan 2012  - Looking Inside the ScrumEndava Career Days Iasi Jan 2012  - Looking Inside the Scrum
Endava Career Days Iasi Jan 2012 - Looking Inside the Scrum
 

Último

Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsNanddeep Nachan
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024The Digital Insurer
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Zilliz
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...apidays
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...Zilliz
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu SubbuApidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbuapidays
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot ModelNavi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot ModelDeepika Singh
 

Último (20)

Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu SubbuApidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot ModelNavi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 

Refactoring legacy code: step-by-step examples

  • 2. This is not a work of fiction. Design Flaws and Bugs are neither the product of the author's imagination nor used fictitiously. Any resemblance to real legacy projects is entirely non coincidental.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8. Uses many attributes from external classes Is excessively large and complex Is very non-cohesive
  • 9. Data and behavior that acts on that data belong together. When a method makes too many calls to other classes to obtain data or functionality, Feature Envy is in the air. 4 methods are affected by this design flaw
  • 10. All methods are envy on Policy Details Extended form datas
  • 11. This is a Context Object and its role is to encapsulate state in a protocol independent way. This Design Flow doesn't harm the application and can be ignored POST /path/policy.do HTTP/1.0 User-Agent: HTTPTool/1.0 Content-Type: application/x-www-form-urlencoded Content-Length: 532 policyType=1&eCommerceSys=153 SubBrokers DelegatedAuthorities ... PolicyDetailsForm PolicyDetailsExtendedForm - policyState - policyTypeId - billCoding - manualAdjustable - referringAgent - ... Categories eCommerceSystems Underwriters
  • 12. This is the MAJOR design flow found in this class. The Long Methods with very high cyclomatic complexity make the code hard to understand, maintain and test. 105 + 98 + 76 + 30 + 11 + 10 + 10 + … = 350 ~ 400
  • 13.
  • 14. 1. Orchestrates Business Services (3) «ApplicationController» RequestProcessor «Command» Action «PresentationModel» ActionForm «POJO» BusinessService «JSP» View View Helper «Domain Model» Policy adapt use 0..* manage access 1..* populate invoke dispatch creates 1 2 3 4 5 6 7 POST /path/policy.do HTTP/1.0 User-Agent: HTTPTool/1.0 policyType=1&transType=newPolicy
  • 15. 2. Provides Presentation Model initialization - policy type specific business rules are applied - New Policy, Init
  • 16. 3. Provides Presentation Model validation - policy type specific business rules are applied - Save, Decline Quote, New Coverage, Apply SubBrokers DelegatedAuthorities ... PolicyDetailsForm PolicyDetailsExtendedForm - policyState - policyTypeId - billCoding - manualAdjustable - referringAgent - ... Categories eCommerceSystems Underwriters
  • 17. 4. Populates the Domain Model using the values provided by Presentation Model – some values are copied others are derived using policy type specific business rules - Save, Decline Quote, New Coverage, Set WIP Data , Apply
  • 18. 60 50 40 30 20 10 0 PolicyDetailsExtendedAction number of commits per year commits 2008 2009 2010 2011 2012 2013 2014
  • 19. Refactoring is the 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 structure.
  • 20. 4 Rules to keep in mind when refactoring code:  It passes ALL the tests (preserve its external behavior)  It minimizes duplication in all its forms  It expresses its intent clearly to the reader  It removes unnecessary element
  • 21. It passes ALL the tests (preserve its external behavior) 0,0% 7.631 Number of execution paths • One unit test case in 3 minutes • One man day (6 hours) = 120 branches covered per day • 7631 / 120 ~ 64 days • 5 day per week = 13 weeks TOTAL: 3+ months
  • 22. It allows for quick production of reliable non regression tests to facilitate code refactoring.
  • 23.  Generate enough pseudo-random data  Use a code coverage data
  • 24. if (PolicyTypes.isUKPolicyType(policy.getPolicyTypeId().intValue()) || _form.getStatus() == Status.RENEWING) { if (_form.getWinsArpCode().equals("Y")) { policy.setBookedStatus(BookingStatus.ELIGIBLE_FOR_AUTOBOOKING_HELD); } else if (_form.getWinsArpCode().equals("C")) { policy.setBookedStatus(BookingStatus.FORCED_INVITE); } else if (_form.getWinsArpCode().equals("E")) { policy.setBookedStatus(BookingStatus.ELIGIBLE_FOR_AUTOBOOKING); } } 1 1 {UK/Travel=1, IT/Travel=7} 2 2 {RENEWING=W,NEW=N} 3 3 {Y,C,E}
  • 25. 1 7 Y Y Y Y C C C C E E E E T ValuesGenerator + ValuesGenerator(List<T>) + getNextValue() : T PolicyTypeGenerator + getNextValue() : int FormStatusGenerator + getNextValue() : char 1 FormWinsArpCodeGenerator + getNextValue() : String W W N N 2 3 1 7 1 7 1 7 1 7 1 7 1 7 W W N N W W N N W W N N Y Y Y Y C C C C E E E E 12
  • 26. Find a way to capture the output of the system without changing the production code Direct output  HttpSession (Domain Model)  Presentation Model  HttpRequest  Computed ActionForward  Thrown Exceptions Indirect output  Errors sent by email to operation team
  • 27.  Use a non intrusive solution - the existing code should not be modified  Non Serializable objects must be serialized too  Persist the output into a human readable format  Provide a mechanism to omit some fields Current date/time populated somewhere by one of the SUT indirect colaborators Error stack serializer.registerOmitField(Policy.class, “creationDate"); serializer.registerOmitField(Policy.class, "lastModifiedDate"); serializer.registerOmitField(Throwable.class, "stackTrace"); framework: XStream
  • 28. Number of execution paths 98,0%
  • 29. Missing return statement zoneReferred value is computed but not used – always returns 0 b.c.
  • 30. Dead Code the second branch is unreachable because the generateDynamicList variable is hardcoded to true
  • 31. Unnecessary null check if the address is null, a new address is created on the fly.
  • 32. Policy Type is used to implement business rules variations for all 3 responsibilities:  initialize  validate  save 32 Accident / Travel ITA 2010
  • 33. Method body Method body Common to ALL COUNTRY specific YEAR / TYPE specific > 1k
  • 34. Common to ALL Policies Common to a specific COUNTRY Specific by YEAR / TYPE ALL IT 2010/Travel 2012/Travel UK 2010/Accident RESPONSIBILITIES I N I T I A L I Z E V A L I D A T E S A V E
  • 35.  Single Responsibility Principle  Open for Extension Close for Modification  Group together things that change together
  • 36. InitializationRulesFactory + getRulesForPolicyType() : InitializationRules asks provides PolicyAction # initialize() : void # validate() : void «interface» InitializationRules use + initialize() : void CommonInitializationRules + initialize() : void DEUInitializationRules + initialize() : void UKInitializationRules + initialize() : void UK2012InitializationRules + initialize() : void ValidationRulesFactory + getRulesForPolicyType() : ValidationRules «interface» ValidationRules + validate() : void CommonValidationRules + validate() : void UKValidationRules + validate() : void DEUValidationRules + validate() : void UK2012ValidationRules + validate() : void UK2014ValidationRules + validate() : void use asks provides
  • 37. red green refactor commit green revert
  • 38. A. Extract ALL initialization rules into a new Class The refactoring steps are depicted below  Use Extract Class and create a new class to express the split-off responsibilities  Use Move Field on each relevant field  Use Move Method to move method over from old class to new one  Use Replace constructor with Factory Method and create a new dedicated class responsible to provide the right subclass of InitializePolicyFormService based on Policy Type. In this way we separate the instantiation responsibility from initialization responsibility.
  • 39. B. Extract NDL specific initialization rules into a new Subclass that extends the Class created above The refactoring steps are depicted below  Use Extract Subclass and define a new subclass that hosts the specific NDL initialization rules  Use Push Down Method on methods specific to NDL.  Copy methods that contains conditional logic specific to NDL and simplify the method preserving only the conditional leg relevant for NDL context. Make the original method protected  Update the Factory Class to return this subclass if Policy Type belongs to NDL
  • 40. C. Refactor the Factory Method  Use Replace conditional dispatcher with Command D. Repeat steps (B) and (C) for each Country / Year / Policy Type.
  • 41. Refactoring Improves the Design of Software  Without refactoring, the design of the program will decay (people change code to realize short-term goals without a full comprehension of the design)  Loss of the structure of code has a cumulative effect (the harder it is to see the design in the code, the harder it is to preserve it)
  • 42.
  • 43.
  • 44. Books  http://www.amazon.com/Refactoring-Improving-Design-Existing-Code/dp/0201485672  http://www.amazon.com/Refactoring-Patterns-Joshua-Kerievsky/dp/0321213351 Articles  http://java.dzone.com/articles/testing-legacy-code-golden  http://blog.adrianbolboaca.ro/2014/05/legacy-coderetreat-golden-master/  http://martinsson-johan.blogspot.fr/2014/01/golden-master-and-legacy-few-insights.html Tools  http://approvaltests.sourceforge.net/  http://xstream.codehaus.org/

Notas del editor

  1. Emergent design – create an initial design and then extend the design as we learn more
  2. Emergent design – create an initial design and then extend the design as we learn more
  3. Emergent design – create an initial design and then extend the design as we learn more