SlideShare a Scribd company logo
1 of 59
Mariano Sánchez – Software Architect 
marianos@lagash.com 
@marianosz 
http://weblogs.asp.net/marianos
Don't Repeat Yourself!
You (Probably) Aren't 
Gonna Need It.
Ejemplo 1: Switch statements
// set in constructor
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 abstract class Party { } 
public class Company extends Party 
{ 
private String name; 
private String companyType; 
private Date incorporated; 
public void PrintNameAndDetails() 
{ 
System.out.println("Name: " + name + " " + 
companyType); 
System.out.println("Incorporated: " + 
incorporated.toString()); 
} 
} 
public class Person extends Party 
{ 
private String firstName; 
private String lastName; 
private Date dob; 
private String nationality; 
public void printNameAndDetails() 
{ 
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 Person extends Party 
{ 
private String firstName; 
private String lastName; 
private Date dob; 
private String nationality; 
public 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); 
} 
} 
System.out.println("DOB: " + dob.toString() + ", Nationality: " + nationality); 
} 
public void printName()
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; 
} 
} 
public class User 
{ 
Plan getPlan() 
{ 
return plan; 
} 
} 
public class NullUser extends User 
{ 
Plan getPlan() 
{ 
return Plan.basic(); 
} 
} 
if (user == null) 
plan = Plan.basic(); 
else 
plan = user.getPlan();
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(); 
}
Muchas Gracias 
Mariano Sánchez – Software Architect 
marianos@lagash.com 
@marianosz 
http://weblogs.asp.net/marianos

More Related Content

What's hot

TypeScript - All you ever wanted to know - Tech Talk by Epic Labs
TypeScript - All you ever wanted to know - Tech Talk by Epic LabsTypeScript - All you ever wanted to know - Tech Talk by Epic Labs
TypeScript - All you ever wanted to know - Tech Talk by Epic LabsAlfonso Peletier
 
3. Объекты, классы и пакеты в Java
3. Объекты, классы и пакеты в Java3. Объекты, классы и пакеты в Java
3. Объекты, классы и пакеты в JavaDEVTYPE
 
VISUALIZAR REGISTROS EN UN JTABLE
VISUALIZAR REGISTROS EN UN JTABLEVISUALIZAR REGISTROS EN UN JTABLE
VISUALIZAR REGISTROS EN UN JTABLEDarwin Durand
 
Travel management
Travel managementTravel management
Travel management1Parimal2
 
Multi client
Multi clientMulti client
Multi clientganteng8
 
[WELC] 21. I’m Changing the Same Code All Over the Place
[WELC] 21. I’m Changing the Same Code All Over the Place[WELC] 21. I’m Changing the Same Code All Over the Place
[WELC] 21. I’m Changing the Same Code All Over the Place종빈 오
 
Multi client
Multi clientMulti client
Multi clientAisy Cuyy
 
Fee managment system
Fee managment systemFee managment system
Fee managment systemfairy9912
 
c++ program for Railway reservation
c++ program for Railway reservationc++ program for Railway reservation
c++ program for Railway reservationSwarup Kumar Boro
 
Aho-Corasick string matching algorithm
Aho-Corasick string matching algorithmAho-Corasick string matching algorithm
Aho-Corasick string matching algorithmTakatoshi Kondo
 
CBSE Grade12, Computer Science, Sample Question Paper
CBSE Grade12, Computer Science, Sample Question PaperCBSE Grade12, Computer Science, Sample Question Paper
CBSE Grade12, Computer Science, Sample Question PaperMalathi Senthil
 
Lab 4 jawapan (sugentiran mane)
Lab 4 jawapan (sugentiran mane)Lab 4 jawapan (sugentiran mane)
Lab 4 jawapan (sugentiran mane)Yugeswary
 

What's hot (20)

TypeScript - All you ever wanted to know - Tech Talk by Epic Labs
TypeScript - All you ever wanted to know - Tech Talk by Epic LabsTypeScript - All you ever wanted to know - Tech Talk by Epic Labs
TypeScript - All you ever wanted to know - Tech Talk by Epic Labs
 
3. Объекты, классы и пакеты в Java
3. Объекты, классы и пакеты в Java3. Объекты, классы и пакеты в Java
3. Объекты, классы и пакеты в Java
 
VISUALIZAR REGISTROS EN UN JTABLE
VISUALIZAR REGISTROS EN UN JTABLEVISUALIZAR REGISTROS EN UN JTABLE
VISUALIZAR REGISTROS EN UN JTABLE
 
