SlideShare a Scribd company logo
Clean Code
 @mariosangiorgio
Why?
Goals

Readable, maintainable and
    extendable code
Meaningful names
A simple example
public List<int[]> getThem() {
  List<int[]> list1 = new ArrayList<int[]>();
  for (int[] x : theList)
    if (x[0] == 4)
      list1.add(x);
  return list1;
}
A simple example
public List<int[]> getThem() {
  List<int[]> list1 = new ArrayList<int[]>();
  for (int[] x : theList)
    if (x[0] == 4)
      list1.add(x);
  return list1;
}


    This code is quite simple but
          what does it do?
A simple example
public List<int[]> getThem() {
  List<int[]> list1 = new ArrayList<int[]>();
  for (int[] x : theList)
    if (x[0] == 4)
      list1.add(x);
  return list1;
}


    This code is quite simple but
          what does it do?
      Looking at it we can’t tell
       what it is actually doing!
A simple example
public List<int[]> getFlaggedCells() {
  List<int[]> flaggedCells = new ArrayList<int[]>();
  for (int[] cell : gameBoard)
    if (cell[STATUS_VALUE] == FLAGGED)
      flaggedCells.add(x);
  return flaggedCells;
}



       Is this code any better?
A simple example
public List<Cell> getFlaggedCells() {
  List<Cell> flaggedCells = new ArrayList<Cell>();
  for (Cell cell : gameBoard)
    if (cell.isFlagged())
      flaggedCells.add(x);
  return flaggedCells;
}



           What about this?
A simple example
   What we have done:
A simple example
          What we have done:
 used intention         flaggedCells
revealing names       rather than list1
A simple example
             What we have done:
    used intention          flaggedCells
   revealing names        rather than list1
replaced magic numbers   cell[STATUS_VALUE]
    with constants         rather than x[0]
A simple example
             What we have done:
    used intention          flaggedCells
   revealing names        rather than list1
replaced magic numbers   cell[STATUS_VALUE]
    with constants         rather than x[0]
created an appropriate    Cell cell rather
  abstract data type      than int[] cell
Another example
int d;
            What does it mean?
            Days? Diameter? ...
Another example
int d;
                       What does it mean?
                       Days? Diameter? ...

  int d; //elapsed time in days
         Is this any better?
Another example
int d;
                       What does it mean?
                       Days? Diameter? ...

  int d; //elapsed time in days
         Is this any better?

     int elapsedTimeInDays;
         What about this?
Functions
Do one thing
public
bool
isEdible()
{


if
(this.ExpirationDate
>
Date.Now
&&







this.ApprovedForConsumption
==
true
&&







this.InspectorId
!=
null)
{




return
true;


}
else
{




return
false;


}
}



          How many things is the function doing?
Do one thing
public
bool
isEdible()
{


if
(this.ExpirationDate
>
Date.Now
&&         1.check expiration







this.ApprovedForConsumption
==
true
&&







this.InspectorId
!=
null)
{
                                                2.check approval




return
true;                                3.check inspection


}
else
{




return
false;                               4.answer the request


}
}



          How many things is the function doing?
Do one thing
public
bool
isEdible()
{




return
isFresh()



&&
         

isApproved()
&&
                             Now the function is doing one thing!
         

isInspected();
}
Do one thing
public
bool
isEdible()
{




return
isFresh()



&&
         

isApproved()
&&
                             Now the function is doing one thing!
         

isInspected();
}




               A change in the specifications turns
                into a single change in the code!
Don’t mix levels of abstraction

public
void
doTheDomesticThings()
{




takeOutTheTrash();                   public
void
doTheDomesticThings()
{




walkTheDog();                        



takeOutTheTrash();




for
(Dish
dish
:
dirtyDishStack)
{   



walkTheDog();







sink.washDish(dish);              



doTheDishes();







teaTowel.dryDish(dish);           }




}
}




         Which one is easier to read and understand?
Separate commands and queries

Commands should                 Queries should
only do something                only answer
   (One thing)                    something
public
class
Car{




private
boolean
isOn





public
void
turnOn(){








isOn
=
true;




}                        AVOID SIDE EFFECTS!




public
boolean
isOn(){








return
isOn;




}
}
Use exceptions
public
int
foo(){



...
}

public
void
bar(){



if(foo()
==
OK)






...



else






//
error
handling
}
Use exceptions
public
int
foo(){
                          Errors have to be encoded



...
}

public
void
bar(){



if(foo()
==
OK)






...



else






//
error
handling
}
Use exceptions
public
int
foo(){
                          Errors have to be encoded



...
}

public
void
bar(){
                          Checks (when performed)



if(foo()
==
OK)          require a lot of code






...



else






//
error
handling
}
Use exceptions
public
int
foo(){
                          Errors have to be encoded



...
}

