SlideShare a Scribd company logo
Working Effectively with Legacy Code – Part I-ShriKantVashishthaAug 19, 2009
Four Reasons to Change SoftwareAdding a featureFixing a bugImproving the designOptimizing resource usage
A Legacy Code ScenarioWhat changes do we have to make?How will we know that we have done them correctlyHow will we know that we haven’t broken anythingAvoiding change is a bad thing, but what is our alternative?Try harder. Hire more people
Way of doing changes - Edit and Pray
Way of doing changes - Cover and Modify
Why Unit Tests Are Important?Error localizationExecution timeCoverage
A Typical Legacy Code Sample
Legacy Code DilemmaWhen we change code, we should have tests in place. To put tests in place, we often have to change code.Use Primitivize Parameter and Extract Interface to remove these issues
Fake Objects
Fake Objects
Fake objects Support Real Testspublic class FakeDisplay implements Display{    private String lastLine = "";    public void showLine(String line) {lastLine = line;    }    public String getLastLine() {        return lastLine;    }}import junit.framework.*;public class SaleTest extends TestCase{    public void testDisplayAnItem() {FakeDisplay display = new FakeDisplay();        Sale sale = new Sale(display);sale.scan("1");assertEquals("Milk $3.99", display.getLastLine());    }}
SeamsboolCAsyncSslRec::Init(){    …    if (!m_bFailureSent) {m_bFailureSent=TRUE;PostReceiveError(SOCKETCALLBACK, SSL_FAILURE);    }CreateLibrary(m_hSslDll1,"syncesel1.dll");CreateLibrary(m_hSslDll2,"syncesel2.dll");    ….    return true;}
Object Seamclass CAsyncSslRec{    ...    virtual void PostReceiveError(UINT type, UINT errorcode);    ...};class TestingAsyncSslRec : public CAsyncSslRec{    virtual void PostReceiveError(UINT type, UINT errorcode)    {    }};
Seam TypesPreprocessing SeamsLink Seams : static linking in C/C++/Flex and dynamic linking in JavaObject Seams
I Don't Have Much Time and I Have to Change ItSprout MethodSprout ClassWrap MethodWrap Class
Sprout Methodpublic class TransactionGate{    public void postEntries(List entries) {        for (Iterator it = entries.iterator(); it.hasNext(); ) {            Entry entry = (Entry)it.next();entry.postDate();        }transactionBundle.getListManager().add(entries);    }    ...}
Sprout Methodpublic class TransactionGate{    public void postEntries(List entries) {        List entriesToAdd = new LinkedList();        for (Iterator it = entries.iterator(); it.hasNext(); ) {            Entry entry = (Entry)it.next();   if (!transactionBundle.getListManager().hasEntry(entry) {entry.postDate();entriesToAdd.add(entry);            }        }transactionBundle.getListManager().add(entriesToAdd);    }    ...}
Sprout Methodpublic class TransactionGate{    ...    List uniqueEntries(List entries) {        List result = new ArrayList();        for (Iterator it = entries.iterator(); it.hasNext(); ) {            Entry entry = (Entry)it.next();            if (!transactionBundle.getListManager().hasEntry(entry) {result.add(entry);            }        }        return result;    }    ...}public class TransactionGate{    ...    public void postEntries(List entries) {        List entriesToAdd = uniqueEntries(entries);        for (Iterator it = entriesToAdd.iterator(); it.hasNext(); ) {            Entry entry = (Entry)it.next();entry.postDate();        }transactionBundle.getListManager().add(entriesToAdd);    }    ...}
Sprout Classstd::string QuarterlyReportGenerator::generate(){    std::vector<Result> results = database.queryResults(beginDate, endDate);    std::string pageText;pageText += "<html><head><title>"            "Quarterly Report"            "</title></head><body><table>";    if (results.size() != 0) {        for (std::vector<Result>::iterator it = results.begin();                it != results.end();                ++it) {pageText += "<tr>";pageText += "<td>" + it->department + "</td>";pageText += "<td>" + it->manager + "</td>";            char buffer [128];sprintf(buffer, "<td>$%d</td>", it->netProfit / 100);pageText += std::string(buffer);sprintf(buffer, "<td>$%d</td>", it->operatingExpense / 100);pageText += std::string(buffer);pageText += "</tr>";        }    } else {pageText += "No results for this period";    }pageText += "</table>";pageText += "</body>";pageText += "</html>";    return pageText;}
Wrap Methodpublic class Employee{    ...    public void pay() {        Money amount = new Money();        for (Iterator it = timecards.iterator(); it.hasNext(); ) {            Timecard card = (Timecard)it.next();            if (payPeriod.contains(date)) {amount.add(card.getHours() * payRate);            }        }payDispatcher.pay(this, date, amount);    }}
Wrap Methodpublic class Employee{    private void dispatchPayment() {        Money amount = new Money();        for (Iterator it = timecards.iterator(); it.hasNext(); ) {            Timecard card = (Timecard)it.next();            if (payPeriod.contains(date)) {amount.add(card.getHours() * payRate);            }        }payDispatcher.pay(this, date, amount);    }    public void pay() {logPayment();dispatchPayment();    }    private void logPayment() {    ...    }}
Wrap MethodAdvantagesA good way of getting new, tested functionality into an application when we can't easily write tests for the calling codeIt explicitly makes the new functionality independent of existing functionalityDisadvantagesCan lead to poor names
Wrap Classclass Employee{    public void pay() {        Money amount = new Money();        for (Iterator it = timecards.iterator(); it.hasNext(); ) {            Timecard card = (Timecard)it.next();            if (payPeriod.contains(date)) {amount.add(card.getHours() * payRate);            }        }payDispatcher.pay(this, date, amount);    }    ...}
Wrap Classclass LoggingEmployee extends Employee{    public LoggingEmployee(Employee e) {        employee = e;    }    public void pay() {logPayment();employee.pay();    }    private void logPayment() {        ...    }    ...}
Wrap Classclass LoggingPayDispatcher{    private Employee e;    public LoggingPayDispatcher(Employee e) {this.e  = e;    }    public void pay() {employee.pay();logPayment();    }    private void logPayment() {        ...    }    ...}
Wrap ClassAble to add new behavior into a system without adding it to an existing classWhen there are many calls to the code you want to wrap, it often pays to move toward a decorator-ish wrapperIf new behavior has to happen at couple of places, simple class wrapper is very useful
I Don't Have Much Time and I Have to Change It: SummaryUse Sprout Method when the code you have in the existing method communicates a clear algorithm to the reader. Use Wrap Method when you think that the new feature you’re adding is as important as the work that was there beforeUse Wrap Class when the behavior that I want to add is completely independent
Ad

More Related Content

What's hot (20)

High performance web programming with C++14
High performance web programming with C++14High performance web programming with C++14
High performance web programming with C++14
Matthieu Garrigues
 
Is your C# optimized
Is your C# optimizedIs your C# optimized
Is your C# optimized
Woody Pewitt
 
Operator overloading2
Operator overloading2Operator overloading2
Operator overloading2
zindadili
 
Automatically Describing Program Structure and Behavior (PhD Defense)
Automatically Describing Program Structure and Behavior (PhD Defense)Automatically Describing Program Structure and Behavior (PhD Defense)
Automatically Describing Program Structure and Behavior (PhD Defense)
Ray Buse
 
81818088 isc-class-xii-computer-science-project-java-programs
81818088 isc-class-xii-computer-science-project-java-programs81818088 isc-class-xii-computer-science-project-java-programs
81818088 isc-class-xii-computer-science-project-java-programs
Abhishek Jena
 
Антихрупкий TypeScript | Odessa Frontend Meetup #17
Антихрупкий TypeScript | Odessa Frontend Meetup #17Антихрупкий TypeScript | Odessa Frontend Meetup #17
Антихрупкий TypeScript | Odessa Frontend Meetup #17
OdessaFrontend
 
FP 201 - Unit 3 Part 2
FP 201 - Unit 3 Part 2FP 201 - Unit 3 Part 2
FP 201 - Unit 3 Part 2
rohassanie
 
Java Simple Programs
Java Simple ProgramsJava Simple Programs
Java Simple Programs
Upender Upr
 
The secret unit testing tools no one ever told you about
The secret unit testing tools no one ever told you aboutThe secret unit testing tools no one ever told you about
The secret unit testing tools no one ever told you about
Dror Helper
 
Computer science project work
Computer science project workComputer science project work
Computer science project work
rahulchamp2345
 
Simple Java Programs
Simple Java ProgramsSimple Java Programs
Simple Java Programs
AravindSankaran
 
DSU C&C++ Practical File Diploma
DSU C&C++ Practical File DiplomaDSU C&C++ Practical File Diploma
DSU C&C++ Practical File Diploma
mustkeem khan
 
FP 201 - Unit 6
FP 201 - Unit 6FP 201 - Unit 6
FP 201 - Unit 6
rohassanie
 
Automatically Documenting Program Changes
Automatically Documenting Program ChangesAutomatically Documenting Program Changes
Automatically Documenting Program Changes
Ray Buse
 
Lambda Expressions in C++
Lambda Expressions in C++Lambda Expressions in C++
Lambda Expressions in C++
Patrick Viafore
 
C# console programms
C# console programmsC# console programms
C# console programms
Yasir Khan
 
Fp201 unit5 1
Fp201 unit5 1Fp201 unit5 1
Fp201 unit5 1
rohassanie
 
C program
C programC program
C program
Komal Singh
 
Bijender (1)
Bijender (1)Bijender (1)
Bijender (1)
Ankush Kumar
 
C programs
C programsC programs
C programs
Vikram Nandini
 
High performance web programming with C++14
High performance web programming with C++14High performance web programming with C++14
High performance web programming with C++14
Matthieu Garrigues
 
Is your C# optimized
Is your C# optimizedIs your C# optimized
Is your C# optimized
Woody Pewitt
 
Operator overloading2
Operator overloading2Operator overloading2
Operator overloading2
zindadili
 
Automatically Describing Program Structure and Behavior (PhD Defense)
Automatically Describing Program Structure and Behavior (PhD Defense)Automatically Describing Program Structure and Behavior (PhD Defense)
Automatically Describing Program Structure and Behavior (PhD Defense)
Ray Buse
 
81818088 isc-class-xii-computer-science-project-java-programs
81818088 isc-class-xii-computer-science-project-java-programs81818088 isc-class-xii-computer-science-project-java-programs
81818088 isc-class-xii-computer-science-project-java-programs
Abhishek Jena
 
Антихрупкий TypeScript | Odessa Frontend Meetup #17
Антихрупкий TypeScript | Odessa Frontend Meetup #17Антихрупкий TypeScript | Odessa Frontend Meetup #17
Антихрупкий TypeScript | Odessa Frontend Meetup #17
OdessaFrontend
 
FP 201 - Unit 3 Part 2
FP 201 - Unit 3 Part 2FP 201 - Unit 3 Part 2
FP 201 - Unit 3 Part 2
rohassanie
 
Java Simple Programs
Java Simple ProgramsJava Simple Programs
Java Simple Programs
Upender Upr
 
The secret unit testing tools no one ever told you about
The secret unit testing tools no one ever told you aboutThe secret unit testing tools no one ever told you about
The secret unit testing tools no one ever told you about
Dror Helper
 
Computer science project work
Computer science project workComputer science project work
Computer science project work
rahulchamp2345
 
DSU C&C++ Practical File Diploma
DSU C&C++ Practical File DiplomaDSU C&C++ Practical File Diploma
DSU C&C++ Practical File Diploma
mustkeem khan
 
FP 201 - Unit 6
FP 201 - Unit 6FP 201 - Unit 6
FP 201 - Unit 6
rohassanie
 
Automatically Documenting Program Changes
Automatically Documenting Program ChangesAutomatically Documenting Program Changes
Automatically Documenting Program Changes
Ray Buse
 
Lambda Expressions in C++
Lambda Expressions in C++Lambda Expressions in C++
Lambda Expressions in C++
Patrick Viafore
 
C# console programms
C# console programmsC# console programms
C# console programms
Yasir Khan
 

Similar to Working effectively with legacy code (20)

SystemVerilog OOP Ovm Features Summary
SystemVerilog OOP Ovm Features SummarySystemVerilog OOP Ovm Features Summary
SystemVerilog OOP Ovm Features Summary
Amal Khailtash
 
Category theory, Monads, and Duality in the world of (BIG) Data
Category theory, Monads, and Duality in the world of (BIG) DataCategory theory, Monads, and Duality in the world of (BIG) Data
Category theory, Monads, and Duality in the world of (BIG) Data
greenwop
 
Lo Mejor Del Pdc2008 El Futrode C#
Lo Mejor Del Pdc2008 El Futrode C#Lo Mejor Del Pdc2008 El Futrode C#
Lo Mejor Del Pdc2008 El Futrode C#
Juan Pablo
 
Java Generics
Java GenericsJava Generics
Java Generics
Carol McDonald
 
Practices For Becoming A Better Programmer
Practices For Becoming A Better ProgrammerPractices For Becoming A Better Programmer
Practices For Becoming A Better Programmer
Srikanth Shreenivas
 
20.1 Java working with abstraction
20.1 Java working with abstraction20.1 Java working with abstraction
20.1 Java working with abstraction
Intro C# Book
 
Anti patterns
Anti patternsAnti patterns
Anti patterns
Alex Tumanoff
 
Clean Code: Chapter 3 Function
Clean Code: Chapter 3 FunctionClean Code: Chapter 3 Function
Clean Code: Chapter 3 Function
Kent Huang
 
Chapter 2
Chapter 2Chapter 2
Chapter 2
application developer
 
Ruslan Platonov - Transactions
Ruslan Platonov - TransactionsRuslan Platonov - Transactions
Ruslan Platonov - Transactions
Dmitry Buzdin
 
Clean code _v2003
 Clean code _v2003 Clean code _v2003
Clean code _v2003
R696
 
Clean coding-practices
Clean coding-practicesClean coding-practices
Clean coding-practices
John Ferguson Smart Limited
 
Embedded Typesafe Domain Specific Languages for Java
Embedded Typesafe Domain Specific Languages for JavaEmbedded Typesafe Domain Specific Languages for Java
Embedded Typesafe Domain Specific Languages for Java
Jevgeni Kabanov
 
Liferay Training Struts Portlet
Liferay Training Struts PortletLiferay Training Struts Portlet
Liferay Training Struts Portlet
Saikrishna Basetti
 
JDD 2016 - Sebastian Malaca - You Dont Need Unit Tests
JDD 2016 - Sebastian Malaca - You Dont Need Unit TestsJDD 2016 - Sebastian Malaca - You Dont Need Unit Tests
JDD 2016 - Sebastian Malaca - You Dont Need Unit Tests
PROIDEA
 
Reactive programming every day
Reactive programming every dayReactive programming every day
Reactive programming every day
Vadym Khondar
 
Rx workshop
Rx workshopRx workshop
Rx workshop
Ryan Riley
 
Mixing functional and object oriented approaches to programming in C#
Mixing functional and object oriented approaches to programming in C#Mixing functional and object oriented approaches to programming in C#
Mixing functional and object oriented approaches to programming in C#
Mark Needham
 
Mixing Functional and Object Oriented Approaches to Programming in C#
Mixing Functional and Object Oriented Approaches to Programming in C#Mixing Functional and Object Oriented Approaches to Programming in C#
Mixing Functional and Object Oriented Approaches to Programming in C#
Skills Matter
 
Pragmatic functional refactoring with java 8
Pragmatic functional refactoring with java 8Pragmatic functional refactoring with java 8
Pragmatic functional refactoring with java 8
RichardWarburton
 
SystemVerilog OOP Ovm Features Summary
SystemVerilog OOP Ovm Features SummarySystemVerilog OOP Ovm Features Summary
SystemVerilog OOP Ovm Features Summary
Amal Khailtash
 
Category theory, Monads, and Duality in the world of (BIG) Data
Category theory, Monads, and Duality in the world of (BIG) DataCategory theory, Monads, and Duality in the world of (BIG) Data
Category theory, Monads, and Duality in the world of (BIG) Data
greenwop
 
Lo Mejor Del Pdc2008 El Futrode C#
Lo Mejor Del Pdc2008 El Futrode C#Lo Mejor Del Pdc2008 El Futrode C#
Lo Mejor Del Pdc2008 El Futrode C#
Juan Pablo
 
Practices For Becoming A Better Programmer
Practices For Becoming A Better ProgrammerPractices For Becoming A Better Programmer
Practices For Becoming A Better Programmer
Srikanth Shreenivas
 
20.1 Java working with abstraction
20.1 Java working with abstraction20.1 Java working with abstraction
20.1 Java working with abstraction
Intro C# Book
 
Clean Code: Chapter 3 Function
Clean Code: Chapter 3 FunctionClean Code: Chapter 3 Function
Clean Code: Chapter 3 Function
Kent Huang
 
Ruslan Platonov - Transactions
Ruslan Platonov - TransactionsRuslan Platonov - Transactions
Ruslan Platonov - Transactions
Dmitry Buzdin
 
Clean code _v2003
 Clean code _v2003 Clean code _v2003
Clean code _v2003
R696
 
Embedded Typesafe Domain Specific Languages for Java
Embedded Typesafe Domain Specific Languages for JavaEmbedded Typesafe Domain Specific Languages for Java
Embedded Typesafe Domain Specific Languages for Java
Jevgeni Kabanov
 
Liferay Training Struts Portlet
Liferay Training Struts PortletLiferay Training Struts Portlet
Liferay Training Struts Portlet
Saikrishna Basetti
 
JDD 2016 - Sebastian Malaca - You Dont Need Unit Tests
JDD 2016 - Sebastian Malaca - You Dont Need Unit TestsJDD 2016 - Sebastian Malaca - You Dont Need Unit Tests
JDD 2016 - Sebastian Malaca - You Dont Need Unit Tests
PROIDEA
 
Reactive programming every day
Reactive programming every dayReactive programming every day
Reactive programming every day
Vadym Khondar
 
Mixing functional and object oriented approaches to programming in C#
Mixing functional and object oriented approaches to programming in C#Mixing functional and object oriented approaches to programming in C#
Mixing functional and object oriented approaches to programming in C#
Mark Needham
 
Mixing Functional and Object Oriented Approaches to Programming in C#
Mixing Functional and Object Oriented Approaches to Programming in C#Mixing Functional and Object Oriented Approaches to Programming in C#
Mixing Functional and Object Oriented Approaches to Programming in C#
Skills Matter
 
Pragmatic functional refactoring with java 8
Pragmatic functional refactoring with java 8Pragmatic functional refactoring with java 8
Pragmatic functional refactoring with java 8
RichardWarburton
 
Ad

More from ShriKant Vashishtha (14)

Evolution of Agile world with Lean Startup Concepts
 Evolution of Agile world with Lean Startup Concepts Evolution of Agile world with Lean Startup Concepts
Evolution of Agile world with Lean Startup Concepts
ShriKant Vashishtha
 
Distributed Agile Patterns
Distributed Agile PatternsDistributed Agile Patterns
Distributed Agile Patterns
ShriKant Vashishtha
 
What is Agile Testing
What is Agile TestingWhat is Agile Testing
What is Agile Testing
ShriKant Vashishtha
 
Pair Programming and XP Values
Pair Programming and XP ValuesPair Programming and XP Values
Pair Programming and XP Values
ShriKant Vashishtha
 
How to build a fun team
How to build a fun teamHow to build a fun team
How to build a fun team
ShriKant Vashishtha
 
How to Break the Requirements into User Stories
How to Break the Requirements into User StoriesHow to Break the Requirements into User Stories
How to Break the Requirements into User Stories
ShriKant Vashishtha
 
Agile Maintenance by ShriKant Vashishtha
Agile Maintenance by ShriKant VashishthaAgile Maintenance by ShriKant Vashishtha
Agile Maintenance by ShriKant Vashishtha
ShriKant Vashishtha
 
Working With Augmented Distributed Agile Team In Legacy Application
Working With Augmented Distributed Agile Team In Legacy ApplicationWorking With Augmented Distributed Agile Team In Legacy Application
Working With Augmented Distributed Agile Team In Legacy Application
ShriKant Vashishtha
 
Agile FAQs by ShriKant Vashishtha
Agile FAQs by ShriKant VashishthaAgile FAQs by ShriKant Vashishtha
Agile FAQs by ShriKant Vashishtha
ShriKant Vashishtha
 
TheOtherPages Pagination Framework by Shrikant Vashishtha
TheOtherPages Pagination Framework by Shrikant VashishthaTheOtherPages Pagination Framework by Shrikant Vashishtha
TheOtherPages Pagination Framework by Shrikant Vashishtha
ShriKant Vashishtha
 
Caching fundamentals by Shrikant Vashishtha
Caching fundamentals by Shrikant VashishthaCaching fundamentals by Shrikant Vashishtha
Caching fundamentals by Shrikant Vashishtha
ShriKant Vashishtha
 
Pair Programming Explained By Shrikant Vashishtha
Pair Programming Explained  By Shrikant VashishthaPair Programming Explained  By Shrikant Vashishtha
Pair Programming Explained By Shrikant Vashishtha
ShriKant Vashishtha
 
Management and Self Learning Lessons from Indian Mythology
Management and Self Learning Lessons from Indian MythologyManagement and Self Learning Lessons from Indian Mythology
Management and Self Learning Lessons from Indian Mythology
ShriKant Vashishtha
 
Memory Management In C++
Memory Management In C++Memory Management In C++
Memory Management In C++
ShriKant Vashishtha
 
Evolution of Agile world with Lean Startup Concepts
 Evolution of Agile world with Lean Startup Concepts Evolution of Agile world with Lean Startup Concepts
Evolution of Agile world with Lean Startup Concepts
ShriKant Vashishtha
 
How to Break the Requirements into User Stories
How to Break the Requirements into User StoriesHow to Break the Requirements into User Stories
How to Break the Requirements into User Stories
ShriKant Vashishtha
 
Agile Maintenance by ShriKant Vashishtha
Agile Maintenance by ShriKant VashishthaAgile Maintenance by ShriKant Vashishtha
Agile Maintenance by ShriKant Vashishtha
ShriKant Vashishtha
 
Working With Augmented Distributed Agile Team In Legacy Application
Working With Augmented Distributed Agile Team In Legacy ApplicationWorking With Augmented Distributed Agile Team In Legacy Application
Working With Augmented Distributed Agile Team In Legacy Application
ShriKant Vashishtha
 
Agile FAQs by ShriKant Vashishtha
Agile FAQs by ShriKant VashishthaAgile FAQs by ShriKant Vashishtha
Agile FAQs by ShriKant Vashishtha
ShriKant Vashishtha
 
TheOtherPages Pagination Framework by Shrikant Vashishtha
TheOtherPages Pagination Framework by Shrikant VashishthaTheOtherPages Pagination Framework by Shrikant Vashishtha
TheOtherPages Pagination Framework by Shrikant Vashishtha
ShriKant Vashishtha
 
Caching fundamentals by Shrikant Vashishtha
Caching fundamentals by Shrikant VashishthaCaching fundamentals by Shrikant Vashishtha
Caching fundamentals by Shrikant Vashishtha
ShriKant Vashishtha
 
Pair Programming Explained By Shrikant Vashishtha
Pair Programming Explained  By Shrikant VashishthaPair Programming Explained  By Shrikant Vashishtha
Pair Programming Explained By Shrikant Vashishtha
ShriKant Vashishtha
 
Management and Self Learning Lessons from Indian Mythology
Management and Self Learning Lessons from Indian MythologyManagement and Self Learning Lessons from Indian Mythology
Management and Self Learning Lessons from Indian Mythology
ShriKant Vashishtha
 
Ad

Recently uploaded (20)

SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdfSAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
Precisely
 
What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...
Vishnu Singh Chundawat
 
Andrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell: Transforming Business Strategy Through Data-Driven InsightsAndrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell
 
Quantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur MorganQuantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur Morgan
Arthur Morgan
 
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
Alan Dix
 
TrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business ConsultingTrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business Consulting
Trs Labs
 
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
BookNet Canada
 
Big Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur MorganBig Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur Morgan
Arthur Morgan
 
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In FranceManifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
chb3
 
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptxIncreasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Anoop Ashok
 
Drupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy ConsumptionDrupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy Consumption
Exove
 
Procurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptxProcurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptx
Jon Hansen
 
Cybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure ADCybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure AD
VICTOR MAESTRE RAMIREZ
 
HCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser EnvironmentsHCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser Environments
panagenda
 
Semantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AISemantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AI
artmondano
 
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul
 
Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.
hpbmnnxrvb
 
Role of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered ManufacturingRole of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered Manufacturing
Andrew Leo
 
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptxDevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
Justin Reock
 
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptxSpecial Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
shyamraj55
 
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdfSAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
Precisely
 
What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...
Vishnu Singh Chundawat
 
Andrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell: Transforming Business Strategy Through Data-Driven InsightsAndrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell
 
Quantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur MorganQuantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur Morgan
Arthur Morgan
 
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
Alan Dix
 
TrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business ConsultingTrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business Consulting
Trs Labs
 
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
BookNet Canada
 
Big Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur MorganBig Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur Morgan
Arthur Morgan
 
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In FranceManifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
chb3
 
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptxIncreasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Anoop Ashok
 
Drupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy ConsumptionDrupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy Consumption
Exove
 
Procurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptxProcurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptx
Jon Hansen
 
Cybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure ADCybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure AD
VICTOR MAESTRE RAMIREZ
 
HCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser EnvironmentsHCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser Environments
panagenda
 
Semantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AISemantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AI
artmondano
 
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul
 
Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.
hpbmnnxrvb
 
Role of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered ManufacturingRole of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered Manufacturing
Andrew Leo
 
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptxDevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
Justin Reock
 
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptxSpecial Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
shyamraj55
 

Working effectively with legacy code

  • 1. Working Effectively with Legacy Code – Part I-ShriKantVashishthaAug 19, 2009
  • 2. Four Reasons to Change SoftwareAdding a featureFixing a bugImproving the designOptimizing resource usage
  • 3. A Legacy Code ScenarioWhat changes do we have to make?How will we know that we have done them correctlyHow will we know that we haven’t broken anythingAvoiding change is a bad thing, but what is our alternative?Try harder. Hire more people
  • 4. Way of doing changes - Edit and Pray
  • 5. Way of doing changes - Cover and Modify
  • 6. Why Unit Tests Are Important?Error localizationExecution timeCoverage
  • 7. A Typical Legacy Code Sample
  • 8. Legacy Code DilemmaWhen we change code, we should have tests in place. To put tests in place, we often have to change code.Use Primitivize Parameter and Extract Interface to remove these issues
  • 11. Fake objects Support Real Testspublic class FakeDisplay implements Display{ private String lastLine = ""; public void showLine(String line) {lastLine = line; } public String getLastLine() { return lastLine; }}import junit.framework.*;public class SaleTest extends TestCase{ public void testDisplayAnItem() {FakeDisplay display = new FakeDisplay(); Sale sale = new Sale(display);sale.scan("1");assertEquals("Milk $3.99", display.getLastLine()); }}
  • 12. SeamsboolCAsyncSslRec::Init(){ … if (!m_bFailureSent) {m_bFailureSent=TRUE;PostReceiveError(SOCKETCALLBACK, SSL_FAILURE); }CreateLibrary(m_hSslDll1,"syncesel1.dll");CreateLibrary(m_hSslDll2,"syncesel2.dll"); …. return true;}
  • 13. Object Seamclass CAsyncSslRec{ ... virtual void PostReceiveError(UINT type, UINT errorcode); ...};class TestingAsyncSslRec : public CAsyncSslRec{ virtual void PostReceiveError(UINT type, UINT errorcode) { }};
  • 14. Seam TypesPreprocessing SeamsLink Seams : static linking in C/C++/Flex and dynamic linking in JavaObject Seams
  • 15. I Don't Have Much Time and I Have to Change ItSprout MethodSprout ClassWrap MethodWrap Class
  • 16. Sprout Methodpublic class TransactionGate{ public void postEntries(List entries) { for (Iterator it = entries.iterator(); it.hasNext(); ) { Entry entry = (Entry)it.next();entry.postDate(); }transactionBundle.getListManager().add(entries); } ...}
  • 17. Sprout Methodpublic class TransactionGate{ public void postEntries(List entries) { List entriesToAdd = new LinkedList(); for (Iterator it = entries.iterator(); it.hasNext(); ) { Entry entry = (Entry)it.next(); if (!transactionBundle.getListManager().hasEntry(entry) {entry.postDate();entriesToAdd.add(entry); } }transactionBundle.getListManager().add(entriesToAdd); } ...}
  • 18. Sprout Methodpublic class TransactionGate{ ... List uniqueEntries(List entries) { List result = new ArrayList(); for (Iterator it = entries.iterator(); it.hasNext(); ) { Entry entry = (Entry)it.next(); if (!transactionBundle.getListManager().hasEntry(entry) {result.add(entry); } } return result; } ...}public class TransactionGate{ ... public void postEntries(List entries) { List entriesToAdd = uniqueEntries(entries); for (Iterator it = entriesToAdd.iterator(); it.hasNext(); ) { Entry entry = (Entry)it.next();entry.postDate(); }transactionBundle.getListManager().add(entriesToAdd); } ...}
  • 19. Sprout Classstd::string QuarterlyReportGenerator::generate(){ std::vector<Result> results = database.queryResults(beginDate, endDate); std::string pageText;pageText += "<html><head><title>" "Quarterly Report" "</title></head><body><table>"; if (results.size() != 0) { for (std::vector<Result>::iterator it = results.begin(); it != results.end(); ++it) {pageText += "<tr>";pageText += "<td>" + it->department + "</td>";pageText += "<td>" + it->manager + "</td>"; char buffer [128];sprintf(buffer, "<td>$%d</td>", it->netProfit / 100);pageText += std::string(buffer);sprintf(buffer, "<td>$%d</td>", it->operatingExpense / 100);pageText += std::string(buffer);pageText += "</tr>"; } } else {pageText += "No results for this period"; }pageText += "</table>";pageText += "</body>";pageText += "</html>"; return pageText;}
  • 20. Wrap Methodpublic class Employee{ ... public void pay() { Money amount = new Money(); for (Iterator it = timecards.iterator(); it.hasNext(); ) { Timecard card = (Timecard)it.next(); if (payPeriod.contains(date)) {amount.add(card.getHours() * payRate); } }payDispatcher.pay(this, date, amount); }}
  • 21. Wrap Methodpublic class Employee{ private void dispatchPayment() { Money amount = new Money(); for (Iterator it = timecards.iterator(); it.hasNext(); ) { Timecard card = (Timecard)it.next(); if (payPeriod.contains(date)) {amount.add(card.getHours() * payRate); } }payDispatcher.pay(this, date, amount); } public void pay() {logPayment();dispatchPayment(); } private void logPayment() { ... }}
  • 22. Wrap MethodAdvantagesA good way of getting new, tested functionality into an application when we can't easily write tests for the calling codeIt explicitly makes the new functionality independent of existing functionalityDisadvantagesCan lead to poor names
  • 23. Wrap Classclass Employee{ public void pay() { Money amount = new Money(); for (Iterator it = timecards.iterator(); it.hasNext(); ) { Timecard card = (Timecard)it.next(); if (payPeriod.contains(date)) {amount.add(card.getHours() * payRate); } }payDispatcher.pay(this, date, amount); } ...}
  • 24. Wrap Classclass LoggingEmployee extends Employee{ public LoggingEmployee(Employee e) { employee = e; } public void pay() {logPayment();employee.pay(); } private void logPayment() { ... } ...}
  • 25. Wrap Classclass LoggingPayDispatcher{ private Employee e; public LoggingPayDispatcher(Employee e) {this.e = e; } public void pay() {employee.pay();logPayment(); } private void logPayment() { ... } ...}
  • 26. Wrap ClassAble to add new behavior into a system without adding it to an existing classWhen there are many calls to the code you want to wrap, it often pays to move toward a decorator-ish wrapperIf new behavior has to happen at couple of places, simple class wrapper is very useful
  • 27. I Don't Have Much Time and I Have to Change It: SummaryUse Sprout Method when the code you have in the existing method communicates a clear algorithm to the reader. Use Wrap Method when you think that the new feature you’re adding is as important as the work that was there beforeUse Wrap Class when the behavior that I want to add is completely independent

Editor's Notes

  • #3: It seems nearly impossible to add behavior without changing it to some degree.Improving design – a series of small structural modifications, supported by tests to make the code easier to change.Optimization – functionality exactly the same but changing something else (usually time or memory)
  • #4: Talk about a team policy where – if it’s not broke, don’t fix it. – Talk about problems it createsDifference between good and bad systems
  • #5: Working with care – leads to using tools and techniques inefficiently
  • #6: Use of safety netCovering software means covering with testsTesting to attempt to show correctnessVsTesting to detect change – tests as software vise – keep most of the behavior fixed and change only what you intend toRegression tests with or without writing tests – mention a story about doing the testing at the end
  • #7: Other kinds of tests often masquerade as unit tests. A test is not a unit test if:It talks to a database.It communicates across a network.It touches the file system.You have to do special things to your environment (such as editing configuration files) to run it.
  • #8: Servlet and DBConnection are two issuesPossible option – pass real db connection but how about servlet itself
  • #12: Mock objects are advanced type of fakes.
  • #13: A seam is a place where you can alter behavior in your program without editing in that place.
  • #17: We need to add code to verify that none of the new entries are already in transactionBundle before we post their dates and add them.
  • #19: Disadvantages: Giving up on the codeAdvantages: Separating new code from old code
  • #20: &quot;&lt;tr&gt;&lt;td&gt;Department&lt;/td&gt;&lt;td&gt;Manager&lt;/td&gt;&lt;td&gt;Profit&lt;/td&gt;&lt;td&gt;Expenses&lt;/td&gt;&lt;/tr&gt;&quot;
  • #21: Every time that we pay an employee, we have to update a file with the employee&apos;s name so that it can be sent off to some reporting softwareThe easiest way to do….is method
  • #22: We create a method with the name of the original method and have it delegate to our old code
  • #25: Use of decoratorToolController controller = new StepNotifyingController( new AlarmingController ( new ACMEController()), notifyees);
  • #26: Without using decorator