Clean code and Code Smells

11,688 views

Published on

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

Published in: Technology
0 Comments
37 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
11,688
On SlideShare
0
From Embeds
0
Number of Embeds
136
Actions
Shares
0
Downloads
794
Comments
0
Likes
37
Embeds 0
No embeds

No notes for slide
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • Clean code and Code Smells

    1. 1. Clean Code @mariosangiorgio
    2. 2. Why?
    3. 3. GoalsReadable, maintainable and extendable code
    4. 4. Meaningful names
    5. 5. A simple examplepublic 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 examplepublic 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 examplepublic 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 examplepublic 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 examplepublic 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 flaggedCellsrevealing names rather than list1
    12. 12. A simple example What we have done: used intention flaggedCells revealing names rather than list1replaced 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 list1replaced 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 exampleint d; What does it mean? Days? Diameter? ...
    15. 15. Another exampleint d; What does it mean? Days? Diameter? ... int d; //elapsed time in days Is this any better?
    16. 16. Another exampleint 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 thingpublic
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 thingpublic
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 thingpublic
bool
isEdible()
{



return
isFresh()



&& 

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

isInspected();}
    21. 21. Do one thingpublic
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 abstractionpublic
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 queriesCommands should Queries shouldonly do something only answer (One thing) somethingpublic
class
Car{



private
boolean
isOn



public
void
turnOn(){







isOn
=
true;



} AVOID SIDE EFFECTS!



public
boolean
isOn(){







return
isOn;



}}
    24. 24. Use exceptionspublic
int
foo(){


...}public
void
bar(){


if(foo()
==
OK)





...


else





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


...}public
void
bar(){


if(foo()
==
OK)





...


else





//
error
handling}
    26. 26. Use exceptionspublic
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 exceptionspublic
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 exceptionspublic
void
foo()






throws
FooException{


...}public
void
bar(){


try{





foo();





...


}
catch(FooException){





//
error
handling


}}
    29. 29. Use exceptionspublic
void
foo()






throws
FooException{ No need to mix return


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


try{





foo();





...


}
catch(FooException){





//
error
handling


}}
    30. 30. Use exceptionspublic
void
foo()






throws
FooException{ No need to mix return


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


try{ Cleaner syntax





foo();





...


}
catch(FooException){





//
error
handling


}}
    31. 31. Use exceptionspublic
void
foo()






throws
FooException{ No need to mix return


...} values and control valuespublic
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 benefitsif ((employee.flags & HOURLY_FLAG) && (employee.age > 65)) if (employee.isEligibleForFullBenefits())
    36. 36. Comments GOOD BADAPI Documentation RedundantExplanation of intent Obsolete Clarification Code commented-out
    37. 37. Other code smellsWhat 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 violatedPrimitive obsession It is a symptom of bad and too much design parameters
    39. 39. Primitive obsessionpublic 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 hierarchyAlternative 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 bequestSubclass 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 preventersSomething is making hard to change the code A class has to be changedDivergent change in several parts A single change requires Shotgun surgery changes in several classes
    44. 44. The dispensables The code contains something unnecessaryA 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 littleInappropriate Intimacy as possible about each other Message Chains Too complex data access
    46. 46. Feature Envypublic class Customer{ private PhoneNumber mobilePhone; ... public String getMobilePhoneNumber(){ return “(” + mobilePhone.getAreaCode() + “)” + mobilePhone.getPrefix() + “-” + mobilePhone.getNumber(); }}
    47. 47. Feature Envypublic class Customer{ private PhoneNumber mobilePhone; ... public String getMobilePhoneNumber(){ return “(” + mobilePhone.getAreaCode() + “)” + mobilePhone.getPrefix() + “-” + mobilePhone.getNumber(); }} public String getMobilePhoneNumber(){ return mobilePhone.toFormattedString(); }
    48. 48. Message chainsa.getB().getC().getD().getTheNeededData() a.getTheNeededData() Law of Demeter: Each unit should only talk with friends

    ×