public
void
bar(){
                          Checks (when performed)



if(foo()
==
OK)          require a lot of code






...



else






//
error
handling
}                         It’s harder to extend such
                                   programs
Use exceptions
public
void
foo()







throws
FooException{



...
}

public
void
bar(){



try{






foo();






...



}
catch(FooException){






//
error
handling



}
}
Use exceptions
public
void
foo()







throws
FooException{    No need to mix return



...
}
                             values and control values
public
void
bar(){



try{






foo();






...



}
catch(FooException){






//
error
handling



}
}
Use exceptions
public
void
foo()







throws
FooException{    No need to mix return



...
}
                             values and control values
public
void
bar(){



try{                           Cleaner syntax






foo();






...



}
catch(FooException){






//
error
handling



}
}
Use exceptions
public
void
foo()







throws
FooException{    No need to mix return



...
}
                             values and control values
public
void
bar(){



try{                           Cleaner syntax






foo();






...



}
catch(FooException){






//
error
handling          Easier to extend



}
}
Don’t Repeat Yourself
                     public
void
bar(){
                     

String
[]
elements
=
{“A”,
“B”,
“C”};
public
void
bar(){


foo(“A”);
                     

for(String
element
:
elements){


foo(“B”);
                     



foo(element);


foo(“C”);
                     

}
}
                     }




      DO NOT EVER COPY AND PASTE CODE
Don’t Repeat Yourself
                     public
void
bar(){
                     

String
[]
elements
=
{“A”,
“B”,
“C”};
public
void
bar(){


foo(“A”);
                     

for(String
element
:
elements){


foo(“B”);
                     



foo(element);


foo(“C”);
                     

}
}
                     }

                     Logic to handle the elements
                        it’s written once for all
      DO NOT EVER COPY AND PASTE CODE
Comments
Explain yourself in the code

                Which one is clearer?

// Check to see if the employee is eligible for full benefits
if ((employee.flags & HOURLY_FLAG) && (employee.age > 65))



          if (employee.isEligibleForFullBenefits())
Comments
      GOOD                    BAD

API Documentation           Redundant
Explanation of intent        Obsolete
    Clarification        Code commented-out
Other code smells
What we don’t want to see in your code
The bloaters
     Something in your code grow too large


  Long methods             Single responsibility
 and large classes          principle violated

Primitive obsession
                          It is a symptom of bad
   and too much
                                    design
    parameters
Primitive obsession
public Class Car{
    private int red, green, blue;

     public void paint(int red, int green, int blue){
         this.red   = red;
         this.green = green;
         this.blue = blue;
     }
}

public Class Car{
    private Color color;

    public void paint(Color color){
        this.color = color;
    }
}
The OO abusers
     Object orientation is not fully exploited

 Switch statements on         It is better to use
        objects                 polymorphism

   Refused bequest
                            Poor class hierarchy
Alternative classes with          design
  different interfaces
Switch vs polymorphism
 public Money calculatePay(Employee e)
     throws InvalidEmployeeType{
         switch(e.type){
             case COMMISSIONED:
                 return calculateCommissionedPay(e);
             case HOURLY:
                 return calculateHourlyPay(e);
             case SALARIED:
                 return calculateSalariedPay(e);
             default:
                 throw new
 InvalidEmployeeType(e.type);
         }
     }



 public abstract class Employee{
     public abstract Money calculatePay();
 }
Refused bequest
Subclass doesn’t use superclass methods and attributes
         public abstract class Employee{
             private int quota;
             public int getQuota();
             ...
         }

         public class Salesman extends Employee{ ... }

         public class Engineer extends Employee{
             ...
             public int getQuota(){
                 throw new NotSupportedException();
             }
         }


      Engineer does not use quota. It should be
             pushed down to Salesman
The change preventers
Something is making hard to change the code

                     A class has to be changed
Divergent change
                          in several parts

                      A single change requires
 Shotgun surgery
                      changes in several classes
The dispensables
 The code contains something unnecessary


A class is not doing
                       Class not providing logic
      enough


   Unused or
                       It isn’t something useful
 redundant code
The couplers
        Some classes are too tightly coupled

    Feature Envy           Misplaced responsibility

                         Classes should know as little
Inappropriate Intimacy
                         as possible about each other

   Message Chains          Too complex data access
Feature Envy
public class Customer{
    private PhoneNumber mobilePhone;

    ...

    public String getMobilePhoneNumber(){
        return “(” +
                mobilePhone.getAreaCode() + “)” +
                mobilePhone.getPrefix() + “-” +
                mobilePhone.getNumber();
    }
}
Feature Envy
public class Customer{
    private PhoneNumber mobilePhone;

    ...

    public String getMobilePhoneNumber(){
        return “(” +
                mobilePhone.getAreaCode() + “)” +
                mobilePhone.getPrefix() + “-” +
                mobilePhone.getNumber();
    }
}


    public String getMobilePhoneNumber(){
        return mobilePhone.toFormattedString();
    }