Ds 2 cycle
Ds 2 cycleDs 2 cycle
Ds 2 cycle
 
Travel management
Travel managementTravel management
Travel management
 
Multi client
Multi clientMulti client
Multi client
 
Ip project
Ip projectIp project
Ip project
 
[WELC] 21. I’m Changing the Same Code All Over the Place
[WELC] 21. I’m Changing the Same Code All Over the Place[WELC] 21. I’m Changing the Same Code All Over the Place
[WELC] 21. I’m Changing the Same Code All Over the Place
 
Scala best practices
Scala best practicesScala best practices
Scala best practices
 
Multi client
Multi clientMulti client
Multi client
 
Fee managment system
Fee managment systemFee managment system
Fee managment system
 
C++ TUTORIAL 5
C++ TUTORIAL 5C++ TUTORIAL 5
C++ TUTORIAL 5
 
C++ TUTORIAL 4
C++ TUTORIAL 4C++ TUTORIAL 4
C++ TUTORIAL 4
 
c++ program for Railway reservation
c++ program for Railway reservationc++ program for Railway reservation
c++ program for Railway reservation
 
C++ TUTORIAL 3
C++ TUTORIAL 3C++ TUTORIAL 3
C++ TUTORIAL 3
 
Aho-Corasick string matching algorithm
Aho-Corasick string matching algorithmAho-Corasick string matching algorithm
Aho-Corasick string matching algorithm
 
CBSE Grade12, Computer Science, Sample Question Paper
CBSE Grade12, Computer Science, Sample Question PaperCBSE Grade12, Computer Science, Sample Question Paper
CBSE Grade12, Computer Science, Sample Question Paper
 
Cquestions
Cquestions Cquestions
Cquestions
 
Lab 4 jawapan (sugentiran mane)
Lab 4 jawapan (sugentiran mane)Lab 4 jawapan (sugentiran mane)
Lab 4 jawapan (sugentiran mane)
 
C++ prgms 3rd unit
C++ prgms 3rd unitC++ prgms 3rd unit
C++ prgms 3rd unit
 

Similar to Code Smells y Refactoring o haciendo que nuestro codigo huela (y se vea) mejor by Mariano Sanchez

Refactoring - Mejorando el diseño del código existente
Refactoring - Mejorando el diseño del código existenteRefactoring - Mejorando el diseño del código existente
Refactoring - Mejorando el diseño del código existenteMariano Sánchez
 
TDC2016POA | Trilha .NET - CQRS e ES na prática com RavenDB
TDC2016POA | Trilha .NET - CQRS e ES na prática com RavenDBTDC2016POA | Trilha .NET - CQRS e ES na prática com RavenDB
TDC2016POA | Trilha .NET - CQRS e ES na prática com RavenDBtdc-globalcode
 
TDC2016SP - Trilha .NET
TDC2016SP - Trilha .NETTDC2016SP - Trilha .NET
TDC2016SP - Trilha .NETtdc-globalcode
 
