SlideShare a Scribd company logo
Clean Code 2
Fredrik Wendt
Clean Code
  what, why, how
http://blog.xebia.com/2009/01/clean-code-vs-implementation-patterns/
Disclaimer




 Correlation between
Clean code and success?
How is it even possible
for code to be this bad?
Exhibits
    • Hudson class is 3900+
      LOC
    • Hudson class is untestable
      Singleton
    • Constructor calls a method
      that gets the singleton
      instance and calls a method
      on the instance.
    • Hudson extends Node, but
      Node calls methods defined
      in Hudson
WTF!
So why care – Jenkins is great?
Clean Code 2
”Smart” vs Professional
• Smart                                • Professional
  ●   Great coding skills                  ●   Readable code
  ●   Writes advanced code                 ●   Maintainable code
  ●   String r; // lowercase url           ●   'Clarity is king'
                                           ●   String lowerCaseUrl
                                               OfCurrentPage;




               http://www.slideshare.net/JandV/clean-code-summary
What is Clean Code?
int d; // elapsed time in days
int d; // elapsed time in days
int elapsedTimeInDays;
int d; // elapsed time in days
int elapsedTimeInDays;
int daysSinceCreation;
int d; // elapsed time in days
int elapsedTimeInDays;
int daysSinceCreation;
int fileAgeInDays;
public List<int[]> getThem() {
    List<int[]> list1 = new ArrayList<int[]>();
    for (int[] x : theList)
      if (x[0] == 4)
        list1.add(x);
    return list1;
}
public List<int[]> getThem() {
    List<int[]> list1 = new ArrayList<int[]>();
    for (int[] cell : gameBoard)
      if (cell[STATUS_VALUE] == FLAGGED)
        list1.add(cell);
    return list1;
}
public List<int[]> getFlaggedCells() {
    List<int[]> flaggedCells = new ArrayList<int[]>();
    for (int[] cell : gameBoard)
      if (cell[STATUS_VALUE] == FLAGGED)
        flaggedCells.add(cell);
    return flaggedCells;
}
public List<Cell> getFlaggedCells() {
    List<Cell> flaggedCells = new ArrayList<Cell>();
    for (Cell cell : gameBoard)
      if (cell.isFlagged())
        flaggedCells.add(cell);
    return flaggedCells;
}
Clean code always

looks like it was written by

    someone who cares
Clean code always

looks like it was wrtten by

    somone who craes
Readable
Maintainable
Changeable
Agile Manifesto


Individuals and interactions
     over processes and tools
Working software
     over comprehensive documentation
Customer collaboration
     over contract negotiation
Responding to change
     over following a plan
Clean Code 2
Readable?
~ 90% of your time is reading

                  What if you'd
                ddouble write-time
                   and thereby
                  cut read-time
                     by half?
public class Part {
    private String m_dsc; // The textual description
    void setName(String name) {
        m_dsc = name;
    }
}


public class Part {
    private String description;
    void setDescription(String description) {
        this.description = description;
    }
}
Still, why bother?
Code is written for humans!
Why?
Who's the main recipient of the code we write – a computer, an
end user or a programmer?
The primary user of source
code is a programmer, perhaps
   ●   your Customer
   ●   your Colleague
   ●   You
How should I write code?
DRY - Don't Repeat Yourself


YAGNI - You Ain't Gonna Need It
small
Meaningful Names
• Intention-Revealing   • JobQueue
• Pronounceable         • Words from the domain
• Avoid Encoding
                        • Comments
• Classes               • Formatting!
• Methods
Law of Demeter

  More formally, the Law of Demeter
      for functions requires that
      a method M of an object O
   may only invoke the methods of
    the following kinds of objects:

1. O itself
2. M's parameters
3. any objects created/instantiated within M
4. O's direct component objects
5. a variable, accessible by O, in the scope of M
Dog's Legs
public class CareTaker {
    private Dog dog;
    ...
    public void walkTheDog(){
        dog.walk();


        dog.stop(); // tree or grass etc


        dog.doYourThing();
        ...
    }
}
Dog's Legs
public class CareTaker {
    private Dog dog;
    ...
    public void walkTheDog(){
        for (Leg leg : dog.getLegs())
          leg.move();
        for (Leg leg : dog.getLegs())
          leg.stopMoving();
        dog.brain.urinationCenter.releaseUrge();
        ...
    }
}
Don't talk to strangers



http://www.ccs.neu.edu/research/demeter/demeter-method/LawOfDemeter/paper-boy/
Law of Demeter
public class PaperBoy {
    private Wallet myWallet;
    ...
    public void chargeCustomer(Customer customer) {
        Wallet wallet = customer.getWallet();
        Collection<Bill> bills = wallet.getBills();
        Collection<Bill> payment = extract(5, bills);
        myWallet.add(payment); // or bills?
    }
}
Law of Demeter
public class PaperBoy {
    private Wallet myWallet;
    ...
    public void chargeCustomer(Customer customer) {
        Collection<Bill> payment = customer.getPayment(5);
        myWallet.add(payment);
    }
}
Single Responsibility




       1
        small
