SlideShare una empresa de Scribd logo
1 de 65
Code Smells and Refactoring
Code Smells?A code smell is a design that
duplicates, complicates, bloats or
tightly couples code
Refactoring?
"Refactoring is the process of
changing a software system in
such a way that it does not alter
the external behavior of the code
yet improves its internal
structure." – Martin Fowler
In computer programming, code
smell is any symptom in the source
code of a program that possibly
indicates a deeper problem. Code
smells are usually not bugs—they
are not technically incorrect and do
not currently prevent the program
from functioning. Instead, they
indicate weaknesses in design that
may be slowing down development
or increasing the risk of bugs or
failures in the future.
A short history of Code Smells
• If it stinks, change it!
• Kent Beck coined the
term code smell to
signify something in code
that needed to be
changed.
Common Code Smells
• Inappropriate naming
• Comments
• Dead code
• Duplicated code
• Primitive obsession
• Large class
• God class
• Lazy class
• Middle man
• Data clumps
• Data class
• Long method
• Long parameter list
• Switch statements
• Speculative generality
• Oddball solution
• Feature envy
• Refused bequest
• Black sheep
• Contrived complexity
• Divergent change
• Shotgun Surgery
Inappropriate Naming
• Names given to variables (fields) ,methods or class should
be clear and meaningful.
• A variable, field, class name should say exactly what it is.
• Which is better?
private string s; OR private string salary;
• A method should say exactly what it does.
• Which is better?
public double calc (double s); OR
public double calculateFederalTaxes (double salary);
Remedy:
Rename Variables, Fields, Method, Class
Comments
• Comments are often used as deodorant
• Comments represent a failure to express
an idea in the code. Try to make your
code self-documenting or intention-
revealing
• When you feel like writing a comment,
first try to refactor it.
• Remedy:
Extract Method
Rename Method
Comments (Cont’d)
void List::add(string element)
{
if (!m_readOnly)
{
int newSize = m_size + 1;
if (newSize > getCapacity())
{
// grow the array
m_capacity += INITIAL_CAPACITY;
string* elements2 = new string[m_capacity];
for (int i = 0; i < m_size; i++)
elements2[i] = m_elements[i];
delete[] m_elements;
m_elements = elements2;
}
m_elements[m_size++] = element;
}
Comments (Cont’d)
void List::add(string element)
{
if (m_readOnly)
return;
if (shouldGrow())
grow();
storeElement(element);
}
bool List::shouldGrow()
{
return (m_size + 1) >
capacity();
}
void List::grow()
{
m_capacity += 10;
string *newElements = new string[m_capacity];
for(int i = 0;i < m_size;i++)
newElements[i] = m_elements[i];
delete [] m_elements;
m_elements = newElements;
}
void List::storeElement(string element)
{
m_elements[m_size++] = element;
}
Rename Method
Remedy of Comments
Extract Method
void PrintOwning(double amount){
PrintBanner();
/ / print details
System.Console.Out.WriteLine(“name: “+ name);
System.Console.Out.WriteLine(“amount: “+ amount);
}
Remedy of Comments
void PrintOwning(double amount){
PrintBanner();
PrintDetails(amount);
}
void PrintDetails(double amount){
System.Console.Out.WriteLine(“name: “+ name);
System.Console.Out.WriteLine(“amount: “+ amount);
}
Long Method
• A method is long when it is too hard to quickly comprehend.
• Long methods tend to hide behavior that ought to be shared,
which leads to duplicated code in other methods or classes.
• Good OO code is easiest to understand and maintain with
shorter methods with good names
• Remedies:
 Extract Method
 Replace Temp with Query
 Introduce Parameter Object
 Preserve Whole Object
 Replace Method with Method Object.
 Decompose Conditional
Long Method (Cont’d)
private String toStringHelper(StringBuffer result) {
result.append("<");
result.append(name);
result.append(attributes.toString());
result.append(">");
if (!value.equals(""))
result.append(value);
Iterator it = children().iterator();
while (it.hasNext()) {
TagNode node = (TagNode)it.next();
node.toStringHelper(result);
}
result.append("</");
result.append(name);
result.append(">");
return result.toString();
}
Extract Method
private String toStringHelper(StringBuffer result) {
writeOpenTagTo(result);
writeValueTo(result);
writeChildrenTo(result);
writeEndTagTo(result);
return result.toString();
}
private void writeOpenTagTo(StringBuffer result) {
result.append("<");
result.append(name);
result.append(attributes.toString());
result.append(">");
}
private void writeValueTo(StringBuffer result) {
if (!value.equals(""))
result.append(value);
}
private void writeChildrenTo(StringBuffer result) {
Iterator it = children().iterator();
while (it.hasNext()) {
T agNode node = (TagNode)it.next();
node.toStringHelper(result);
}
}
private void writeEndTagTo(StringBuffer result)
{
result.append("</");
result.append(name);
result.append(">");
}
Remedy of Long method
Replace Temp with Query
double basePrice = _quanity
* _itemPrice;
if(basePrice > 1000)
{
return basePrice * 0.95;
}
else
{
return basePrice * 0.98;
}
if(getBasePrice() > 1000) {
return getBasePrice() * 0.95;
}
else {
return getBasePrice() * 0.98;
}
double getBasePrice() {
return _quanitiy *
_itemPrice;
}
Remedy of Long method
Introduce Parameter Object
Remedy of Long method
Replace Method with Method Object
//class Order...
double price() {
double primaryBasePrice;
double secondaryBasePrice;
double tertiaryBasePrice;
// long computation;
...
}
Remedy of Long method
Decompose Conditional
• You have a complicated conditional (if-then-
else) statement. Extract methods from the
condition, then part, and else parts.
if (date.before (SUMMER_START) || date.after(SUMMER_END))
charge = quantity * _winterRate + _winterServiceCharge;
else charge = quantity * _summerRate;
---------------------------------------------------------------------------------------------
if (notSummer(date))
charge = winterCharge(quantity);
else charge = summerCharge (quantity);
Remedy of Long method
Lazy Class
• A class that isn't doing enough to carry its
weight. We let the class die with dignity
Remedies
Inline Class
Collapse Hierarchy
Lazy Class (Cont’d)
public class Letter {
private final String content;
public Letter(String content) {
this.content = content;
}
public String getContent() {
return content;
}
}
Inline Class
Remedy of Lazy Class
Collapse Hierarchy
Remedy of Lazy Class
Speculative Generality
• You get this smell when people say "Oh, I think we will
need the ability to do that someday" and thus want all
sorts of hooks and special cases to handle things that aren't
required.
• This odor exists when you have generic or abstract code
that isn’t actually needed today. Such code often exists to
support future behavior, which may or may not be
necessary in the future.
Remedy
Collapse Hierarchy
Inline Class
Remove Parameter
Rename Method
Speculative Generality (Cont’d)
public class Customer {
private String name;
private String address;
private String salutation;
private String otherDetails;
private MailingSystem mailingSystem;
public Customer(String name, String salutation, String add, String details, MailingSystem mSys) {
this.name = name;
this.address = add;
this.salutation = salutation;
this.otherDetails = details;
this.mailingSystem = mSys;
}
String getName() {
return name;
}
MailingSystem getMailingSystem() {
return mailingSystem;
}
}
Speculative Generality (Cont’d)
Collapse Hierarchy
Remedy of Speculative Generality
Inline Class
Remedy of Speculative Generality
Remove Parameter
Remedy of Speculative Generality
Dead Code
• Code that is no longer used in a system or
related system is Dead Code.
• Increased Complexity.
• Accidental Changes.
• More Dead Code
• Remedy
Dead Code (Cont’d)
One of the following constructors is never called by a client. It is dead code.
public class Loan {
public Loan(double commitment, int riskRating, Date maturity, Date expiry) {
this(commitment, 0.00, riskRating, maturity, expiry);
}
public Loan(double commitment, double outstanding, int customerRating, Date
maturity, Date expiry) {
this(null, commitment, outstanding, customerRating, maturity, expiry);
}
public Loan(CapitalStrategy capitalStrategy, double commitment, int riskRating, Date
maturity, Date expiry) {
this(capitalStrategy, commitment, 0.00, riskRating, maturity, expiry);
}
...
}
Refused Bequest
• This rather potent odor results
when subclasses inherit code that
they don’t want. In some cases, a
subclass may “refuse the bequest”
by providing a do nothing
implementation of an inherited
method.
Remedy
Push Down Field/Method
Replace Inheritance with Delegation
Refused Bequest (Cont’d)
Remedy of Refused Bequest
Push Down Method
Black Sheep
• Sometimes a subclass or method doesn't fit in so well with
its family.
• A subclass that is substantially different in nature than
other subclasses in the hierarchy.
• A method in a class that is noticeably different from other
methods in the class.
Remedy
 Move Method
 Extract Class
Black Sheep (Cont’d)
Duplicate Code
• Duplicated Code
• The most pervasive and pungent smell in software
• There is obvious or blatant duplication such as copy and
paste
• There are subtle or non-obvious duplications
• Such as parallel inheritance hierarchies.
• Similar algorithms
• Remedy
 Extract Method
 Pull Up Field
 Form Template Method
 Substitute Algorithm
Duplicate Code (Cont’d)
Ctl+C Ctl+V Pattern
Duplicate Code (Cont’d)
public int addCustomer( int userId, Customer newCustomer) {
List<Customer> customerList = customers.get(userId);
int customerId = (int) Math.random() * 1000;
// TODO: Logic to find/generate customer id.
newCustomer.setId(customerId);
if (customerList == null) {
customerList = new LinkedList<Customer>();
customers.put(userId, customerList);
}
customerList.add(newCustomer);
return customerId;
}
Duplicate Code (Cont’d)
public int addTemplate( int userId, Template newTemplate) {
List<Template> templateList = templates.get(userId);
int templateId = (int) Math.random() * 1000;
// TODO: Logic to find/generate template id.
newTemplate.setId(templateId);
if (templateList == null) {
templateList = new LinkedList<Template>();
templates.put(userId, templateList);
}
templateList.add(newTemplate);
return templateId;
}
Duplicate Code (Cont’d)
Literal
Semantic
Data Duplication
Conceptual
Duplicate Code (Cont’d)
Levels of Duplication
Literal Duplication
Same for loop in 2 places
Duplicate Code (Cont’d)
Semantic Duplication
1st Level - For and For Each Loop
2nd Level - Loop v/s Lines repeated
3rd Level - Loop v/s Recursion
stack.push(1);
stack.push(3);
stack.push(5);
stack.push(10);
stack.push(15);
v/s
for(int i : asList(1,3,5,10,15))
stack.push(i);
Duplicate Code (Cont’d)
Data Duplication
Some constant declared in 2 classes (test and
production)
Duplicate Code (Cont’d)
Conceptual Duplication
Two Algorithms to Sort elements (Bubble sort
and Quick sort)
Duplicate Code (Cont’d)
Pull Up Field
Remedy of duplicate code
Substitute Algorithm
String foundPerson(String[] people){
for (int i = 0; i < people.length; i++) {
if (people[i].equals ("Don")){
return "Don";
}
if (people[i].equals ("John")){
return "John";
}
if (people[i].equals ("Kent")){
return "Kent";
}
}
return "";
}
String foundPerson(String[] people){
List candidates = Arrays.asList(new String[]
{"Don", "John", "Kent"});
for (String person : people)
if (candidates.contains(person))
return person;
return "";
Remedy of duplicate code
Switch Statement
• This smell exists when the same switch statement (or “if…else if…else if”
• statement) is duplicated across a system.
• Such duplicated code reveals a lack of object-orientation and a missed
• opportunity to rely on the elegance of polymorphism.
• Remedy:
– Replace Type Code with Polymorphism
– Replace Type Code with State / Strategy
– Replace Parameter with Explicit Methods
– Introduce Null Object.
Switch Smell (Cont’d)
Switch Smell (Cont’d)
Replace Type Code with Polymorphism
Remedy of Switch Smell
Replace Parameter with Method
void setValue (String name, int value) {
if (name.equals("height"))
this.height = value;
if (name.equals("width"))
this.width = value;
}
void setHeight(int h) {
this.height = h;
}
void setWidth (int w) {
this.width = w;
}
Remedy of Switch Smell
Introduce Null Object
// In client class
Customer customer = site.getCustomer();
BillingPlan plan;
if (customer == null) plan = BillingPlan.basic();
else plan = customer.getPlan();
// In client class
Customer customer = site.getCustomer();
BillingPlan plan = customer.getPlan();
// In Null Customer
public BillingPlan getPlan(){
return BillingPlan.basic();
}
Remedy of Switch Smell
Large Class
• Like people, classes suffer when they take on too many
responsibilities.
• GOD Objects
• Fowler and Beck note that the presence of too many instance
variables usually indicates that a class is trying to do too much. In
general, large classes typically contain too many responsibilities.
• Remedies
– Extract Class
– Replace Type Code with Class/Subclass
– Replace Type Code with State/Strategy
– Replace Conditional with Polymorphism
– Extract Interface
– Duplicate Observed Data
Extract Class
Replace Type Code with Class
Replace Type Code with Subclasses
Replace Type Code with State/Strategy
Feature Envy
• A method that seems more interested in some
other class than the one it is in data and behavior
that acts on that data belong together.
• When a method makes too many calls to other
classes to obtain data or functionality, Feature
Envy is in the air.
• Remedies:
– Move Field
– Move Method
– Extract Method
Move Field
Contrived complexity
Forced usage of overly
complicated design
patterns where simpler
design would suffice.
“Any intelligent fool can make
things bigger, more complex,
and more violent. It takes a
touch of genius…and a lot of
courage to move in the opposite
direction.” ~ E.F. Schumacher
Data clumps
• Whenever two or three
values are gathered
together in a class
Remedy: Extract class
Temporary fields
• Class has a variable which is only used in some
situation.
Remedy
Move field
Acknowledgements
 Martin Fowler
 Kent Beck
 Naresh Jain
 Ron Jeffries
 Robert C. Martin
 Industrial Logic
 Though Works
 Nerd Castle
 The Other Resources
Code smells and remedies
Code smells and remedies

Más contenido relacionado

La actualidad más candente (20)

Refactoring 101
Refactoring 101Refactoring 101
Refactoring 101
 
Refactoring
RefactoringRefactoring
Refactoring
 
Clean code
Clean codeClean code
Clean code
 
Clean code
Clean codeClean code
Clean code
 
Bad Code Smells
Bad Code SmellsBad Code Smells
Bad Code Smells
 
Clean code
Clean codeClean code
Clean code
 
Clean code slide
Clean code slideClean code slide
Clean code slide
 
Code Smell, Software Engineering
Code Smell, Software EngineeringCode Smell, Software Engineering
Code Smell, Software Engineering
 
Code refactoring
Code refactoringCode refactoring
Code refactoring
 
Code Refactoring
Code RefactoringCode Refactoring
Code Refactoring
 
Clean coding-practices
Clean coding-practicesClean coding-practices
Clean coding-practices
 
Coding Best Practices
Coding Best PracticesCoding Best Practices
Coding Best Practices
 
Clean code
Clean code Clean code
Clean code
 
Refactoring
RefactoringRefactoring
Refactoring
 
Clean Code: Chapter 3 Function
Clean Code: Chapter 3 FunctionClean Code: Chapter 3 Function
Clean Code: Chapter 3 Function
 
Clean code
Clean codeClean code
Clean code
 
Refactoring
RefactoringRefactoring
Refactoring
 
Clean Code
Clean CodeClean Code
Clean Code
 
Java input
Java inputJava input
Java input
 
Coding standard
Coding standardCoding standard
Coding standard
 

Destacado

Refactoring-ch7 moving feature btw objects
Refactoring-ch7 moving feature btw objectsRefactoring-ch7 moving feature btw objects
Refactoring-ch7 moving feature btw objectsfungfung Chen
 
Software craftsmanship coaching
Software craftsmanship coachingSoftware craftsmanship coaching
Software craftsmanship coachingPedro Santos
 
Theorie und Praxis der Achtsamkeit / Mindfulness
Theorie und Praxis der Achtsamkeit / MindfulnessTheorie und Praxis der Achtsamkeit / Mindfulness
Theorie und Praxis der Achtsamkeit / MindfulnessStefan Spiecker
 
Revisiting the Relationship Between Code Smells and Refactoring
Revisiting the Relationship Between Code Smells and RefactoringRevisiting the Relationship Between Code Smells and Refactoring
Revisiting the Relationship Between Code Smells and RefactoringNorihiro Yoshida
 
Piotr Szotkowski about "Ruby smells"
Piotr Szotkowski about "Ruby smells"Piotr Szotkowski about "Ruby smells"
Piotr Szotkowski about "Ruby smells"Pivorak MeetUp
 
Refactoring code smell
Refactoring code smellRefactoring code smell
Refactoring code smellmartintsch
 
Fighting Ruby code smell
Fighting Ruby code smellFighting Ruby code smell
Fighting Ruby code smellolegshpynov
 
Training from the BACK of the Room
Training from the BACK of the RoomTraining from the BACK of the Room
Training from the BACK of the Roomsparkagility
 
Clean Code I - Best Practices
Clean Code I - Best PracticesClean Code I - Best Practices
Clean Code I - Best PracticesTheo Jungeblut
 
Clean Code summary
Clean Code summaryClean Code summary
Clean Code summaryJan de Vries
 
Engage the Brain: 5 Ways to Create Interactive Slides
Engage the Brain: 5 Ways to Create Interactive SlidesEngage the Brain: 5 Ways to Create Interactive Slides
Engage the Brain: 5 Ways to Create Interactive SlidesSharon Bowman
 
How to Design Great Training: Begin with the End in Mind
How to Design Great Training: Begin with the End in MindHow to Design Great Training: Begin with the End in Mind
How to Design Great Training: Begin with the End in MindSharon Bowman
 
Code Smells and Refactoring
Code Smells and RefactoringCode Smells and Refactoring
Code Smells and RefactoringStanly Lau
 
Six Trumps: Six Learning Principles that Trump Traditional Teaching
Six Trumps: Six Learning Principles that Trump Traditional TeachingSix Trumps: Six Learning Principles that Trump Traditional Teaching
Six Trumps: Six Learning Principles that Trump Traditional TeachingSharon Bowman
 
Was Unternehmen von Gehirnen lernen können. (Alpha-Version)
Was Unternehmen von Gehirnen lernen können. (Alpha-Version)Was Unternehmen von Gehirnen lernen können. (Alpha-Version)
Was Unternehmen von Gehirnen lernen können. (Alpha-Version)Christoph Bauer
 

Destacado (20)

Refactoring-ch7 moving feature btw objects
Refactoring-ch7 moving feature btw objectsRefactoring-ch7 moving feature btw objects
Refactoring-ch7 moving feature btw objects
 
Software craftsmanship coaching
Software craftsmanship coachingSoftware craftsmanship coaching
Software craftsmanship coaching
 
Code smells
Code smellsCode smells
Code smells
 
Theorie und Praxis der Achtsamkeit / Mindfulness
Theorie und Praxis der Achtsamkeit / MindfulnessTheorie und Praxis der Achtsamkeit / Mindfulness
Theorie und Praxis der Achtsamkeit / Mindfulness
 
Revisiting the Relationship Between Code Smells and Refactoring
Revisiting the Relationship Between Code Smells and RefactoringRevisiting the Relationship Between Code Smells and Refactoring
Revisiting the Relationship Between Code Smells and Refactoring
 
Fighting code smells
Fighting code smellsFighting code smells
Fighting code smells
 
Piotr Szotkowski about "Ruby smells"
Piotr Szotkowski about "Ruby smells"Piotr Szotkowski about "Ruby smells"
Piotr Szotkowski about "Ruby smells"
 
Code Smell
Code SmellCode Smell
Code Smell
 
Refactoring code smell
Refactoring code smellRefactoring code smell
Refactoring code smell
 
Fighting Ruby code smell
Fighting Ruby code smellFighting Ruby code smell
Fighting Ruby code smell
 
Bad Smell In Codes 1
Bad Smell In Codes 1Bad Smell In Codes 1
Bad Smell In Codes 1
 
Training from the BACK of the Room
Training from the BACK of the RoomTraining from the BACK of the Room
Training from the BACK of the Room
 
Clean Code I - Best Practices
Clean Code I - Best PracticesClean Code I - Best Practices
Clean Code I - Best Practices
 
Clean Code summary
Clean Code summaryClean Code summary
Clean Code summary
 
Engage the Brain: 5 Ways to Create Interactive Slides
Engage the Brain: 5 Ways to Create Interactive SlidesEngage the Brain: 5 Ways to Create Interactive Slides
Engage the Brain: 5 Ways to Create Interactive Slides
 
How to Design Great Training: Begin with the End in Mind
How to Design Great Training: Begin with the End in MindHow to Design Great Training: Begin with the End in Mind
How to Design Great Training: Begin with the End in Mind
 
Code Refactoring
Code RefactoringCode Refactoring
Code Refactoring
 
Code Smells and Refactoring
Code Smells and RefactoringCode Smells and Refactoring
Code Smells and Refactoring
 
Six Trumps: Six Learning Principles that Trump Traditional Teaching
Six Trumps: Six Learning Principles that Trump Traditional TeachingSix Trumps: Six Learning Principles that Trump Traditional Teaching
Six Trumps: Six Learning Principles that Trump Traditional Teaching
 
Was Unternehmen von Gehirnen lernen können. (Alpha-Version)
Was Unternehmen von Gehirnen lernen können. (Alpha-Version)Was Unternehmen von Gehirnen lernen können. (Alpha-Version)
Was Unternehmen von Gehirnen lernen können. (Alpha-Version)
 

Similar a Code smells and remedies

Addressing Scenario
Addressing ScenarioAddressing Scenario
Addressing ScenarioTara Hardin
 
20.1 Java working with abstraction
20.1 Java working with abstraction20.1 Java working with abstraction
20.1 Java working with abstractionIntro C# Book
 
C++ CoreHard Autumn 2018. Debug C++ Without Running - Anastasia Kazakova
C++ CoreHard Autumn 2018. Debug C++ Without Running - Anastasia KazakovaC++ CoreHard Autumn 2018. Debug C++ Without Running - Anastasia Kazakova
C++ CoreHard Autumn 2018. Debug C++ Without Running - Anastasia Kazakovacorehard_by
 
Refactoring - improving the smell of your code
Refactoring - improving the smell of your codeRefactoring - improving the smell of your code
Refactoring - improving the smell of your codevmandrychenko
 
How much do we know about Object-Oriented Programming?
How much do we know about Object-Oriented Programming?How much do we know about Object-Oriented Programming?
How much do we know about Object-Oriented Programming?Sandro Mancuso
 
Modernising Legacy Code
Modernising Legacy CodeModernising Legacy Code
Modernising Legacy CodeSamThePHPDev
 
Metrics ekon 14_2_kleiner
Metrics ekon 14_2_kleinerMetrics ekon 14_2_kleiner
Metrics ekon 14_2_kleinerMax Kleiner
 
Evolving a Clean, Pragmatic Architecture at JBCNConf 2019
Evolving a Clean, Pragmatic Architecture at JBCNConf 2019Evolving a Clean, Pragmatic Architecture at JBCNConf 2019
Evolving a Clean, Pragmatic Architecture at JBCNConf 2019Victor Rentea
 
NET Systems Programming Learned the Hard Way.pptx
NET Systems Programming Learned the Hard Way.pptxNET Systems Programming Learned the Hard Way.pptx
NET Systems Programming Learned the Hard Way.pptxpetabridge
 
Code and Design Smells. Are They a Real Threat?
Code and Design Smells. Are They a Real Threat?Code and Design Smells. Are They a Real Threat?
Code and Design Smells. Are They a Real Threat?GlobalLogic Ukraine
 
Dart for Java Developers
Dart for Java DevelopersDart for Java Developers
Dart for Java DevelopersYakov Fain
 
10 ways to make your code rock
10 ways to make your code rock10 ways to make your code rock
10 ways to make your code rockmartincronje
 
Automated Refactoring
Automated RefactoringAutomated Refactoring
Automated RefactoringJaneve George
 
Geek Sync | Rewriting Bad SQL Code 101
Geek Sync | Rewriting Bad SQL Code 101Geek Sync | Rewriting Bad SQL Code 101
Geek Sync | Rewriting Bad SQL Code 101IDERA Software
 
Clean code _v2003
 Clean code _v2003 Clean code _v2003
Clean code _v2003R696
 

Similar a Code smells and remedies (20)

Addressing Scenario
Addressing ScenarioAddressing Scenario
Addressing Scenario
 
20.1 Java working with abstraction
20.1 Java working with abstraction20.1 Java working with abstraction
20.1 Java working with abstraction
 
C++ CoreHard Autumn 2018. Debug C++ Without Running - Anastasia Kazakova
C++ CoreHard Autumn 2018. Debug C++ Without Running - Anastasia KazakovaC++ CoreHard Autumn 2018. Debug C++ Without Running - Anastasia Kazakova
C++ CoreHard Autumn 2018. Debug C++ Without Running - Anastasia Kazakova
 
One Careful Owner
One Careful OwnerOne Careful Owner
One Careful Owner
 
Clean code
Clean codeClean code
Clean code
 
Refactoring - improving the smell of your code
Refactoring - improving the smell of your codeRefactoring - improving the smell of your code
Refactoring - improving the smell of your code
 
How much do we know about Object-Oriented Programming?
How much do we know about Object-Oriented Programming?How much do we know about Object-Oriented Programming?
How much do we know about Object-Oriented Programming?
 
Modernising Legacy Code
Modernising Legacy CodeModernising Legacy Code
Modernising Legacy Code
 
Metrics ekon 14_2_kleiner
Metrics ekon 14_2_kleinerMetrics ekon 14_2_kleiner
Metrics ekon 14_2_kleiner
 
Evolving a Clean, Pragmatic Architecture at JBCNConf 2019
Evolving a Clean, Pragmatic Architecture at JBCNConf 2019Evolving a Clean, Pragmatic Architecture at JBCNConf 2019
Evolving a Clean, Pragmatic Architecture at JBCNConf 2019
 
NET Systems Programming Learned the Hard Way.pptx
NET Systems Programming Learned the Hard Way.pptxNET Systems Programming Learned the Hard Way.pptx
NET Systems Programming Learned the Hard Way.pptx
 
Code and Design Smells. Are They a Real Threat?
Code and Design Smells. Are They a Real Threat?Code and Design Smells. Are They a Real Threat?
Code and Design Smells. Are They a Real Threat?
 
Dart for Java Developers
Dart for Java DevelopersDart for Java Developers
Dart for Java Developers
 
10 ways to make your code rock
10 ways to make your code rock10 ways to make your code rock
10 ways to make your code rock
 
SOLID Java Code
SOLID Java CodeSOLID Java Code
SOLID Java Code
 
Clean Code
Clean CodeClean Code
Clean Code
 
Automated Refactoring
Automated RefactoringAutomated Refactoring
Automated Refactoring
 
Geek Sync | Rewriting Bad SQL Code 101
Geek Sync | Rewriting Bad SQL Code 101Geek Sync | Rewriting Bad SQL Code 101
Geek Sync | Rewriting Bad SQL Code 101
 
Javascript Design Patterns
Javascript Design PatternsJavascript Design Patterns
Javascript Design Patterns
 
Clean code _v2003
 Clean code _v2003 Clean code _v2003
Clean code _v2003
 

Más de Md.Mojibul Hoque

Más de Md.Mojibul Hoque (11)

Facebook Marketing
Facebook Marketing Facebook Marketing
Facebook Marketing
 
Surela
SurelaSurela
Surela
 
Harvard University database
Harvard University databaseHarvard University database
Harvard University database
 
Business level strategy
Business level strategyBusiness level strategy
Business level strategy
 
Establishing objectives
Establishing objectivesEstablishing objectives
Establishing objectives
 
Value chain and SWOT analysis
Value chain and SWOT analysisValue chain and SWOT analysis
Value chain and SWOT analysis
 
Ms sql-server
Ms sql-serverMs sql-server
Ms sql-server
 
University Student Payment System ( USPS )
University Student Payment System ( USPS )University Student Payment System ( USPS )
University Student Payment System ( USPS )
 
Software design principles
Software design principlesSoftware design principles
Software design principles
 
Writing a research report
Writing a research reportWriting a research report
Writing a research report
 
Dynamic programming
Dynamic programmingDynamic programming
Dynamic programming
 

Último

Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...OnePlan Solutions
 
VictoriaMetrics Q1 Meet Up '24 - Community & News Update
VictoriaMetrics Q1 Meet Up '24 - Community & News UpdateVictoriaMetrics Q1 Meet Up '24 - Community & News Update
VictoriaMetrics Q1 Meet Up '24 - Community & News UpdateVictoriaMetrics
 
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full Recording
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full RecordingOpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full Recording
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full RecordingShane Coughlan
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtimeandrehoraa
 
Large Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and RepairLarge Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and RepairLionel Briand
 
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdfEnhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdfRTS corp
 
SoftTeco - Software Development Company Profile
SoftTeco - Software Development Company ProfileSoftTeco - Software Development Company Profile
SoftTeco - Software Development Company Profileakrivarotava
 
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full Recording
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full RecordingOpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full Recording
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full RecordingShane Coughlan
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Angel Borroy López
 
Effectively Troubleshoot 9 Types of OutOfMemoryError
Effectively Troubleshoot 9 Types of OutOfMemoryErrorEffectively Troubleshoot 9 Types of OutOfMemoryError
Effectively Troubleshoot 9 Types of OutOfMemoryErrorTier1 app
 
SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?Alexandre Beguel
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationBradBedford3
 
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxUI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxAndreas Kunz
 
Keeping your build tool updated in a multi repository world
Keeping your build tool updated in a multi repository worldKeeping your build tool updated in a multi repository world
Keeping your build tool updated in a multi repository worldRoberto Pérez Alcolea
 
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdfExploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdfkalichargn70th171
 
Comparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfComparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfDrew Moseley
 
Understanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM ArchitectureUnderstanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM Architecturerahul_net
 
Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Rob Geurden
 
Strategies for using alternative queries to mitigate zero results
Strategies for using alternative queries to mitigate zero resultsStrategies for using alternative queries to mitigate zero results
Strategies for using alternative queries to mitigate zero resultsJean Silva
 
Osi security architecture in network.pptx
Osi security architecture in network.pptxOsi security architecture in network.pptx
Osi security architecture in network.pptxVinzoCenzo
 

Último (20)

Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
 
VictoriaMetrics Q1 Meet Up '24 - Community & News Update
VictoriaMetrics Q1 Meet Up '24 - Community & News UpdateVictoriaMetrics Q1 Meet Up '24 - Community & News Update
VictoriaMetrics Q1 Meet Up '24 - Community & News Update
 
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full Recording
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full RecordingOpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full Recording
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full Recording
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtime
 
Large Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and RepairLarge Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and Repair
 
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdfEnhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
 
SoftTeco - Software Development Company Profile
SoftTeco - Software Development Company ProfileSoftTeco - Software Development Company Profile
SoftTeco - Software Development Company Profile
 
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full Recording
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full RecordingOpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full Recording
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full Recording
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
 
Effectively Troubleshoot 9 Types of OutOfMemoryError
Effectively Troubleshoot 9 Types of OutOfMemoryErrorEffectively Troubleshoot 9 Types of OutOfMemoryError
Effectively Troubleshoot 9 Types of OutOfMemoryError
 
SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion Application
 
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxUI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
 
Keeping your build tool updated in a multi repository world
Keeping your build tool updated in a multi repository worldKeeping your build tool updated in a multi repository world
Keeping your build tool updated in a multi repository world
 
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdfExploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
 
Comparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfComparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdf
 
Understanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM ArchitectureUnderstanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM Architecture
 
Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...
 
Strategies for using alternative queries to mitigate zero results
Strategies for using alternative queries to mitigate zero resultsStrategies for using alternative queries to mitigate zero results
Strategies for using alternative queries to mitigate zero results
 
Osi security architecture in network.pptx
Osi security architecture in network.pptxOsi security architecture in network.pptx
Osi security architecture in network.pptx
 

Code smells and remedies

  • 1. Code Smells and Refactoring
  • 2. Code Smells?A code smell is a design that duplicates, complicates, bloats or tightly couples code Refactoring? "Refactoring is the process of changing a software system in such a way that it does not alter the external behavior of the code yet improves its internal structure." – Martin Fowler In computer programming, code smell is any symptom in the source code of a program that possibly indicates a deeper problem. Code smells are usually not bugs—they are not technically incorrect and do not currently prevent the program from functioning. Instead, they indicate weaknesses in design that may be slowing down development or increasing the risk of bugs or failures in the future.
  • 3. A short history of Code Smells • If it stinks, change it! • Kent Beck coined the term code smell to signify something in code that needed to be changed.
  • 4. Common Code Smells • Inappropriate naming • Comments • Dead code • Duplicated code • Primitive obsession • Large class • God class • Lazy class • Middle man • Data clumps • Data class • Long method • Long parameter list • Switch statements • Speculative generality • Oddball solution • Feature envy • Refused bequest • Black sheep • Contrived complexity • Divergent change • Shotgun Surgery
  • 5. Inappropriate Naming • Names given to variables (fields) ,methods or class should be clear and meaningful. • A variable, field, class name should say exactly what it is. • Which is better? private string s; OR private string salary; • A method should say exactly what it does. • Which is better? public double calc (double s); OR public double calculateFederalTaxes (double salary); Remedy: Rename Variables, Fields, Method, Class
  • 6. Comments • Comments are often used as deodorant • Comments represent a failure to express an idea in the code. Try to make your code self-documenting or intention- revealing • When you feel like writing a comment, first try to refactor it. • Remedy: Extract Method Rename Method
  • 7. Comments (Cont’d) void List::add(string element) { if (!m_readOnly) { int newSize = m_size + 1; if (newSize > getCapacity()) { // grow the array m_capacity += INITIAL_CAPACITY; string* elements2 = new string[m_capacity]; for (int i = 0; i < m_size; i++) elements2[i] = m_elements[i]; delete[] m_elements; m_elements = elements2; } m_elements[m_size++] = element; }
  • 8. Comments (Cont’d) void List::add(string element) { if (m_readOnly) return; if (shouldGrow()) grow(); storeElement(element); } bool List::shouldGrow() { return (m_size + 1) > capacity(); } void List::grow() { m_capacity += 10; string *newElements = new string[m_capacity]; for(int i = 0;i < m_size;i++) newElements[i] = m_elements[i]; delete [] m_elements; m_elements = newElements; } void List::storeElement(string element) { m_elements[m_size++] = element; }
  • 10. Extract Method void PrintOwning(double amount){ PrintBanner(); / / print details System.Console.Out.WriteLine(“name: “+ name); System.Console.Out.WriteLine(“amount: “+ amount); } Remedy of Comments void PrintOwning(double amount){ PrintBanner(); PrintDetails(amount); } void PrintDetails(double amount){ System.Console.Out.WriteLine(“name: “+ name); System.Console.Out.WriteLine(“amount: “+ amount); }
  • 11. Long Method • A method is long when it is too hard to quickly comprehend. • Long methods tend to hide behavior that ought to be shared, which leads to duplicated code in other methods or classes. • Good OO code is easiest to understand and maintain with shorter methods with good names • Remedies:  Extract Method  Replace Temp with Query  Introduce Parameter Object  Preserve Whole Object  Replace Method with Method Object.  Decompose Conditional
  • 12. Long Method (Cont’d) private String toStringHelper(StringBuffer result) { result.append("<"); result.append(name); result.append(attributes.toString()); result.append(">"); if (!value.equals("")) result.append(value); Iterator it = children().iterator(); while (it.hasNext()) { TagNode node = (TagNode)it.next(); node.toStringHelper(result); } result.append("</"); result.append(name); result.append(">"); return result.toString(); }
  • 13. Extract Method private String toStringHelper(StringBuffer result) { writeOpenTagTo(result); writeValueTo(result); writeChildrenTo(result); writeEndTagTo(result); return result.toString(); } private void writeOpenTagTo(StringBuffer result) { result.append("<"); result.append(name); result.append(attributes.toString()); result.append(">"); } private void writeValueTo(StringBuffer result) { if (!value.equals("")) result.append(value); } private void writeChildrenTo(StringBuffer result) { Iterator it = children().iterator(); while (it.hasNext()) { T agNode node = (TagNode)it.next(); node.toStringHelper(result); } } private void writeEndTagTo(StringBuffer result) { result.append("</"); result.append(name); result.append(">"); } Remedy of Long method
  • 14. Replace Temp with Query double basePrice = _quanity * _itemPrice; if(basePrice > 1000) { return basePrice * 0.95; } else { return basePrice * 0.98; } if(getBasePrice() > 1000) { return getBasePrice() * 0.95; } else { return getBasePrice() * 0.98; } double getBasePrice() { return _quanitiy * _itemPrice; } Remedy of Long method
  • 16. Replace Method with Method Object //class Order... double price() { double primaryBasePrice; double secondaryBasePrice; double tertiaryBasePrice; // long computation; ... } Remedy of Long method
  • 17. Decompose Conditional • You have a complicated conditional (if-then- else) statement. Extract methods from the condition, then part, and else parts. if (date.before (SUMMER_START) || date.after(SUMMER_END)) charge = quantity * _winterRate + _winterServiceCharge; else charge = quantity * _summerRate; --------------------------------------------------------------------------------------------- if (notSummer(date)) charge = winterCharge(quantity); else charge = summerCharge (quantity); Remedy of Long method
  • 18. Lazy Class • A class that isn't doing enough to carry its weight. We let the class die with dignity Remedies Inline Class Collapse Hierarchy
  • 19. Lazy Class (Cont’d) public class Letter { private final String content; public Letter(String content) { this.content = content; } public String getContent() { return content; } }
  • 22. Speculative Generality • You get this smell when people say "Oh, I think we will need the ability to do that someday" and thus want all sorts of hooks and special cases to handle things that aren't required. • This odor exists when you have generic or abstract code that isn’t actually needed today. Such code often exists to support future behavior, which may or may not be necessary in the future. Remedy Collapse Hierarchy Inline Class Remove Parameter Rename Method
  • 23. Speculative Generality (Cont’d) public class Customer { private String name; private String address; private String salutation; private String otherDetails; private MailingSystem mailingSystem; public Customer(String name, String salutation, String add, String details, MailingSystem mSys) { this.name = name; this.address = add; this.salutation = salutation; this.otherDetails = details; this.mailingSystem = mSys; } String getName() { return name; } MailingSystem getMailingSystem() { return mailingSystem; } }
  • 25. Collapse Hierarchy Remedy of Speculative Generality
  • 26. Inline Class Remedy of Speculative Generality
  • 27. Remove Parameter Remedy of Speculative Generality
  • 28. Dead Code • Code that is no longer used in a system or related system is Dead Code. • Increased Complexity. • Accidental Changes. • More Dead Code • Remedy
  • 29. Dead Code (Cont’d) One of the following constructors is never called by a client. It is dead code. public class Loan { public Loan(double commitment, int riskRating, Date maturity, Date expiry) { this(commitment, 0.00, riskRating, maturity, expiry); } public Loan(double commitment, double outstanding, int customerRating, Date maturity, Date expiry) { this(null, commitment, outstanding, customerRating, maturity, expiry); } public Loan(CapitalStrategy capitalStrategy, double commitment, int riskRating, Date maturity, Date expiry) { this(capitalStrategy, commitment, 0.00, riskRating, maturity, expiry); } ... }
  • 30. Refused Bequest • This rather potent odor results when subclasses inherit code that they don’t want. In some cases, a subclass may “refuse the bequest” by providing a do nothing implementation of an inherited method. Remedy Push Down Field/Method Replace Inheritance with Delegation
  • 32. Remedy of Refused Bequest Push Down Method
  • 33. Black Sheep • Sometimes a subclass or method doesn't fit in so well with its family. • A subclass that is substantially different in nature than other subclasses in the hierarchy. • A method in a class that is noticeably different from other methods in the class. Remedy  Move Method  Extract Class
  • 35. Duplicate Code • Duplicated Code • The most pervasive and pungent smell in software • There is obvious or blatant duplication such as copy and paste • There are subtle or non-obvious duplications • Such as parallel inheritance hierarchies. • Similar algorithms • Remedy  Extract Method  Pull Up Field  Form Template Method  Substitute Algorithm
  • 38. public int addCustomer( int userId, Customer newCustomer) { List<Customer> customerList = customers.get(userId); int customerId = (int) Math.random() * 1000; // TODO: Logic to find/generate customer id. newCustomer.setId(customerId); if (customerList == null) { customerList = new LinkedList<Customer>(); customers.put(userId, customerList); } customerList.add(newCustomer); return customerId; } Duplicate Code (Cont’d) public int addTemplate( int userId, Template newTemplate) { List<Template> templateList = templates.get(userId); int templateId = (int) Math.random() * 1000; // TODO: Logic to find/generate template id. newTemplate.setId(templateId); if (templateList == null) { templateList = new LinkedList<Template>(); templates.put(userId, templateList); } templateList.add(newTemplate); return templateId; }
  • 41. Literal Duplication Same for loop in 2 places Duplicate Code (Cont’d)
  • 42. Semantic Duplication 1st Level - For and For Each Loop 2nd Level - Loop v/s Lines repeated 3rd Level - Loop v/s Recursion stack.push(1); stack.push(3); stack.push(5); stack.push(10); stack.push(15); v/s for(int i : asList(1,3,5,10,15)) stack.push(i); Duplicate Code (Cont’d)
  • 43. Data Duplication Some constant declared in 2 classes (test and production) Duplicate Code (Cont’d)
  • 44. Conceptual Duplication Two Algorithms to Sort elements (Bubble sort and Quick sort) Duplicate Code (Cont’d)
  • 45. Pull Up Field Remedy of duplicate code
  • 46. Substitute Algorithm String foundPerson(String[] people){ for (int i = 0; i < people.length; i++) { if (people[i].equals ("Don")){ return "Don"; } if (people[i].equals ("John")){ return "John"; } if (people[i].equals ("Kent")){ return "Kent"; } } return ""; } String foundPerson(String[] people){ List candidates = Arrays.asList(new String[] {"Don", "John", "Kent"}); for (String person : people) if (candidates.contains(person)) return person; return ""; Remedy of duplicate code
  • 47. Switch Statement • This smell exists when the same switch statement (or “if…else if…else if” • statement) is duplicated across a system. • Such duplicated code reveals a lack of object-orientation and a missed • opportunity to rely on the elegance of polymorphism. • Remedy: – Replace Type Code with Polymorphism – Replace Type Code with State / Strategy – Replace Parameter with Explicit Methods – Introduce Null Object.
  • 50. Replace Type Code with Polymorphism Remedy of Switch Smell
  • 51. Replace Parameter with Method void setValue (String name, int value) { if (name.equals("height")) this.height = value; if (name.equals("width")) this.width = value; } void setHeight(int h) { this.height = h; } void setWidth (int w) { this.width = w; } Remedy of Switch Smell
  • 52. Introduce Null Object // In client class Customer customer = site.getCustomer(); BillingPlan plan; if (customer == null) plan = BillingPlan.basic(); else plan = customer.getPlan(); // In client class Customer customer = site.getCustomer(); BillingPlan plan = customer.getPlan(); // In Null Customer public BillingPlan getPlan(){ return BillingPlan.basic(); } Remedy of Switch Smell
  • 53. Large Class • Like people, classes suffer when they take on too many responsibilities. • GOD Objects • Fowler and Beck note that the presence of too many instance variables usually indicates that a class is trying to do too much. In general, large classes typically contain too many responsibilities. • Remedies – Extract Class – Replace Type Code with Class/Subclass – Replace Type Code with State/Strategy – Replace Conditional with Polymorphism – Extract Interface – Duplicate Observed Data
  • 55. Replace Type Code with Class
  • 56. Replace Type Code with Subclasses
  • 57. Replace Type Code with State/Strategy
  • 58. Feature Envy • A method that seems more interested in some other class than the one it is in data and behavior that acts on that data belong together. • When a method makes too many calls to other classes to obtain data or functionality, Feature Envy is in the air. • Remedies: – Move Field – Move Method – Extract Method
  • 60. Contrived complexity Forced usage of overly complicated design patterns where simpler design would suffice. “Any intelligent fool can make things bigger, more complex, and more violent. It takes a touch of genius…and a lot of courage to move in the opposite direction.” ~ E.F. Schumacher
  • 61. Data clumps • Whenever two or three values are gathered together in a class Remedy: Extract class
  • 62. Temporary fields • Class has a variable which is only used in some situation. Remedy Move field
  • 63. Acknowledgements  Martin Fowler  Kent Beck  Naresh Jain  Ron Jeffries  Robert C. Martin  Industrial Logic  Though Works  Nerd Castle  The Other Resources