Ce diaporama a bien été signalé.
Nous utilisons votre profil LinkedIn et vos données d’activité pour vous proposer des publicités personnalisées et pertinentes. Vous pouvez changer vos préférences de publicités à tout moment.
Clean Code @mariosangiorgio
Why?
GoalsReadable, maintainable and    extendable code
Meaningful names
A simple examplepublic List<int[]> getThem() {  List<int[]> list1 = new ArrayList<int[]>();  for (int[] x : theList)    if...
A simple examplepublic List<int[]> getThem() {  List<int[]> list1 = new ArrayList<int[]>();  for (int[] x : theList)    if...
A simple examplepublic List<int[]> getThem() {  List<int[]> list1 = new ArrayList<int[]>();  for (int[] x : theList)    if...
A simple examplepublic List<int[]> getFlaggedCells() {  List<int[]> flaggedCells = new ArrayList<int[]>();  for (int[] cel...
A simple examplepublic 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         flaggedCellsrevealing names       rather than list1
A simple example             What we have done:    used intention          flaggedCells   revealing names        rather th...
A simple example             What we have done:    used intention          flaggedCells   revealing names        rather th...
Another exampleint d;            What does it mean?            Days? Diameter? ...
Another exampleint d;                       What does it mean?                       Days? Diameter? ...  int d; //elapsed...
Another exampleint d;                       What does it mean?                       Days? Diameter? ...  int d; //elapsed...
Functions
Do one thingpublic
bool
isEdible()
{

if
(this.ExpirationDate
>
Date.Now
&&






this.ApprovedForConsumption
==
true
&&

...
Do one thingpublic
bool
isEdible()
{

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






this.Approved...
Do one thingpublic
bool
isEdible()
{



return
isFresh()



&&         

isApproved()
&&                             Now t...
Do one thingpublic
bool
isEdible()
{



return
isFresh()



&&         

isApproved()
&&                             Now t...
Don’t mix levels of abstractionpublic
void
doTheDomesticThings()
{



takeOutTheTrash();                   public
void
doT...
Separate commands and queriesCommands should                 Queries shouldonly do something                only answer   ...
Use exceptionspublic
int
foo(){


...}public
void
bar(){


if(foo()
==
OK)





...


else





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


...}public
void
bar(){


if(foo()
==
...
Use exceptionspublic
int
foo(){                          Errors have to be encoded


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


...}public
void
bar(){               ...
Use exceptionspublic
void
foo()






throws
FooException{


...}public
void
bar(){


try{





foo();





...


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






throws
FooException{    No need to mix return


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






throws
FooException{    No need to mix return


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






throws
FooException{    No need to mix return


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

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

String
[]
elements
=
{“A”,
“B”,
“C”};pu...
Comments
Explain yourself in the code                Which one is clearer?// Check to see if the employee is eligible for full bene...
Comments      GOOD                    BADAPI Documentation           RedundantExplanation of intent        Obsolete    Cla...
Other code smellsWhat 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  ...
Primitive obsessionpublic Class Car{    private int red, green, blue;     public void paint(int red, int green, int blue){...
The OO abusers     Object orientation is not fully exploited Switch statements on         It is better to use        objec...
Switch vs polymorphism public Money calculatePay(Employee e)     throws InvalidEmployeeType{         switch(e.type){      ...
Refused bequestSubclass doesn’t use superclass methods and attributes         public abstract class Employee{             ...
The change preventersSomething is making hard to change the code                     A class has to be changedDivergent ch...
The dispensables The code contains something unnecessaryA class is not doing                       Class not providing log...
The couplers        Some classes are too tightly coupled    Feature Envy           Misplaced responsibility               ...
Feature Envypublic class Customer{    private PhoneNumber mobilePhone;    ...    public String getMobilePhoneNumber(){    ...
Feature Envypublic class Customer{    private PhoneNumber mobilePhone;    ...    public String getMobilePhoneNumber(){    ...
Message chainsa.getB().getC().getD().getTheNeededData()          a.getTheNeededData()  Law of Demeter: Each unit should   ...
Prochain SlideShare
Chargement dans…5
×

Clean code and Code Smells

16 291 vues

Publié le

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

Publié dans : Technologie
  • Doctor's 2-Minute Ritual For Shocking Daily Belly Fat Loss! Watch This Video ■■■ https://tinyurl.com/bkfitness4u
       Répondre 
    Voulez-vous vraiment ?  Oui  Non
    Votre message apparaîtra ici
  • DOWNLOAD FULL BOOKS, INTO AVAILABLE FORMAT ......................................................................................................................... ......................................................................................................................... 1.DOWNLOAD FULL. PDF EBOOK here { https://tinyurl.com/y8nn3gmc } ......................................................................................................................... 1.DOWNLOAD FULL. EPUB Ebook here { https://tinyurl.com/y8nn3gmc } ......................................................................................................................... 1.DOWNLOAD FULL. doc Ebook here { https://tinyurl.com/y8nn3gmc } ......................................................................................................................... 1.DOWNLOAD FULL. PDF EBOOK here { https://tinyurl.com/y8nn3gmc } ......................................................................................................................... 1.DOWNLOAD FULL. EPUB Ebook here { https://tinyurl.com/y8nn3gmc } ......................................................................................................................... 1.DOWNLOAD FULL. doc Ebook here { https://tinyurl.com/y8nn3gmc } ......................................................................................................................... ......................................................................................................................... ......................................................................................................................... .............. Browse by Genre Available eBooks ......................................................................................................................... Art, Biography, Business, Chick Lit, Children's, Christian, Classics, Comics, Contemporary, Cookbooks, Crime, Ebooks, Fantasy, Fiction, Graphic Novels, Historical Fiction, History, Horror, Humor And Comedy, Manga, Memoir, Music, Mystery, Non Fiction, Paranormal, Philosophy, Poetry, Psychology, Religion, Romance, Science, Science Fiction, Self Help, Suspense, Spirituality, Sports, Thriller, Travel, Young Adult,
       Répondre 
    Voulez-vous vraiment ?  Oui  Non
    Votre message apparaîtra ici
  • Download The Complete Lean Belly Breakthrough Program with Special Discount.  https://tinyurl.com/bkfitness4u
       Répondre 
    Voulez-vous vraiment ?  Oui  Non
    Votre message apparaîtra ici
  • .DOWNLOAD THIS BOOKS INTO AVAILABLE FORMAT ......................................................................................................................... ......................................................................................................................... .DOWNLOAD PDF EBOOK here { https://tinyurl.com/y8nn3gmc } ......................................................................................................................... .DOWNLOAD EPUB Ebook here { https://tinyurl.com/y8nn3gmc } ......................................................................................................................... .DOWNLOAD doc Ebook here { https://tinyurl.com/y8nn3gmc } ......................................................................................................................... .DOWNLOAD PDF EBOOK here { https://tinyurl.com/y8nn3gmc } ......................................................................................................................... .DOWNLOAD EPUB Ebook here { https://tinyurl.com/y8nn3gmc } ......................................................................................................................... .DOWNLOAD doc Ebook here { https://tinyurl.com/y8nn3gmc } ......................................................................................................................... ......................................................................................................................... ......................................................................................................................... .............. Browse by Genre Available eBooks ......................................................................................................................... Art, Biography, Business, Chick Lit, Children's, Christian, Classics, Comics, Contemporary, Cookbooks, Crime, Ebooks, Fantasy, Fiction, Graphic Novels, Historical Fiction, History, Horror, Humor And Comedy, Manga, Memoir, Music, Mystery, Non Fiction, Paranormal, Philosophy, Poetry, Psychology, Religion, Romance, Science, Science Fiction, Self Help, Suspense, Spirituality, Sports, Thriller, Travel, Young Adult,
       Répondre 
    Voulez-vous vraiment ?  Oui  Non
    Votre message apparaîtra ici

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

×