@author public class Person{   String sname, .pdf
  @author   public class Person{   String sname, .pdf  @author   public class Person{   String sname, .pdf
@author public class Person{   String sname, .pdfaplolomedicalstoremr
 
public class Person { private String name; private int age;.pdf
public class Person { private String name; private int age;.pdfpublic class Person { private String name; private int age;.pdf
public class Person { private String name; private int age;.pdfarjuncp10
 
please help with java questionsJAVA CODEplease check my code and.pdf
please help with java questionsJAVA CODEplease check my code and.pdfplease help with java questionsJAVA CODEplease check my code and.pdf
please help with java questionsJAVA CODEplease check my code and.pdfarishmarketing21
 
Creating a Facebook Clone - Part XX.pdf
Creating a Facebook Clone - Part XX.pdfCreating a Facebook Clone - Part XX.pdf
Creating a Facebook Clone - Part XX.pdfShaiAlmog1
 
How to Start Test-Driven Development in Legacy Code
How to Start Test-Driven Development in Legacy CodeHow to Start Test-Driven Development in Legacy Code
How to Start Test-Driven Development in Legacy CodeDaniel Wellman
 
Inheritance 3.pptx
Inheritance 3.pptxInheritance 3.pptx
Inheritance 3.pptxSamanAshraf9
 
[PL] O klasycznej, programistycznej elegancji
[PL] O klasycznej, programistycznej elegancji[PL] O klasycznej, programistycznej elegancji
[PL] O klasycznej, programistycznej elegancjiJakub Marchwicki
 
Better Software: introduction to good code
Better Software: introduction to good codeBetter Software: introduction to good code
Better Software: introduction to good codeGiordano Scalzo
 
Assignment 7
Assignment 7Assignment 7
Assignment 7IIUM
 
29. Code an application program that keeps track of student informat.pdf
29. Code an application program that keeps track of student informat.pdf29. Code an application program that keeps track of student informat.pdf
29. Code an application program that keeps track of student informat.pdfarishaenterprises12
 

Similar to Code Smells y Refactoring o haciendo que nuestro codigo huela (y se vea) mejor by Mariano Sanchez (20)

Refactoring - Mejorando el diseño del código existente
Refactoring - Mejorando el diseño del código existenteRefactoring - Mejorando el diseño del código existente
Refactoring - Mejorando el diseño del código existente
 
TDC2016POA | Trilha .NET - CQRS e ES na prática com RavenDB
TDC2016POA | Trilha .NET - CQRS e ES na prática com RavenDBTDC2016POA | Trilha .NET - CQRS e ES na prática com RavenDB
TDC2016POA | Trilha .NET - CQRS e ES na prática com RavenDB
 
TDC2016SP - Trilha .NET
TDC2016SP - Trilha .NETTDC2016SP - Trilha .NET
TDC2016SP - Trilha .NET
 
OOP Lab Report.docx
OOP Lab Report.docxOOP Lab Report.docx
OOP Lab Report.docx
 
@author public class Person{   String sname, .pdf
  @author   public class Person{   String sname, .pdf  @author   public class Person{   String sname, .pdf
@author public class Person{   String sname, .pdf
 
public class Person { private String name; private int age;.pdf
public class Person { private String name; private int age;.pdfpublic class Person { private String name; private int age;.pdf
public class Person { private String name; private int age;.pdf
 
please help with java questionsJAVA CODEplease check my code and.pdf
please help with java questionsJAVA CODEplease check my code and.pdfplease help with java questionsJAVA CODEplease check my code and.pdf
please help with java questionsJAVA CODEplease check my code and.pdf
 
Creating a Facebook Clone - Part XX.pdf
Creating a Facebook Clone - Part XX.pdfCreating a Facebook Clone - Part XX.pdf
Creating a Facebook Clone - Part XX.pdf
 
DotNet Conference: code smells
DotNet Conference: code smellsDotNet Conference: code smells
DotNet Conference: code smells
 
How to Start Test-Driven Development in Legacy Code
How to Start Test-Driven Development in Legacy CodeHow to Start Test-Driven Development in Legacy Code
How to Start Test-Driven Development in Legacy Code
 
Inheritance 3.pptx
Inheritance 3.pptxInheritance 3.pptx
Inheritance 3.pptx
 
[PL] O klasycznej, programistycznej elegancji
[PL] O klasycznej, programistycznej elegancji[PL] O klasycznej, programistycznej elegancji
[PL] O klasycznej, programistycznej elegancji
 
Better Software: introduction to good code
Better Software: introduction to good codeBetter Software: introduction to good code
Better Software: introduction to good code
 
C# Is The Future
C# Is The FutureC# Is The Future
C# Is The Future
 
Assignment 7
Assignment 7Assignment 7
Assignment 7
 
Manual tecnic sergi_subirats
Manual tecnic sergi_subiratsManual tecnic sergi_subirats
Manual tecnic sergi_subirats
 
Oop objects_classes
Oop objects_classesOop objects_classes
Oop objects_classes
 
Lecture4
Lecture4Lecture4
Lecture4
 
Lecture4
Lecture4Lecture4
Lecture4
 
29. Code an application program that keeps track of student informat.pdf
29. Code an application program that keeps track of student informat.pdf29. Code an application program that keeps track of student informat.pdf
29. Code an application program that keeps track of student informat.pdf
 

More from .NET Conf UY

Roslyn: el futuro de C# y VB.NET by Rodolfo Finochietti
Roslyn: el futuro de C# y VB.NET by Rodolfo FinochiettiRoslyn: el futuro de C# y VB.NET by Rodolfo Finochietti
Roslyn: el futuro de C# y VB.NET by Rodolfo Finochietti.NET Conf UY
 
Machine Learning: Inteligencia Artificial no es sólo un tema de Ciencia Ficci...
Machine Learning: Inteligencia Artificial no es sólo un tema de Ciencia Ficci...Machine Learning: Inteligencia Artificial no es sólo un tema de Ciencia Ficci...
Machine Learning: Inteligencia Artificial no es sólo un tema de Ciencia Ficci....NET Conf UY
 
Building Real Time Applications with ASP.NET SignalR 2.0 by Rachel Appel
Building Real Time Applications with ASP.NET SignalR 2.0 by Rachel AppelBuilding Real Time Applications with ASP.NET SignalR 2.0 by Rachel Appel
Building Real Time Applications with ASP.NET SignalR 2.0 by Rachel Appel.NET Conf UY
 
Building Modern Websites with ASP.NET by Rachel Appel
Building Modern Websites with ASP.NET by Rachel AppelBuilding Modern Websites with ASP.NET by Rachel Appel
Building Modern Websites with ASP.NET by Rachel Appel.NET Conf UY
 
I just met you, and "this" is crazy, but here's my NaN, so call(me), maybe? b...
I just met you, and "this" is crazy, but here's my NaN, so call(me), maybe? b...I just met you, and "this" is crazy, but here's my NaN, so call(me), maybe? b...
I just met you, and "this" is crazy, but here's my NaN, so call(me), maybe? b....NET Conf UY
 
Windows y .NET en la Internet of Things by Pablo Garcia
Windows y .NET en la Internet of Things by Pablo GarciaWindows y .NET en la Internet of Things by Pablo Garcia
Windows y .NET en la Internet of Things by Pablo Garcia.NET Conf UY
 
Metodologías ¿Ágiles o productivas? Una visión desde la trinchera by Marcos E...
Metodologías ¿Ágiles o productivas? Una visión desde la trinchera by Marcos E...Metodologías ¿Ágiles o productivas? Una visión desde la trinchera by Marcos E...
Metodologías ¿Ágiles o productivas? Una visión desde la trinchera by Marcos E....NET Conf UY
 
Tips & tricks for sharing C# code on iOS, Android and Windows Phone by Jaime ...
Tips & tricks for sharing C# code on iOS, Android and Windows Phone by Jaime ...Tips & tricks for sharing C# code on iOS, Android and Windows Phone by Jaime ...
Tips & tricks for sharing C# code on iOS, Android and Windows Phone by Jaime ....NET Conf UY
 
Emprendiendo un futuro by Gabriel Camargo
Emprendiendo un futuro by Gabriel CamargoEmprendiendo un futuro by Gabriel Camargo
Emprendiendo un futuro by Gabriel Camargo.NET Conf UY
 
Microsoft Platform Vision by Eduardo Mangarelli
Microsoft Platform Vision by Eduardo MangarelliMicrosoft Platform Vision by Eduardo Mangarelli
Microsoft Platform Vision by Eduardo Mangarelli.NET Conf UY
 
Arquitectura para Windows Azure: Pienso, luego existo by Fernando Machado
Arquitectura para Windows Azure: Pienso, luego existo by Fernando MachadoArquitectura para Windows Azure: Pienso, luego existo by Fernando Machado
Arquitectura para Windows Azure: Pienso, luego existo by Fernando Machado.NET Conf UY
 
Extendiendo SharePoint, Project y Office 2013 con el nuevo modelo de Apps by ...
Extendiendo SharePoint, Project y Office 2013 con el nuevo modelo de Apps by ...Extendiendo SharePoint, Project y Office 2013 con el nuevo modelo de Apps by ...
Extendiendo SharePoint, Project y Office 2013 con el nuevo modelo de Apps by ....NET Conf UY
 
Getting Ahead of Delivery Issues with Deep SDLC Analysis by Donald Belcham
Getting Ahead of Delivery Issues with Deep SDLC Analysis by Donald BelchamGetting Ahead of Delivery Issues with Deep SDLC Analysis by Donald Belcham
Getting Ahead of Delivery Issues with Deep SDLC Analysis by Donald Belcham.NET Conf UY
 
Opportunities to Improve System Reliability and Resilience by Donald Belcham
Opportunities to Improve System Reliability and Resilience by Donald BelchamOpportunities to Improve System Reliability and Resilience by Donald Belcham
Opportunities to Improve System Reliability and Resilience by Donald Belcham.NET Conf UY
 
RESTful Para todos by Diego Sapriza
RESTful Para todos by Diego SaprizaRESTful Para todos by Diego Sapriza
RESTful Para todos by Diego Sapriza.NET Conf UY
 
Introduction to Aspect Oriented Programming by Donald Belcham
Introduction to Aspect Oriented Programming by Donald BelchamIntroduction to Aspect Oriented Programming by Donald Belcham
Introduction to Aspect Oriented Programming by Donald Belcham.NET Conf UY
 
Fun with .NET - Windows Phone, LEGO Mindstorms, and Azure by Dan Fernandez
Fun with .NET - Windows Phone, LEGO Mindstorms, and Azure by Dan FernandezFun with .NET - Windows Phone, LEGO Mindstorms, and Azure by Dan Fernandez
Fun with .NET - Windows Phone, LEGO Mindstorms, and Azure by Dan Fernandez.NET Conf UY
 
Azure: un parque de diversiones en la nube para el desarrollador moderno by A...
Azure: un parque de diversiones en la nube para el desarrollador moderno by A...Azure: un parque de diversiones en la nube para el desarrollador moderno by A...
Azure: un parque de diversiones en la nube para el desarrollador moderno by A....NET Conf UY
 

More from .NET Conf UY (18)

Roslyn: el futuro de C# y VB.NET by Rodolfo Finochietti
Roslyn: el futuro de C# y VB.NET by Rodolfo FinochiettiRoslyn: el futuro de C# y VB.NET by Rodolfo Finochietti
Roslyn: el futuro de C# y VB.NET by Rodolfo Finochietti
 
Machine Learning: Inteligencia Artificial no es sólo un tema de Ciencia Ficci...
Machine Learning: Inteligencia Artificial no es sólo un tema de Ciencia Ficci...Machine Learning: Inteligencia Artificial no es sólo un tema de Ciencia Ficci...
Machine Learning: Inteligencia Artificial no es sólo un tema de Ciencia Ficci...
 
Building Real Time Applications with ASP.NET SignalR 2.0 by Rachel Appel
Building Real Time Applications with ASP.NET SignalR 2.0 by Rachel AppelBuilding Real Time Applications with ASP.NET SignalR 2.0 by Rachel Appel
Building Real Time Applications with ASP.NET SignalR 2.0 by Rachel Appel
 
Building Modern Websites with ASP.NET by Rachel Appel
Building Modern Websites with ASP.NET by Rachel AppelBuilding Modern Websites with ASP.NET by Rachel Appel
Building Modern Websites with ASP.NET by Rachel Appel
 
I just met you, and "this" is crazy, but here's my NaN, so call(me), maybe? b...
I just met you, and "this" is crazy, but here's my NaN, so call(me), maybe? b...I just met you, and "this" is crazy, but here's my NaN, so call(me), maybe? b...
I just met you, and "this" is crazy, but here's my NaN, so call(me), maybe? b...
 
Windows y .NET en la Internet of Things by Pablo Garcia
Windows y .NET en la Internet of Things by Pablo GarciaWindows y .NET en la Internet of Things by Pablo Garcia
Windows y .NET en la Internet of Things by Pablo Garcia
 
Metodologías ¿Ágiles o productivas? Una visión desde la trinchera by Marcos E...
Metodologías ¿Ágiles o productivas? Una visión desde la trinchera by Marcos E...Metodologías ¿Ágiles o productivas? Una visión desde la trinchera by Marcos E...
Metodologías ¿Ágiles o productivas? Una visión desde la trinchera by Marcos E...
 
Tips & tricks for sharing C# code on iOS, Android and Windows Phone by Jaime ...
Tips & tricks for sharing C# code on iOS, Android and Windows Phone by Jaime ...Tips & tricks for sharing C# code on iOS, Android and Windows Phone by Jaime ...
Tips & tricks for sharing C# code on iOS, Android and Windows Phone by Jaime ...
 
Emprendiendo un futuro by Gabriel Camargo
Emprendiendo un futuro by Gabriel CamargoEmprendiendo un futuro by Gabriel Camargo
Emprendiendo un futuro by Gabriel Camargo
 
Microsoft Platform Vision by Eduardo Mangarelli
Microsoft Platform Vision by Eduardo MangarelliMicrosoft Platform Vision by Eduardo Mangarelli
Microsoft Platform Vision by Eduardo Mangarelli
 
Arquitectura para Windows Azure: Pienso, luego existo by Fernando Machado
Arquitectura para Windows Azure: Pienso, luego existo by Fernando MachadoArquitectura para Windows Azure: Pienso, luego existo by Fernando Machado
Arquitectura para Windows Azure: Pienso, luego existo by Fernando Machado
 
Extendiendo SharePoint, Project y Office 2013 con el nuevo modelo de Apps by ...
Extendiendo SharePoint, Project y Office 2013 con el nuevo modelo de Apps by ...Extendiendo SharePoint, Project y Office 2013 con el nuevo modelo de Apps by ...
Extendiendo SharePoint, Project y Office 2013 con el nuevo modelo de Apps by ...
 
Getting Ahead of Delivery Issues with Deep SDLC Analysis by Donald Belcham
Getting Ahead of Delivery Issues with Deep SDLC Analysis by Donald BelchamGetting Ahead of Delivery Issues with Deep SDLC Analysis by Donald Belcham
Getting Ahead of Delivery Issues with Deep SDLC Analysis by Donald Belcham
 
Opportunities to Improve System Reliability and Resilience by Donald Belcham
Opportunities to Improve System Reliability and Resilience by Donald BelchamOpportunities to Improve System Reliability and Resilience by Donald Belcham
Opportunities to Improve System Reliability and Resilience by Donald Belcham
 
RESTful Para todos by Diego Sapriza
RESTful Para todos by Diego SaprizaRESTful Para todos by Diego Sapriza
RESTful Para todos by Diego Sapriza
 
Introduction to Aspect Oriented Programming by Donald Belcham
Introduction to Aspect Oriented Programming by Donald BelchamIntroduction to Aspect Oriented Programming by Donald Belcham
Introduction to Aspect Oriented Programming by Donald Belcham
 
Fun with .NET - Windows Phone, LEGO Mindstorms, and Azure by Dan Fernandez
Fun with .NET - Windows Phone, LEGO Mindstorms, and Azure by Dan FernandezFun with .NET - Windows Phone, LEGO Mindstorms, and Azure by Dan Fernandez
Fun with .NET - Windows Phone, LEGO Mindstorms, and Azure by Dan Fernandez
 
Azure: un parque de diversiones en la nube para el desarrollador moderno by A...
Azure: un parque de diversiones en la nube para el desarrollador moderno by A...Azure: un parque de diversiones en la nube para el desarrollador moderno by A...
Azure: un parque de diversiones en la nube para el desarrollador moderno by A...
 

Recently uploaded

SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 

Recently uploaded (20)

SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 

Code Smells y Refactoring o haciendo que nuestro codigo huela (y se vea) mejor by Mariano Sanchez

