SlideShare a Scribd company logo
Mariano Sánchez – Software Architect
marianos@lagash.com
Refactoring - Mejorando el diseño del código existente
Refactoring - Mejorando el diseño del código existente
Refactoring - Mejorando el diseño del código existente
Refactoring - Mejorando el diseño del código existente
http://www.refactoring.com/
Refactoring - Mejorando el diseño del código existente
Refactoring - Mejorando el diseño del código existente
Refactoring - Mejorando el diseño del código existente
Ejemplo 1: Switch statements
// set in constructor
Refactoring - Mejorando el diseño del código existente
Amphibian
public class Course
{
public List students;
}

int classSize = course.students.size();

public class Course
{
private List students;
public List getStudents()
{
return students;
}
public void setStudents(List s)
{
students = s;
}
}
int classSize = course.getStudents().size();
public class Customer
{
private String name;
private String workPhoneAreaCode;
private String workPhoneNumber;
}

public class Customer
{
private String name;
private Phone workPhone;
}
public class Phone
{
private String areaCode;
private String number;
}
public class Customer
{
private String name;
public String getName(){ return name; }
public void setName(String string)
{ name = string; }
public String toXML()
{ return "<Customer><Name>" +
name + "</Name></Customer>";
}
}

public class Customer implements SerXML
{
private String name;
public String getName(){ return name; }
public void setName(String string)
{ name = string; }
public String toXML()
{ return "<Customer><Name>" +
name + "</Name></Customer>";
}
}
public interface SerXml {
public abstract String toXML();
}
public class Customer
{
void int foo()
{
…
// Compute score
score = a*b+c;
score *= xfactor;
}
}

public class Customer
{
void int foo()
{
…
score = ComputeScore(a,b,c,xfactor);
}

}

int ComputeScore(int a, int b, int c, int x)
{
return (a*b+c)*x;
}
public class Person
{
private String name;
private String jobTitle;
}

public class Person
{
protected String name;
}
public class Employee extends Person
{
private String jobTitle;
}
public class Employee
{
private String name;
private String jobTitle;
}
public class Student
{
private String name;
private Course course;
}

public abstract class Person
{
protected String name;
}
public class Employee extends Person
{
private String jobTitle;
}
public class Student extends Person
{
private Course course;
}
public class Company extends Party
{
public abstract class Party { }
private String name;
private String companyType;
public class Person extends Party
private Date incorporated;
{
public void PrintNameAndDetails()
private String firstName;
{
private String lastName;
System.out.println("Name: " + name + " " +
private Date dob;
companyType);
private String nationality;
System.out.println("Incorporated: " +
public void printNameAndDetails()
incorporated.toString());
{
}
System.out.println("Name: " + firstName + " " + lastName);
}
System.out.println("DOB: " + dob.toString() + ", Nationality: " + nationality);
}
}
public abstract class Party
{
public void PrintNameAndDetails()
{
printName();
printDetails();
}
public abstract void printName();
public abstract void printDetails();
}

public class Company extends Party
{
private String name;
private String companyType;
private Date incorporated;
public void printDetails()
{
System.out.println("Incorporated: " + incorporated.toString());
}
public void printName()
{
System.out.println("Name: " + name + " " + companyType);
}
}

