Se ha denunciado esta presentación.
Utilizamos tu perfil de LinkedIn y tus datos de actividad para personalizar los anuncios y mostrarte publicidad más relevante. Puedes cambiar tus preferencias de publicidad en cualquier momento.
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)
  ...
A simple example
public List<int[]> getThem() {
  List<int[]> list1 = new ArrayList<int[]>();
  for (int[] x : theList)
  ...
A simple example
public List<int[]> getThem() {
  List<int[]> list1 = new ArrayList<int[]>();
  for (int[] x : theList)
  ...
A simple example
public List<int[]> getFlaggedCells() {
  List<int[]> flaggedCells = new ArrayList<int[]>();
  for (int[] ...
A simple example
public List<Cell> getFlaggedCells() {
  List<Cell> flaggedCells = new ArrayList<Cell>();
  for (Cell cell...
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...
A simple example
             What we have done:
    used intention          flaggedCells
   revealing names        rather...
Another example
int d;
            What does it mean?
            Days? Diameter? ...
Another example
int d;
                       What does it mean?
                       Days? Diameter? ...

  int d; //el...
Another example
int d;
                       What does it mean?
                       Days? Diameter? ...

  int d; //el...
Functions
Do one thing
public
bool
isEdible()
{


if
(this.ExpirationDate
>
Date.Now
&&







this.ApprovedForConsumption
==
true
&...
Do one thing
public
bool
isEdible()
{


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







this.Appro...
Do one thing
public
bool
isEdible()
{




return
isFresh()



&&
         

isApproved()
&&
                             N...
Do one thing
public
bool
isEdible()
{




return
isFresh()



&&
         

isApproved()
&&
                             N...
Don’t mix levels of abstraction

public
void
doTheDomesticThings()
{




takeOutTheTrash();                   public
void
...
Separate commands and queries

Commands should                 Queries should
only do something                only answer...
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(fo...
Use exceptions
public
int
foo(){
                          Errors have to be encoded



...
}

public
void
bar(){
        ...
Use exceptions
public
int
foo(){
                          Errors have to be encoded



...
}

public
void
bar(){
        ...
Use exceptions
public
void
foo()







throws
FooException{



...
}

public
void
bar(){



try{






foo();






...

...
Use exceptions
public
void
foo()







throws
FooException{    No need to mix return



...
}
                           ...
Use exceptions
public
void
foo()







throws
FooException{    No need to mix return



...
}
                           ...
Use exceptions
public
void
foo()







throws
FooException{    No need to mix return



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

String
[]
elements
=
{“A”,
“B”,
“C”};...
Don’t Repeat Yourself
                     public
void
bar(){
                     

String
[]
elements
=
{“A”,
“B”,
“C”};...
Comments
Explain yourself in the code

                Which one is clearer?

// Check to see if the employee is eligible for full ...
Comments
      GOOD                    BAD

API Documentation           Redundant
Explanation of intent        Obsolete
  ...
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 clas...
Primitive obsession
public Class Car{
    private int red, green, blue;

     public void paint(int red, int green, int bl...
The OO abusers
     Object orientation is not fully exploited

 Switch statements on         It is better to use
        o...
Switch vs polymorphism
 public Money calculatePay(Employee e)
     throws InvalidEmployeeType{
         switch(e.type){
  ...
Refused bequest
Subclass doesn’t use superclass methods and attributes
         public abstract class Employee{
          ...
The change preventers
Something is making hard to change the code

                     A class has to be changed
Divergen...
The dispensables
 The code contains something unnecessary


A class is not doing
                       Class not providin...
The couplers
        Some classes are too tightly coupled

    Feature Envy           Misplaced responsibility

          ...
Feature Envy
public class Customer{
    private PhoneNumber mobilePhone;

    ...

    public String getMobilePhoneNumber(...
Feature Envy
public class Customer{
    private PhoneNumber mobilePhone;

    ...

    public String getMobilePhoneNumber(...
Message chains
a.getB().getC().getD().getTheNeededData()




          a.getTheNeededData()




  Law of Demeter: Each uni...
Próximo SlideShare
Cargando en…5
×

de

Clean code and Code Smells Slide 1 Clean code and Code Smells Slide 2 Clean code and Code Smells Slide 3 Clean code and Code Smells Slide 4 Clean code and Code Smells Slide 5 Clean code and Code Smells Slide 6 Clean code and Code Smells Slide 7 Clean code and Code Smells Slide 8 Clean code and Code Smells Slide 9 Clean code and Code Smells Slide 10 Clean code and Code Smells Slide 11 Clean code and Code Smells Slide 12 Clean code and Code Smells Slide 13 Clean code and Code Smells Slide 14 Clean code and Code Smells Slide 15 Clean code and Code Smells Slide 16 Clean code and Code Smells Slide 17 Clean code and Code Smells Slide 18 Clean code and Code Smells Slide 19 Clean code and Code Smells Slide 20 Clean code and Code Smells Slide 21 Clean code and Code Smells Slide 22 Clean code and Code Smells Slide 23 Clean code and Code Smells Slide 24 Clean code and Code Smells Slide 25 Clean code and Code Smells Slide 26 Clean code and Code Smells Slide 27 Clean code and Code Smells Slide 28 Clean code and Code Smells Slide 29 Clean code and Code Smells Slide 30 Clean code and Code Smells Slide 31 Clean code and Code Smells Slide 32 Clean code and Code Smells Slide 33 Clean code and Code Smells Slide 34 Clean code and Code Smells Slide 35 Clean code and Code Smells Slide 36 Clean code and Code Smells Slide 37 Clean code and Code Smells Slide 38 Clean code and Code Smells Slide 39 Clean code and Code Smells Slide 40 Clean code and Code Smells Slide 41 Clean code and Code Smells Slide 42 Clean code and Code Smells Slide 43 Clean code and Code Smells Slide 44 Clean code and Code Smells Slide 45 Clean code and Code Smells Slide 46 Clean code and Code Smells Slide 47 Clean code and Code Smells Slide 48
Próximo SlideShare
Code Smells
Siguiente
Descargar para leer sin conexión y ver en pantalla completa.

54 recomendaciones

Compartir

Descargar para leer sin conexión

Clean code and Code Smells

Descargar para leer sin conexión

Class about how to write clean code and how to identify bad smells in your code

Libros relacionados

Gratis con una prueba de 30 días de Scribd

Ver todo

Audiolibros relacionados

Gratis con una prueba de 30 días de Scribd

Ver todo

Clean code and Code Smells

  1. 1. Clean Code @mariosangiorgio
  2. 2. Why?
  3. 3. Goals Readable, maintainable and extendable code
  4. 4. Meaningful names
  5. 5. 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; }
  6. 6. 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?
  7. 7. 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!
  8. 8. 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?
  9. 9. 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?
  10. 10. A simple example What we have done:
  11. 11. A simple example What we have done: used intention flaggedCells revealing names rather than list1
  12. 12. 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]
  13. 13. 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
  14. 14. Another example int d; What does it mean? Days? Diameter? ...
  15. 15. Another example int d; What does it mean? Days? Diameter? ... int d; //elapsed time in days Is this any better?
  16. 16. 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?
  17. 17. Functions
  18. 18. 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?
  19. 19. 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?
  20. 20. Do one thing public
bool
isEdible()
{ 



return
isFresh()



&& 

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

isInspected(); }
  21. 21. 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!
  22. 22. 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?
  23. 23. 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; 



} }
  24. 24. Use exceptions public
int
foo(){ 


... } public
void
bar(){ 


if(foo()
==
OK) 





... 


else 





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


... } public
void
bar(){ 


if(foo()
==
OK) 





... 


else 





//
error
handling }
  26. 26. 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 }
  27. 27. 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
  28. 28. Use exceptions public
void
foo()
 





throws
FooException{ 


... } public
void
bar(){ 


try{ 





foo(); 





... 


}
catch(FooException){ 





//
error
handling 


} }
  29. 29. 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 


} }
  30. 30. 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 


} }
  31. 31. 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 


} }
  32. 32. 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
  33. 33. 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
  34. 34. Comments
  35. 35. 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())
  36. 36. Comments GOOD BAD API Documentation Redundant Explanation of intent Obsolete Clarification Code commented-out
  37. 37. Other code smells What we don’t want to see in your code
  38. 38. 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
  39. 39. 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; } }
  40. 40. 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
  41. 41. 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(); }
  42. 42. 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
  43. 43. 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
  44. 44. 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
  45. 45. 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
  46. 46. Feature Envy public class Customer{ private PhoneNumber mobilePhone; ... public String getMobilePhoneNumber(){ return “(” + mobilePhone.getAreaCode() + “)” + mobilePhone.getPrefix() + “-” + mobilePhone.getNumber(); } }
  47. 47. Feature Envy public class Customer{ private PhoneNumber mobilePhone; ... public String getMobilePhoneNumber(){ return “(” + mobilePhone.getAreaCode() + “)” + mobilePhone.getPrefix() + “-” + mobilePhone.getNumber(); } } public String getMobilePhoneNumber(){ return mobilePhone.toFormattedString(); }
  48. 48. Message chains a.getB().getC().getD().getTheNeededData() a.getTheNeededData() Law of Demeter: Each unit should only talk with friends
  • anhtunguyen89

    Jun. 25, 2019
  • hanochaloni

    May. 6, 2018
  • AshutoshVaidya4

    Apr. 10, 2018
  • AraJzd

    Mar. 26, 2018
  • Philip.Wang

    Sep. 13, 2017
  • GorsonTanguyGuillaum

    Aug. 8, 2017
  • joelrdz

    Aug. 8, 2017
  • RoeeZolantz

    Jun. 13, 2017
  • goergewashington1428

    Jun. 1, 2017
  • MeMohamedAly

    May. 1, 2017
  • denisristic1

    Apr. 25, 2017
  • ThanichJuthapisuth

    Apr. 8, 2017
  • MuratKahramanGNGR

    Apr. 7, 2017
  • PierreGoiffon

    Apr. 6, 2017
  • PhamManhLan

    Dec. 7, 2016
  • DiarmaidMcGowan

    Nov. 25, 2016
  • didierpirottin

    Oct. 30, 2016
  • DuyHieuDang

    Apr. 8, 2016
  • professional_fci

    Oct. 17, 2015
  • EwertonRibeirodaSilv

    Oct. 12, 2015

Class about how to write clean code and how to identify bad smells in your code

Vistas

Total de vistas

17.419

En Slideshare

0

De embebidos

0

Número de embebidos

377

Acciones

Descargas

1.105

Compartidos

0

Comentarios

0

Me gusta

54

×