Message chains
a.getB().getC().getD().getTheNeededData()




          a.getTheNeededData()




  Law of Demeter: Each unit should
       only talk with friends

More Related Content

PPTX
clean code book summary - uncle bob - English version
PPTX
Clean code
PPTX
Clean code
PPTX
Clean Code I - Best Practices
PDF
PPTX
Clean code slide
PPTX
Clean Code: Chapter 3 Function
PDF
Clean coding-practices
clean code book summary - uncle bob - English version
Clean code
Clean code
Clean Code I - Best Practices
Clean code slide
Clean Code: Chapter 3 Function
Clean coding-practices

What's hot (20)

PPTX
Clean Code
PPTX
Clean code
PDF
Clean code
PPTX
Clean Code Principles
KEY
Clean Code
PDF
Clean code
PPTX
Clean code
PPTX
The Art of Clean code
PPTX
Clean Code
PPT
Clean Code summary
PPTX
Clean Pragmatic Architecture - Avoiding a Monolith
PPTX
Clean Code
PPTX
Inline function
PDF
Clean code and code smells
PDF
Chapter17 of clean code
PPS
Coding Best Practices
PPTX
Object Oriented Programming In JavaScript
PDF
TypeScript
PDF
Real Life Clean Architecture
PDF
Writing clean code
Clean Code
Clean code
Clean code
Clean Code Principles
Clean Code
Clean code
Clean code
The Art of Clean code
Clean Code
Clean Code summary
Clean Pragmatic Architecture - Avoiding a Monolith
Clean Code
Inline function
Clean code and code smells
Chapter17 of clean code
Coding Best Practices
Object Oriented Programming In JavaScript
TypeScript
Real Life Clean Architecture
Writing clean code
Ad

Similar to Clean code and Code Smells (20)

PDF
Clean code
PDF
Clean Code
PPTX
Presentacion clean code
 
PPT
Practices For Becoming A Better Programmer
PPTX
R. herves. clean code (theme)2
PDF
Clean Code 2
PPT
JAVA Tutorial- Do's and Don'ts of Java programming
PPT
JAVA Tutorial- Do's and Don'ts of Java programming
PDF
Agileee Developers Toolkit In The Agile World
PPTX
Clean Code
PPT
Clean code _v2003
PPTX
Clean code, Feb 2012
PPT
Refactoring - improving the smell of your code
PPTX
Android code convention
PPTX
Java Tips, Tricks and Pitfalls
PDF
FP in Java - Project Lambda and beyond
PDF
Effective Java with Groovy - How Language can Influence Good Practices
PPTX
Code reviews
PPTX
Clean code - DSC DYPCOE
ODP
Clean code
Clean code
Clean Code
Presentacion clean code
 
Practices For Becoming A Better Programmer
R. herves. clean code (theme)2
Clean Code 2
JAVA Tutorial- Do's and Don'ts of Java programming
JAVA Tutorial- Do's and Don'ts of Java programming
Agileee Developers Toolkit In The Agile World
Clean Code
Clean code _v2003
Clean code, Feb 2012
Refactoring - improving the smell of your code
Android code convention
Java Tips, Tricks and Pitfalls
FP in Java - Project Lambda and beyond
Effective Java with Groovy - How Language can Influence Good Practices
Code reviews
Clean code - DSC DYPCOE
Clean code
Ad

Recently uploaded (20)

PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PDF
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
PPTX
sap open course for s4hana steps from ECC to s4
PDF
KodekX | Application Modernization Development
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
Review of recent advances in non-invasive hemoglobin estimation
PDF
Unlocking AI with Model Context Protocol (MCP)
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PDF
Empathic Computing: Creating Shared Understanding
PPTX
MYSQL Presentation for SQL database connectivity
PDF
Spectral efficient network and resource selection model in 5G networks
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PDF
Network Security Unit 5.pdf for BCA BBA.
PPTX
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
PDF
Machine learning based COVID-19 study performance prediction
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
Dropbox Q2 2025 Financial Results & Investor Presentation
NewMind AI Weekly Chronicles - August'25 Week I
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
sap open course for s4hana steps from ECC to s4
KodekX | Application Modernization Development
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Chapter 3 Spatial Domain Image Processing.pdf
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Reach Out and Touch Someone: Haptics and Empathic Computing
Review of recent advances in non-invasive hemoglobin estimation
Unlocking AI with Model Context Protocol (MCP)
Understanding_Digital_Forensics_Presentation.pptx
Empathic Computing: Creating Shared Understanding
MYSQL Presentation for SQL database connectivity
Spectral efficient network and resource selection model in 5G networks
Per capita expenditure prediction using model stacking based on satellite ima...
Network Security Unit 5.pdf for BCA BBA.
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
Machine learning based COVID-19 study performance prediction

Clean code and Code Smells

Editor's Notes