public class Person extends Party
{
private String firstName;
private String lastName;
private Date dob;
private String nationality;
public void printDetails()
{
System.out.println("DOB: " + dob.toString() + ", Nationality: " + nationality);
}
public class Student
{
public boolean isTaking(Course course)
{
return (course.getStudents().contains(this));
}
}
public class Course
{
private List students;
public List getStudents()
{
return students;
}
}

public class Student
{
}
public class Course
{
private List students;
public boolean isTaking(Student student)
{
return students.contains(student);
}
}
public class User
{
Plan getPlan()
{
return plan;
}
}

if (user == null)
plan = Plan.basic();
else
plan = user.getPlan();

public class User
{
Plan getPlan()
{
return plan;
}
}
public class NullUser extends User
{
Plan getPlan()
{
return Plan.basic();
}
}
int withdraw(int amount)
{
if (amount > balance)
return -1;
else {
balance -= amount;
return 0;
}
}

void withdraw(int amount)
throws BalanceException
{
if (amount > balance)
{
throw new BalanceException();
}
balance -= amount;
}
double getValueForPeriod (int periodNumber)
{
try
{
return values[periodNumber];
}
catch (ArrayIndexOutOfBoundsException e)
{
return 0;
}
}

double getValueForPeriod (int periodNumber)
{
if (periodNumber >= values.length) return 0;
return values[periodNumber];
}
double getPayAmount() {
double result;
if (isDead) result = deadAmount();
else {
if (isSeparated) result = separatedAmount();
else {
if (isRetired) result = retiredAmount();
else result = normalPayAmount();
}
}
return result;
}
double getPayAmount() {
if (isDead) return deadAmount();
if (isSeparated) return separatedAmount();
if (isRetired) return retiredAmount();
return normalPayAmount();
};
void setValue (String name, int value) {
if (name.equals("height")) {
height = value;
return;
}
if (name.equals("width")) {
width = value;
return;
}
Assert.shouldNeverReachHere();
}

void setHeight(int arg)
{
height = arg;
}
void setWidth (int arg)
{
width = arg;
}
double basePrice = quantity * itemPrice;
if (basePrice > 1000)
return basePrice * 0.95;
else
return basePrice * 0.98;

...

if (basePrice() > 1000)
return basePrice() * 0.95;
else
return basePrice() * 0.98;
double basePrice() {
return quantity * itemPrice;
}
public class Customer
{
public double getinvcdtlmt();
}

public class Customer
{
public double getInvoiceCreditLimit();
}
Refactoring - Mejorando el diseño del código existente
Muchas Gracias

Mariano Sánchez – Software Architect
marianos@lagash.com

More Related Content

PPTX
TDC2016POA | Trilha .NET - C# como você nunca viu: conceitos avançados de pro...
PPTX
TDC2016POA | Trilha .NET - CQRS e ES na prática com RavenDB
PPT
Oop objects_classes
PPTX
TDC2016SP - Trilha .NET
DOCX
Multi client
PDF
Refactoring e Code Smells: Seu código está apodrecendo!
PDF
Code Smells y SOLID: A qué huele tu código?
PPTX
Code Smells y Refactoring o haciendo que nuestro codigo huela (y se vea) mejo...
TDC2016POA | Trilha .NET - C# como você nunca viu: conceitos avançados de pro...
TDC2016POA | Trilha .NET - CQRS e ES na prática com RavenDB
Oop objects_classes
TDC2016SP - Trilha .NET
Multi client
Refactoring e Code Smells: Seu código está apodrecendo!
Code Smells y SOLID: A qué huele tu código?
Code Smells y Refactoring o haciendo que nuestro codigo huela (y se vea) mejo...

Similar to Refactoring - Mejorando el diseño del código existente (20)

PDF
Creating a Facebook Clone - Part XX.pdf
DOCX
OOP Lab Report.docx
PDF
public class Person { private String name; private int age;.pdf
PPTX
Inheritance 3.pptx
DOCX
Assignment 7
PPSX
DotNet Conference: code smells
KEY
How to Start Test-Driven Development in Legacy Code
PDF
Dev Day Andreas Roth.pdf
PDF
3. Объекты, классы и пакеты в Java
PPTX
C# Is The Future
PDF
Object Oriented Programming (OOP) using C++ - Lecture 4
PDF
Lombokの紹介
PDF
please help with java questionsJAVA CODEplease check my code and.pdf
PDF
29. Code an application program that keeps track of student informat.pdf
PDF
Manual tecnic sergi_subirats
PPTX
WINSEM2020-21_STS3105_SS_VL2020210500169_Reference_Material_I_15-Mar-2021_L15...
PDF
F# for C# Programmers
PDF
@author public class Person{   String sname, .pdf
PDF
C h 04 oop_inheritance
PDF
Creating a Facebook Clone - Part XIX.pdf
Creating a Facebook Clone - Part XX.pdf
OOP Lab Report.docx
public class Person { private String name; private int age;.pdf
Inheritance 3.pptx
Assignment 7
DotNet Conference: code smells
How to Start Test-Driven Development in Legacy Code
Dev Day Andreas Roth.pdf
3. Объекты, классы и пакеты в Java
C# Is The Future
Object Oriented Programming (OOP) using C++ - Lecture 4
Lombokの紹介
please help with java questionsJAVA CODEplease check my code and.pdf
29. Code an application program that keeps track of student informat.pdf
Manual tecnic sergi_subirats
WINSEM2020-21_STS3105_SS_VL2020210500169_Reference_Material_I_15-Mar-2021_L15...
F# for C# Programmers
@author public class Person{   String sname, .pdf
C h 04 oop_inheritance
Creating a Facebook Clone - Part XIX.pdf
Ad

More from Mariano Sánchez (18)

PPTX
.NET Core
PPTX
ASP.NET Core 1.0
PPTX
Introducción a SignalR
PPTX
Visual Studio LightSwitch
PPTX
HTML5 + Asp.NET
PPTX
Hey Cortana!
PPTX
Developing Universal Apps for Windows
PPTX
Introducing the Windows Phone 8.1 App Development Platform
PPTX
Visual Studio Online
PPT
Patrones Grasp
PPTX
Patrones de Diseño
PPTX
Introducción a DDD
PPTX
Conociendo TypeScript
PPTX
C# 6 - Que hay de nuevo?
PPTX
Universal Windows Platform Programando para todos y todas
PPTX
Code Smells
PPTX
Introducción a LINQ
PPTX
Patrones de Diseño
.NET Core
ASP.NET Core 1.0
Introducción a SignalR
Visual Studio LightSwitch
HTML5 + Asp.NET
Hey Cortana!
Developing Universal Apps for Windows
Introducing the Windows Phone 8.1 App Development Platform
Visual Studio Online
Patrones Grasp
Patrones de Diseño
Introducción a DDD
Conociendo TypeScript
C# 6 - Que hay de nuevo?
Universal Windows Platform Programando para todos y todas
Code Smells
Introducción a LINQ
Patrones de Diseño
Ad

Recently uploaded (20)

PPTX
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PDF
Approach and Philosophy of On baking technology
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PPTX
Spectroscopy.pptx food analysis technology
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PDF
Spectral efficient network and resource selection model in 5G networks
DOCX
The AUB Centre for AI in Media Proposal.docx
PDF
Unlocking AI with Model Context Protocol (MCP)
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PDF
KodekX | Application Modernization Development
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PPTX
MYSQL Presentation for SQL database connectivity
PDF
cuic standard and advanced reporting.pdf
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
Approach and Philosophy of On baking technology
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
Per capita expenditure prediction using model stacking based on satellite ima...
Reach Out and Touch Someone: Haptics and Empathic Computing
NewMind AI Weekly Chronicles - August'25 Week I
The Rise and Fall of 3GPP – Time for a Sabbatical?
Spectroscopy.pptx food analysis technology
Mobile App Security Testing_ A Comprehensive Guide.pdf
Spectral efficient network and resource selection model in 5G networks
The AUB Centre for AI in Media Proposal.docx
Unlocking AI with Model Context Protocol (MCP)
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Agricultural_Statistics_at_a_Glance_2022_0.pdf
KodekX | Application Modernization Development
Dropbox Q2 2025 Financial Results & Investor Presentation
MYSQL Presentation for SQL database connectivity
cuic standard and advanced reporting.pdf
Building Integrated photovoltaic BIPV_UPV.pdf

Refactoring - Mejorando el diseño del código existente