  • 1. Mariano Sánchez – Software Architect marianos@lagash.com @marianosz http://weblogs.asp.net/marianos
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 23. You (Probably) Aren't Gonna Need It.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37. Ejemplo 1: Switch statements
  • 38. // set in constructor
  • 39.
  • 41. 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();
  • 42. 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; }
  • 43. 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(); }
  • 44. 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; } }
  • 45. public class Person { private String name; private String jobTitle; } public class Person { protected String name; } public class Employee extends Person { private String jobTitle; }
  • 46. 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; }
  • 47. public abstract class Party { } public class Company extends Party { private String name; private String companyType; private Date incorporated; public void PrintNameAndDetails() { System.out.println("Name: " + name + " " + companyType); System.out.println("Incorporated: " + incorporated.toString()); } } public class Person extends Party { private String firstName; private String lastName; private Date dob; private String nationality; public void printNameAndDetails() { System.out.println("Name: " + firstName + " " + lastName); System.out.println("DOB: " + dob.toString() + ", Nationality: " + nationality); } }
  • 48. public abstract class Party public void PrintNameAndDetails() { printName(); printDetails(); } public abstract void printName(); public abstract void printDetails(); } public class Person extends Party { private String firstName; private String lastName; private Date dob; private String nationality; public 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); } } System.out.println("DOB: " + dob.toString() + ", Nationality: " + nationality); } public void printName()
  • 49. 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); } }
  • 50. public class User { Plan getPlan() { return plan; } } public class User { Plan getPlan() { return plan; } } public class NullUser extends User { Plan getPlan() { return Plan.basic(); } } if (user == null) plan = Plan.basic(); else plan = user.getPlan();
  • 51. 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; }
  • 52. 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]; }
  • 53. 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(); };
  • 54. 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; }
  • 55. 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; }
  • 56. public class Customer { public double getinvcdtlmt(); } public class Customer { public double getInvoiceCreditLimit(); }
  • 57.
  • 58.
  • 59. Muchas Gracias Mariano Sánchez – Software Architect marianos@lagash.com @marianosz http://weblogs.asp.net/marianos