Clean Code 2
Boy Scout Rule




Leave the campground cleaner than you found it.
Hur mäter man Clean Code?
       Eller kodkvalitet?
Can you measure Clean Code?
        Or code quality?
WTFs / minute




The only valid
measurement of
 code quality
Summary


     Source code vs machine code
   Write with the audience in minde
        Smart vs Professional
    Code quality and retrospectives
Code Review (wtf!) vs pair programming
Legacy Code




Code with no tests
What about the code that's
already in my backpack?


• Get the old man on track
  – make the code testable
  (and tested)
• Fix bugs brought out in
  daylight by the tests
• ”Make it right”
What about the code that's
already in my backpack?


• Get the old man on track
  – make the code testable
  (and tested)
• Fix bugs brought out in
  daylight by the tests
• ”Make it right” – refactor!
Code without tests ...
• is legacy code
• is not refactored
• unlikely to be changed by
   someone other than the
   person who wrote it (the
   past few days)
• is heavy load/back pack

More Related Content

PPTX
Clean Code - Design Patterns and Best Practices at Silicon Valley Code Camp
PPTX
Clean Code II - Dependency Injection
PPTX
Clean Code I - Best Practices
PPTX
Clean Code for East Bay .NET User Group
PDF
Clean code & design patterns
PDF
Clean Code at Silicon Valley Code Camp 2011 (02/17/2012)
PPTX
Clean Code Part I - Design Patterns at SoCal Code Camp
PPTX
Clean Code Part III - Craftsmanship at SoCal Code Camp
Clean Code - Design Patterns and Best Practices at Silicon Valley Code Camp
Clean Code II - Dependency Injection
Clean Code I - Best Practices
Clean Code for East Bay .NET User Group
Clean code & design patterns
Clean Code at Silicon Valley Code Camp 2011 (02/17/2012)
Clean Code Part I - Design Patterns at SoCal Code Camp
Clean Code Part III - Craftsmanship at SoCal Code Camp

What's hot (20)