  • 1. Mariano Sánchez – Software Architect marianos@lagash.com
  • 10. Ejemplo 1: Switch statements
  • 11. // set in constructor
  • 14. public class Course { public List students; } int classSize = course.students.size(); public class Course { private List students; public List getStudents() { return students; } public void setStudents(List s) { students = s; } } int classSize = course.getStudents().size();
  • 15. public class Customer { private String name; private String workPhoneAreaCode; private String workPhoneNumber; } public class Customer { private String name; private Phone workPhone; } public class Phone { private String areaCode; private String number; }
  • 16. public class Customer { private String name; public String getName(){ return name; } public void setName(String string) { name = string; } public String toXML() { return "<Customer><Name>" + name + "</Name></Customer>"; } } public class Customer implements SerXML { private String name; public String getName(){ return name; } public void setName(String string) { name = string; } public String toXML() { return "<Customer><Name>" + name + "</Name></Customer>"; } } public interface SerXml { public abstract String toXML(); }
  • 17. public class Customer { void int foo() { … // Compute score score = a*b+c; score *= xfactor; } } public class Customer { void int foo() { … score = ComputeScore(a,b,c,xfactor); } } int ComputeScore(int a, int b, int c, int x) { return (a*b+c)*x; }
  • 18. public class Person { private String name; private String jobTitle; } public class Person { protected String name; } public class Employee extends Person { private String jobTitle; }
  • 19. public class Employee { private String name; private String jobTitle; } public class Student { private String name; private Course course; } public abstract class Person { protected String name; } public class Employee extends Person { private String jobTitle; } public class Student extends Person { private Course course; }
  • 20. public class Company extends Party { public abstract class Party { } private String name; private String companyType; public class Person extends Party private Date incorporated; { public void PrintNameAndDetails() private String firstName; { private String lastName; System.out.println("Name: " + name + " " + private Date dob; companyType); private String nationality; System.out.println("Incorporated: " + public void printNameAndDetails() incorporated.toString()); { } System.out.println("Name: " + firstName + " " + lastName); } System.out.println("DOB: " + dob.toString() + ", Nationality: " + nationality); } }
  • 21. public abstract class Party { public void PrintNameAndDetails() { printName(); printDetails(); } public abstract void printName(); public abstract void printDetails(); } public class Company extends Party { private String name; private String companyType; private Date incorporated; public void printDetails() { System.out.println("Incorporated: " + incorporated.toString()); } public void printName() { System.out.println("Name: " + name + " " + companyType); } } public class Person extends Party { private String firstName; private String lastName; private Date dob; private String nationality; public void printDetails() { System.out.println("DOB: " + dob.toString() + ", Nationality: " + nationality); }
  • 22. public class Student { public boolean isTaking(Course course) { return (course.getStudents().contains(this)); } } public class Course { private List students; public List getStudents() { return students; } } public class Student { } public class Course { private List students; public boolean isTaking(Student student) { return students.contains(student); } }
  • 23. public class User { Plan getPlan() { return plan; } } if (user == null) plan = Plan.basic(); else plan = user.getPlan(); public class User { Plan getPlan() { return plan; } } public class NullUser extends User { Plan getPlan() { return Plan.basic(); } }
  • 24. int withdraw(int amount) { if (amount > balance) return -1; else { balance -= amount; return 0; } } void withdraw(int amount) throws BalanceException { if (amount > balance) { throw new BalanceException(); } balance -= amount; }
  • 25. double getValueForPeriod (int periodNumber) { try { return values[periodNumber]; } catch (ArrayIndexOutOfBoundsException e) { return 0; } } double getValueForPeriod (int periodNumber) { if (periodNumber >= values.length) return 0; return values[periodNumber]; }
  • 26. double getPayAmount() { double result; if (isDead) result = deadAmount(); else { if (isSeparated) result = separatedAmount(); else { if (isRetired) result = retiredAmount(); else result = normalPayAmount(); } } return result; } double getPayAmount() { if (isDead) return deadAmount(); if (isSeparated) return separatedAmount(); if (isRetired) return retiredAmount(); return normalPayAmount(); };
  • 27. void setValue (String name, int value) { if (name.equals("height")) { height = value; return; } if (name.equals("width")) { width = value; return; } Assert.shouldNeverReachHere(); } void setHeight(int arg) { height = arg; } void setWidth (int arg) { width = arg; }
  • 28. double basePrice = quantity * itemPrice; if (basePrice > 1000) return basePrice * 0.95; else return basePrice * 0.98; ... if (basePrice() > 1000) return basePrice() * 0.95; else return basePrice() * 0.98; double basePrice() { return quantity * itemPrice; }
  • 29. public class Customer { public double getinvcdtlmt(); } public class Customer { public double getInvoiceCreditLimit(); }
  • 31. Muchas Gracias Mariano Sánchez – Software Architect marianos@lagash.com