SlideShare a Scribd company logo
1 of 48
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

What's hot

Clean Code I - Best Practices
Clean Code I - Best PracticesClean Code I - Best Practices
Clean Code I - Best Practices
Theo Jungeblut
 
Object Oriented Programming with Java
Object Oriented Programming with JavaObject Oriented Programming with Java
Object Oriented Programming with Java
backdoor
 
Evolving a Clean, Pragmatic Architecture - A Craftsman's Guide
Evolving a Clean, Pragmatic Architecture - A Craftsman's GuideEvolving a Clean, Pragmatic Architecture - A Craftsman's Guide
Evolving a Clean, Pragmatic Architecture - A Craftsman's Guide
Victor Rentea
 

What's hot (20)

Clean code
Clean codeClean code
Clean code
 
7 rules of simple and maintainable code
7 rules of simple and maintainable code7 rules of simple and maintainable code
7 rules of simple and maintainable code
 
Clean Code
Clean CodeClean Code
Clean Code
 
Writing clean code
Writing clean codeWriting clean code
Writing clean code
 
Clean code
Clean codeClean code
Clean code
 
Clean Code
Clean CodeClean Code
Clean Code
 
Clean Code
Clean CodeClean Code
Clean Code
 
Clean Code: Chapter 3 Function
Clean Code: Chapter 3 FunctionClean Code: Chapter 3 Function
Clean Code: Chapter 3 Function
 
Code smell overview
Code smell overviewCode smell overview
Code smell overview
 
Clean Code I - Best Practices
Clean Code I - Best PracticesClean Code I - Best Practices
Clean Code I - Best Practices
 
Clean Code Principles
Clean Code PrinciplesClean Code Principles
Clean Code Principles
 
Clean code
Clean codeClean code
Clean code
 
Refactoring and code smells
Refactoring and code smellsRefactoring and code smells
Refactoring and code smells
 
Code smells and remedies
Code smells and remediesCode smells and remedies
Code smells and remedies
 
Code Smells
Code SmellsCode Smells
Code Smells
 
Clean Code
Clean CodeClean Code
Clean Code
 
Object Oriented Programming with Java
Object Oriented Programming with JavaObject Oriented Programming with Java
Object Oriented Programming with Java
 
Java 8 Stream API. A different way to process collections.
Java 8 Stream API. A different way to process collections.Java 8 Stream API. A different way to process collections.
Java 8 Stream API. A different way to process collections.
 
Evolving a Clean, Pragmatic Architecture - A Craftsman's Guide
Evolving a Clean, Pragmatic Architecture - A Craftsman's GuideEvolving a Clean, Pragmatic Architecture - A Craftsman's Guide
Evolving a Clean, Pragmatic Architecture - A Craftsman's Guide
 
Clean Code
Clean CodeClean Code
Clean Code
 

Similar to Clean code and Code Smells

Working effectively with legacy code
Working effectively with legacy codeWorking effectively with legacy code
Working effectively with legacy code
ShriKant Vashishtha
 
C# 6.0 - April 2014 preview
C# 6.0 - April 2014 previewC# 6.0 - April 2014 preview
C# 6.0 - April 2014 preview
Paulo Morgado
 
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
vmandrychenko
 

Similar to Clean code and Code Smells (20)

Clean Code
Clean CodeClean Code
Clean Code
 
Java 2
Java   2Java   2
Java 2
 
Java Class Design
Java Class DesignJava Class Design
Java Class Design
 
MUTANTS KILLER (Revised) - PIT: state of the art of mutation testing system
MUTANTS KILLER (Revised) - PIT: state of the art of mutation testing system MUTANTS KILLER (Revised) - PIT: state of the art of mutation testing system
MUTANTS KILLER (Revised) - PIT: state of the art of mutation testing system
 
Paradigmas de Linguagens de Programacao - Aula #4
Paradigmas de Linguagens de Programacao - Aula #4Paradigmas de Linguagens de Programacao - Aula #4
Paradigmas de Linguagens de Programacao - Aula #4
 
Working effectively with legacy code
Working effectively with legacy codeWorking effectively with legacy code
Working effectively with legacy code
 
From clever code to better code
From clever code to better codeFrom clever code to better code
From clever code to better code
 
Functional Programming with C#
Functional Programming with C#Functional Programming with C#
Functional Programming with C#
 
Navigating the xDD Alphabet Soup
Navigating the xDD Alphabet SoupNavigating the xDD Alphabet Soup
Navigating the xDD Alphabet Soup
 
Android code convention
Android code conventionAndroid code convention
Android code convention
 
Practices For Becoming A Better Programmer
Practices For Becoming A Better ProgrammerPractices For Becoming A Better Programmer
Practices For Becoming A Better Programmer
 
Do I need tests when I have the compiler - Andrzej Jóźwiak - TomTom Dev Day 2020
Do I need tests when I have the compiler - Andrzej Jóźwiak - TomTom Dev Day 2020Do I need tests when I have the compiler - Andrzej Jóźwiak - TomTom Dev Day 2020
Do I need tests when I have the compiler - Andrzej Jóźwiak - TomTom Dev Day 2020
 
Google guava
Google guavaGoogle guava
Google guava
 
Who killed object oriented design?
Who killed object oriented design?Who killed object oriented design?
Who killed object oriented design?
 
Software design principles SOLID
Software design principles SOLIDSoftware design principles SOLID
Software design principles SOLID
 
SOLID Principles
SOLID PrinciplesSOLID Principles
SOLID Principles
 
C# 6.0 - April 2014 preview
C# 6.0 - April 2014 previewC# 6.0 - April 2014 preview
C# 6.0 - April 2014 preview
 
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
 
JDD 2016 - Sebastian Malaca - You Dont Need Unit Tests
JDD 2016 - Sebastian Malaca - You Dont Need Unit TestsJDD 2016 - Sebastian Malaca - You Dont Need Unit Tests
JDD 2016 - Sebastian Malaca - You Dont Need Unit Tests
 
Mixing functional and object oriented approaches to programming in C#
Mixing functional and object oriented approaches to programming in C#Mixing functional and object oriented approaches to programming in C#
Mixing functional and object oriented approaches to programming in C#
 

Recently uploaded

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 

Recently uploaded (20)

Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot ModelNavi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
 
A Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusA Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source Milvus
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 

Clean code and Code Smells

Editor's Notes

  1. \n
  2. \n
  3. \n
  4. \n
  5. \n
  6. \n
  7. \n
  8. \n
  9. \n
  10. \n
  11. \n
  12. \n
  13. \n
  14. \n
  15. \n
  16. \n
  17. \n
  18. \n
  19. \n
  20. \n
  21. \n
  22. \n
  23. \n
  24. \n
  25. \n
  26. \n
  27. \n
  28. \n
  29. \n
  30. \n
  31. \n
  32. \n
  33. \n
  34. \n
  35. \n
  36. \n
  37. \n
  38. \n
  39. \n