PPTX
Clean Code II - Dependency Injection at SoCal Code Camp San Diego (07/27/2013)
PDF
Contract First Development with Microsoft Code Contracts and Microsoft Pex at...
PPTX
Clean Code - Design Patterns and Best Practices for Bay.NET SF User Group (01...
PDF
Clean code
PDF
Mental models, complexity and software
PDF
Lego For Engineers - Dependency Injection for LIDNUG (2011-06-03)
PPTX
Clean Code Part II - Dependency Injection at SoCal Code Camp
PDF
.NET Coding Standards For The Real World (2012)
PPTX
Clean Code I - Design Patterns and Best Practices at SoCal Code Camp San Dieg...
PPTX
Stop wasting-time-by-applying-clean-code-principles
PPTX
Clean Code Part i - Design Patterns and Best Practices -
PDF
Lego for Software Engineers at Silicon Valley Code Camp 2011 (2010-10-10)
PPTX
Clean Code III - Software Craftsmanship
PPTX
Writing High Quality Code in C#
PDF
WordCamp US: Clean Code
PPTX
C# coding standards, good programming principles & refactoring
ODP
Clean code
PPTX
Tdd is not about testing (C++ version)
PPTX
Tdd is not about testing (OOP)
PDF
Clean Code II - Dependency Injection at SoCal Code Camp San Diego (07/27/2013)
Contract First Development with Microsoft Code Contracts and Microsoft Pex at...
Clean Code - Design Patterns and Best Practices for Bay.NET SF User Group (01...
Clean code
Mental models, complexity and software
Lego For Engineers - Dependency Injection for LIDNUG (2011-06-03)
Clean Code Part II - Dependency Injection at SoCal Code Camp
.NET Coding Standards For The Real World (2012)
Clean Code I - Design Patterns and Best Practices at SoCal Code Camp San Dieg...
Stop wasting-time-by-applying-clean-code-principles
Clean Code Part i - Design Patterns and Best Practices -
Lego for Software Engineers at Silicon Valley Code Camp 2011 (2010-10-10)
Clean Code III - Software Craftsmanship
Writing High Quality Code in C#
WordCamp US: Clean Code
C# coding standards, good programming principles & refactoring
Clean code
Tdd is not about testing (C++ version)
Tdd is not about testing (OOP)
Ad

Viewers also liked (8)

PDF
Informationsradiatorer NFI Systemunderhåll 2015-12-01
ODP
Clean code
PPTX
Accidentally Manager – A Survival Guide for First-Time Engineering Managers
KEY
Clean code and Code Smells
PPTX
Clean Code: Stop wasting my time
PPTX
Clean Code
PDF
Clean code
PDF
Clean coding-practices
Informationsradiatorer NFI Systemunderhåll 2015-12-01
Clean code
Accidentally Manager – A Survival Guide for First-Time Engineering Managers
Clean code and Code Smells
Clean Code: Stop wasting my time
Clean Code
Clean code
Clean coding-practices
Ad

Similar to Clean Code 2 (20)

PDF
Clean code
PDF
Clean code and code smells
PPTX
Clean Code
PPTX
Principled And Clean Coding
PDF
Clean Code
PPTX
Clean code
PPTX
R. herves. clean code (theme)2
PPTX
Code reviews
PPTX
Writing Clean Code (Recommendations by Robert Martin)
PPTX
Clean code bites
PPTX
Writing clean code in C# and .NET
PPT
Writing Good Code
ODP
Clean Code
PPTX
Clean code
PPTX
Clean code presentation
PPTX
Coding Checkpoints
PDF
Clean Code
PDF
Java Code Review Checklist
PPT
Clean code
PPTX
Clean code - DSC DYPCOE
Clean code
Clean code and code smells
Clean Code
Principled And Clean Coding
Clean Code
Clean code
R. herves. clean code (theme)2
Code reviews
Writing Clean Code (Recommendations by Robert Martin)
Clean code bites
Writing clean code in C# and .NET
Writing Good Code
Clean Code
Clean code
Clean code presentation
Coding Checkpoints
Clean Code
Java Code Review Checklist
Clean code
Clean code - DSC DYPCOE

More from Fredrik Wendt (11)

PDF
Continuous Delivery Experience Report - Agile Greece Summit 2016
PDF
Go.cd - the tool that Jenkins ain't
PDF
Impact of CD, Clean Code, ... on Team Performance
PDF
Arkitektur i agila projekt
PDF
Coding dojos på arbetstid
ODP
Js Test Driver, JsHamcrest, JsMockito
PDF
Jdojo@Gbg Introduction
ODP
Presentation of JSConf.eu
ODP
Agile Injection, Varberg
PDF
Webboptimering 25 min
ODP
Using Mockito
Continuous Delivery Experience Report - Agile Greece Summit 2016
Go.cd - the tool that Jenkins ain't
Impact of CD, Clean Code, ... on Team Performance
Arkitektur i agila projekt
Coding dojos på arbetstid
Js Test Driver, JsHamcrest, JsMockito
Jdojo@Gbg Introduction
Presentation of JSConf.eu
Agile Injection, Varberg
Webboptimering 25 min
Using Mockito

Recently uploaded (20)

PDF
Network Security Unit 5.pdf for BCA BBA.
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PPTX
breach-and-attack-simulation-cybersecurity-india-chennai-defenderrabbit-2025....
PDF
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
PDF
Empathic Computing: Creating Shared Understanding
DOCX
The AUB Centre for AI in Media Proposal.docx
PPTX
MYSQL Presentation for SQL database connectivity
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PDF
Modernizing your data center with Dell and AMD
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PDF
cuic standard and advanced reporting.pdf
PDF
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
PDF
Spectral efficient network and resource selection model in 5G networks
PDF
KodekX | Application Modernization Development
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
Network Security Unit 5.pdf for BCA BBA.
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
Mobile App Security Testing_ A Comprehensive Guide.pdf
breach-and-attack-simulation-cybersecurity-india-chennai-defenderrabbit-2025....
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
Empathic Computing: Creating Shared Understanding
The AUB Centre for AI in Media Proposal.docx
MYSQL Presentation for SQL database connectivity
Chapter 3 Spatial Domain Image Processing.pdf
“AI and Expert System Decision Support & Business Intelligence Systems”
Advanced methodologies resolving dimensionality complications for autism neur...
Modernizing your data center with Dell and AMD
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
cuic standard and advanced reporting.pdf
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
Spectral efficient network and resource selection model in 5G networks
KodekX | Application Modernization Development
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows

Clean Code 2

  • 3. Clean Code what, why, how
  • 6. How is it even possible for code to be this bad?
  • 7. Exhibits • Hudson class is 3900+ LOC • Hudson class is untestable Singleton • Constructor calls a method that gets the singleton instance and calls a method on the instance. • Hudson extends Node, but Node calls methods defined in Hudson
  • 8. WTF! So why care – Jenkins is great?
  • 10. ”Smart” vs Professional • Smart • Professional ● Great coding skills ● Readable code ● Writes advanced code ● Maintainable code ● String r; // lowercase url ● 'Clarity is king' ● String lowerCaseUrl OfCurrentPage; http://www.slideshare.net/JandV/clean-code-summary
  • 11. What is Clean Code?
  • 12. int d; // elapsed time in days
  • 13. int d; // elapsed time in days int elapsedTimeInDays;
  • 14. int d; // elapsed time in days int elapsedTimeInDays; int daysSinceCreation;
  • 15. int d; // elapsed time in days int elapsedTimeInDays; int daysSinceCreation; int fileAgeInDays;
  • 16. public List<int[]> getThem() { List<int[]> list1 = new ArrayList<int[]>(); for (int[] x : theList) if (x[0] == 4) list1.add(x); return list1; }
  • 17. public List<int[]> getThem() { List<int[]> list1 = new ArrayList<int[]>(); for (int[] cell : gameBoard) if (cell[STATUS_VALUE] == FLAGGED) list1.add(cell); return list1; }
  • 18. public List<int[]> getFlaggedCells() { List<int[]> flaggedCells = new ArrayList<int[]>(); for (int[] cell : gameBoard) if (cell[STATUS_VALUE] == FLAGGED) flaggedCells.add(cell); return flaggedCells; }
  • 19. public List<Cell> getFlaggedCells() { List<Cell> flaggedCells = new ArrayList<Cell>(); for (Cell cell : gameBoard) if (cell.isFlagged()) flaggedCells.add(cell); return flaggedCells; }
  • 20. Clean code always looks like it was written by someone who cares
  • 21. Clean code always looks like it was wrtten by somone who craes
  • 23. Agile Manifesto Individuals and interactions over processes and tools Working software over comprehensive documentation Customer collaboration over contract negotiation Responding to change over following a plan
  • 26. ~ 90% of your time is reading What if you'd ddouble write-time and thereby cut read-time by half?
  • 27. public class Part { private String m_dsc; // The textual description void setName(String name) { m_dsc = name; } } public class Part { private String description; void setDescription(String description) { this.description = description; } }
  • 29. Code is written for humans!
  • 30. Why? Who's the main recipient of the code we write – a computer, an end user or a programmer? The primary user of source code is a programmer, perhaps ● your Customer ● your Colleague ● You
  • 31. How should I write code?
  • 32. DRY - Don't Repeat Yourself YAGNI - You Ain't Gonna Need It
  • 33. small
  • 34. Meaningful Names • Intention-Revealing • JobQueue • Pronounceable • Words from the domain • Avoid Encoding • Comments • Classes • Formatting! • Methods
  • 35. Law of Demeter More formally, the Law of Demeter for functions requires that a method M of an object O may only invoke the methods of the following kinds of objects: 1. O itself 2. M's parameters 3. any objects created/instantiated within M 4. O's direct component objects 5. a variable, accessible by O, in the scope of M
  • 36. Dog's Legs public class CareTaker { private Dog dog; ... public void walkTheDog(){ dog.walk(); dog.stop(); // tree or grass etc dog.doYourThing(); ... } }
  • 37. Dog's Legs public class CareTaker { private Dog dog; ... public void walkTheDog(){ for (Leg leg : dog.getLegs()) leg.move(); for (Leg leg : dog.getLegs()) leg.stopMoving(); dog.brain.urinationCenter.releaseUrge(); ... } }
  • 38. Don't talk to strangers http://www.ccs.neu.edu/research/demeter/demeter-method/LawOfDemeter/paper-boy/
  • 39. Law of Demeter public class PaperBoy { private Wallet myWallet; ... public void chargeCustomer(Customer customer) { Wallet wallet = customer.getWallet(); Collection<Bill> bills = wallet.getBills(); Collection<Bill> payment = extract(5, bills); myWallet.add(payment); // or bills? } }
  • 40. Law of Demeter public class PaperBoy { private Wallet myWallet; ... public void chargeCustomer(Customer customer) { Collection<Bill> payment = customer.getPayment(5); myWallet.add(payment); } }
  • 43. Boy Scout Rule Leave the campground cleaner than you found it.
  • 44. Hur mäter man Clean Code? Eller kodkvalitet?
  • 45. Can you measure Clean Code? Or code quality?
  • 46. WTFs / minute The only valid measurement of code quality
  • 47. Summary Source code vs machine code Write with the audience in minde Smart vs Professional Code quality and retrospectives Code Review (wtf!) vs pair programming
  • 49. What about the code that's already in my backpack? • Get the old man on track – make the code testable (and tested) • Fix bugs brought out in daylight by the tests • ”Make it right”
  • 50. What about the code that's already in my backpack? • Get the old man on track – make the code testable (and tested) • Fix bugs brought out in daylight by the tests • ”Make it right” – refactor!
  • 51. Code without tests ... • is legacy code • is not refactored • unlikely to be changed by someone other than the person who wrote it (the past few days) • is heavy load/back pack