SlideShare a Scribd company logo
Best practice       Luigi De Russis




                Clean Code
2       Measuring code quality




Clean Code                       07/03/2013
The only valid measurement: WTFs/min
3



                 Good code               Bad code

                                                    WTF,
         WTF                       WTF              this is shit!


                    CODE                   CODE
                   REVIEW    WTF          REVIEW    WTF
                                   WTF

                                                    Dude,
                                                    WTF


                                                    WTF




    Clean Code                                      07/03/2013
4       Goals




Clean Code      07/03/2013
Code MUST be…
5




          Readable   Maintainable


       Extendable      Testable
    Clean Code                07/03/2013
6       How?




Clean Code     07/03/2013
7   Clean Code   07/03/2013
8       Meaningful names




Clean Code                 07/03/2013
An example…
9

    public List<int[]> getThem()
    {
        List<int[]> list = new ArrayList<int[]>();
        for (int[] x : theList)
             if (x[0] == 4)
                 list.add(x);
        return list;
    }



                      What does this code do?

    Clean Code                                       07/03/2013
An example…
10

     public List<int[]> getFlaggedCells()
     {
         List<int[]> flaggedCells = new ArrayList<int[]>();
         for (int[] cell : gameBoard)
              if (cell[STATUS_VALUE] == FLAGGED)
                  flaggedCell.add(cell);
         return flaggedCells;
     }



                                  Better?

     Clean Code                                          07/03/2013
An example…
11

     public List<Cell> getFlaggedCells()
     {
         List<Cell> flaggedCells = new ArrayList<Cell>();
         for (Cell cell : gameBoard)
              if (cell.isFlagged())
                  flaggedCell.add(cell);
         return flaggedCells;
     }



                            What about this?

     Clean Code                                             07/03/2013
What we have done
12




     Used intention           flaggedCells rather
     revealing names          than list

     Replaced magic           cell[STATUS_VALUE]
     numbers with constants   rather than x[0]

     Created an appropriate   Cell cell rather than
     abstract data type       int[] cell

     Clean Code                               07/03/2013
Another example…
13

     class DtaRcrd102
     {
         private Date genymdhms;
         private Date modymdhms;
         private final String pszqint = “102”;
         /* ... */
     }



           Use pronounceable and searchable names
                          (please!)

     Clean Code                                  07/03/2013
Another example…
14

     class Customer
     {
         private Date generationTimeStamp;
         private Date modificationTimeStamp;
         private final String recordId = “102”;
         /* ... */
     }



                               Better?


     Clean Code                                   07/03/2013
15       Functions




 Clean Code          07/03/2013
Functions
16




                     Small



                  Do One Thing

     Clean Code                  07/03/2013
Do One Thing
17



     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?


     Clean Code                                              07/03/2013
Do One Thing
18


     public bool isEdible()
     {
          return isFresh() &&
                  isApproved() &&
                  isInspected();
     }

              Now the function is doing one thing!
         A change in the specification turns into a single
                      change in the code.

     Clean Code                                      07/03/2013
Functions
19




          Handle errors (and use exceptions)


                  Don’t Repeat Yourself
                  (avoid copy-and-paste code)

     Clean Code                                 07/03/2013
20       Comments




 Clean Code         07/03/2013
Explain yourself in the code
21




                        Which one is cleaner?

        //check to see if the employee is eligible for full benefits
          if((employee.flags & HOURLY_FLAG) && (employee.age > 65))




                  if(employee.isEligibleForFullBenefits())




     Clean Code                                                07/03/2013
Explain yourself in the code
22




                        Which one is cleaner?

        //check to see if the employee is eligible for full benefits
          if((employee.flags & HOURLY_FLAG) && (employee.age > 65))




                  if(employee.isEligibleForFullBenefits())




     Clean Code                                                07/03/2013
API Documentation

     YES            Explanation of intent
                    Clarification
                    Warning of consequences


                    Orphan comments

     NO             Obsolete comments
                    Noise comments
                    Code commented-out

23     Clean Code                        07/03/2013
24       Formatting




 Clean Code           07/03/2013
Formatting
25




                  Communication is the purpose of
                           formatting

        Vertical openness between concepts
        Each blank line is a visual cue that identifies a new and separate concept




     Clean Code                                                            07/03/2013
Breaking Indentation
26



     public class CommentWidget extends TextWidget {
         public static final String REGEXP =
                  “^#[rn]*(?:(?:rn)|n|r)?”;
         public CommentWidget(String text) { super(text); }
         public String render() throws Exception { return “”; }
     }


                                   Eh?



     Clean Code                                          07/03/2013
Breaking Indentation
27


     public class CommentWidget extends TextWidget
     {
        public static final String REGEXP =
              “^#[rn]*(?:(?:rn)|n|r)?”;

         public CommentWidget(String text)
         {                                           Better?
            super(text);
         }

         public String render() throws Exception
         {
            return “”;
         }
     }

     Clean Code                                           07/03/2013
28       Conventions




 Clean Code            07/03/2013
Conventions
29



                    Conventions enable common
                          understanding

      Stick to the language-specific conventions

                  Respect team-level conventions
                   Still complying with the language-specific conventions…
     Clean Code                                                              07/03/2013
References
30


        Robert C. Martin Series, “Clean Code - A Handbook
         of Agile Software Craftsmanship”, Prentice Hall
        Geek and Poke,
         http://geekandpoke.typepad.com/
        OSNews Comics, http://www.osnews.com/comics




     Clean Code                                     07/03/2013
License
31

        This work is licensed under the Creative Commons “Attribution-
         NonCommercial-ShareAlike Unported (CC BY-NC-SA 3,0)” License.
        You are free:
            to Share - to copy, distribute and transmit the work
            to Remix - to adapt the work
        Under the following conditions:
            Attribution - You must attribute the work in the manner specified by the
             author or licensor (but not in any way that suggests that they endorse
             you or your use of the work).
            Noncommercial - You may not use this work for commercial purposes.
            Share Alike - If you alter, transform, or build upon this work, you may
             distribute the resulting work only under the same or similar license to this
             one.
        To view a copy of this license, visit
         http://creativecommons.org/licenses/by-nc-sa/3.0/
     Clean Code                                                                07/03/2013

More Related Content

What's hot

Clean code and Code Smells
Clean code and Code SmellsClean code and Code Smells
Clean code and Code Smells
Mario Sangiorgio
 
Clean code slide
Clean code slideClean code slide
Clean code slide
Anh Huan Miu
 
Clean code
Clean codeClean code
Clean code
Arturo Herrero
 
Clean code
Clean codeClean code
Clean code
Henrique Smoco
 
Clean code & design patterns
Clean code & design patternsClean code & design patterns
Clean code & design patterns
Pascal Larocque
 
Clean Code - Design Patterns and Best Practices at Silicon Valley Code Camp
Clean Code - Design Patterns and Best Practices at Silicon Valley Code CampClean Code - Design Patterns and Best Practices at Silicon Valley Code Camp
Clean Code - Design Patterns and Best Practices at Silicon Valley Code Camp
Theo Jungeblut
 
Clean code
Clean codeClean code
Clean code
Mahmoud Zizo
 
Clean code
Clean codeClean code
Clean code
Jean Carlo Machado
 
Clean Code: Successive Refinement
Clean Code: Successive RefinementClean Code: Successive Refinement
Clean Code: Successive Refinement
Ali A Jalil
 
Clean Code II - Dependency Injection
Clean Code II - Dependency InjectionClean Code II - Dependency Injection
Clean Code II - Dependency Injection
Theo Jungeblut
 
C++11 & C++14
C++11 & C++14C++11 & C++14
C++11 & C++14
CyberPlusIndia
 
Coding standards
Coding standardsCoding standards
Coding standards
Mark Reynolds
 
Clean Code summary
Clean Code summaryClean Code summary
Clean Code summary
Jan de Vries
 
Clean code
Clean codeClean code
Clean code
Knoldus Inc.
 
Clean Code
Clean CodeClean Code
Clean Code
swaraj Patil
 
Clean Code
Clean CodeClean Code
Clean Code
ISchwarz23
 
Exception Handling
Exception HandlingException Handling
Exception Handling
Reddhi Basu
 
Java exception handling ppt
Java exception handling pptJava exception handling ppt
Java exception handling ppt
JavabynataraJ
 

What's hot (20)

Clean code and Code Smells
Clean code and Code SmellsClean code and Code Smells
Clean code and Code Smells
 
Clean code slide
Clean code slideClean code slide
Clean code slide
 
Clean code
Clean codeClean code
Clean code
 
Clean code
Clean codeClean code
Clean code
 
Chapter17 of clean code
Chapter17 of clean codeChapter17 of clean code
Chapter17 of clean code
 
Clean code & design patterns
Clean code & design patternsClean code & design patterns
Clean code & design patterns
 
Clean Code - Design Patterns and Best Practices at Silicon Valley Code Camp
Clean Code - Design Patterns and Best Practices at Silicon Valley Code CampClean Code - Design Patterns and Best Practices at Silicon Valley Code Camp
Clean Code - Design Patterns and Best Practices at Silicon Valley Code Camp
 
Clean code
Clean codeClean code
Clean code
 
Clean code
Clean codeClean code
Clean code
 
Clean Code: Successive Refinement
Clean Code: Successive RefinementClean Code: Successive Refinement
Clean Code: Successive Refinement
 
Clean Code II - Dependency Injection
Clean Code II - Dependency InjectionClean Code II - Dependency Injection
Clean Code II - Dependency Injection
 
C++11 & C++14
C++11 & C++14C++11 & C++14
C++11 & C++14
 
Coding standards
Coding standardsCoding standards
Coding standards
 
Clean Code summary
Clean Code summaryClean Code summary
Clean Code summary
 
Clean code
Clean codeClean code
Clean code
 
Clean Code
Clean CodeClean Code
Clean Code
 
Clean Code
Clean CodeClean Code
Clean Code
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
Exception handling in Java
Exception handling in JavaException handling in Java
Exception handling in Java
 
Java exception handling ppt
Java exception handling pptJava exception handling ppt
Java exception handling ppt
 

Similar to Clean Code

Finding bugs that matter with Findbugs
Finding bugs that matter with FindbugsFinding bugs that matter with Findbugs
Finding bugs that matter with FindbugsCarol McDonald
 
Clean Code 2
Clean Code 2Clean Code 2
Clean Code 2
Fredrik Wendt
 
Spock Framework
Spock FrameworkSpock Framework
Clean code bites
Clean code bitesClean code bites
Clean code bites
Roy Nitert
 
Encapsulation
EncapsulationEncapsulation
Encapsulation
Ducat India
 
C# coding standards, good programming principles & refactoring
C# coding standards, good programming principles & refactoringC# coding standards, good programming principles & refactoring
C# coding standards, good programming principles & refactoring
Eyob Lube
 
GS-4150, Bullet 3 OpenCL Rigid Body Simulation, by Erwin Coumans
GS-4150, Bullet 3 OpenCL Rigid Body Simulation, by Erwin CoumansGS-4150, Bullet 3 OpenCL Rigid Body Simulation, by Erwin Coumans
GS-4150, Bullet 3 OpenCL Rigid Body Simulation, by Erwin Coumans
AMD Developer Central
 
Presentacion clean code
Presentacion clean codePresentacion clean code
Presentacion clean code
IBM
 
Javascript Deofuscation A manual Approach
Javascript Deofuscation A manual ApproachJavascript Deofuscation A manual Approach
Javascript Deofuscation A manual Approach
Gregory Hanis
 
Clean Code
Clean CodeClean Code
Clean Code
Nascenia IT
 
Midiendo la calidad de código en WTF/Min (Revisado EUI Abril 2014)
Midiendo la calidad de código en WTF/Min (Revisado EUI Abril 2014)Midiendo la calidad de código en WTF/Min (Revisado EUI Abril 2014)
Midiendo la calidad de código en WTF/Min (Revisado EUI Abril 2014)David Gómez García
 
20191116 DevFest 2019 The Legacy Code came to stay (El legacy vino para queda...
20191116 DevFest 2019 The Legacy Code came to stay (El legacy vino para queda...20191116 DevFest 2019 The Legacy Code came to stay (El legacy vino para queda...
20191116 DevFest 2019 The Legacy Code came to stay (El legacy vino para queda...
Antonio de la Torre Fernández
 
Unethical JavaScript - Giorgio Natili - Codemotion Rome 2017
Unethical JavaScript - Giorgio Natili - Codemotion Rome 2017Unethical JavaScript - Giorgio Natili - Codemotion Rome 2017
Unethical JavaScript - Giorgio Natili - Codemotion Rome 2017
Codemotion
 
Oleksandr Valetskyy - DI vs. IoC
Oleksandr Valetskyy - DI vs. IoCOleksandr Valetskyy - DI vs. IoC
Oleksandr Valetskyy - DI vs. IoC
Oleksandr Valetskyy
 
Eclipse Democamp Zurich
Eclipse Democamp ZurichEclipse Democamp Zurich
Eclipse Democamp Zurich
Marcel Bruch
 
Making an Exception
Making an ExceptionMaking an Exception
Making an Exception
Kevlin Henney
 
Object Oriented Concepts and Principles
Object Oriented Concepts and PrinciplesObject Oriented Concepts and Principles
Object Oriented Concepts and Principles
deonpmeyer
 
Extension methods, nulls, namespaces and precedence in c#
Extension methods, nulls, namespaces and precedence in c#Extension methods, nulls, namespaces and precedence in c#
Extension methods, nulls, namespaces and precedence in c#
Paul Houle
 

Similar to Clean Code (20)

Clean code
Clean codeClean code
Clean code
 
Finding bugs that matter with Findbugs
Finding bugs that matter with FindbugsFinding bugs that matter with Findbugs
Finding bugs that matter with Findbugs
 
Clean Code 2
Clean Code 2Clean Code 2
Clean Code 2
 
Spock Framework
Spock FrameworkSpock Framework
Spock Framework
 
Clean code bites
Clean code bitesClean code bites
Clean code bites
 
Encapsulation
EncapsulationEncapsulation
Encapsulation
 
C# coding standards, good programming principles & refactoring
C# coding standards, good programming principles & refactoringC# coding standards, good programming principles & refactoring
C# coding standards, good programming principles & refactoring
 
unit_tests_tutorial
unit_tests_tutorialunit_tests_tutorial
unit_tests_tutorial
 
GS-4150, Bullet 3 OpenCL Rigid Body Simulation, by Erwin Coumans
GS-4150, Bullet 3 OpenCL Rigid Body Simulation, by Erwin CoumansGS-4150, Bullet 3 OpenCL Rigid Body Simulation, by Erwin Coumans
GS-4150, Bullet 3 OpenCL Rigid Body Simulation, by Erwin Coumans
 
Presentacion clean code
Presentacion clean codePresentacion clean code
Presentacion clean code
 
Javascript Deofuscation A manual Approach
Javascript Deofuscation A manual ApproachJavascript Deofuscation A manual Approach
Javascript Deofuscation A manual Approach
 
Clean Code
Clean CodeClean Code
Clean Code
 
Midiendo la calidad de código en WTF/Min (Revisado EUI Abril 2014)
Midiendo la calidad de código en WTF/Min (Revisado EUI Abril 2014)Midiendo la calidad de código en WTF/Min (Revisado EUI Abril 2014)
Midiendo la calidad de código en WTF/Min (Revisado EUI Abril 2014)
 
20191116 DevFest 2019 The Legacy Code came to stay (El legacy vino para queda...
20191116 DevFest 2019 The Legacy Code came to stay (El legacy vino para queda...20191116 DevFest 2019 The Legacy Code came to stay (El legacy vino para queda...
20191116 DevFest 2019 The Legacy Code came to stay (El legacy vino para queda...
 
Unethical JavaScript - Giorgio Natili - Codemotion Rome 2017
Unethical JavaScript - Giorgio Natili - Codemotion Rome 2017Unethical JavaScript - Giorgio Natili - Codemotion Rome 2017
Unethical JavaScript - Giorgio Natili - Codemotion Rome 2017
 
Oleksandr Valetskyy - DI vs. IoC
Oleksandr Valetskyy - DI vs. IoCOleksandr Valetskyy - DI vs. IoC
Oleksandr Valetskyy - DI vs. IoC
 
Eclipse Democamp Zurich
Eclipse Democamp ZurichEclipse Democamp Zurich
Eclipse Democamp Zurich
 
Making an Exception
Making an ExceptionMaking an Exception
Making an Exception
 
Object Oriented Concepts and Principles
Object Oriented Concepts and PrinciplesObject Oriented Concepts and Principles
Object Oriented Concepts and Principles
 
Extension methods, nulls, namespaces and precedence in c#
Extension methods, nulls, namespaces and precedence in c#Extension methods, nulls, namespaces and precedence in c#
Extension methods, nulls, namespaces and precedence in c#
 

More from Luigi De Russis

Assessing Virtual Assistant Capabilities with Italian Dysarthric Speech
Assessing Virtual Assistant Capabilities with Italian Dysarthric SpeechAssessing Virtual Assistant Capabilities with Italian Dysarthric Speech
Assessing Virtual Assistant Capabilities with Italian Dysarthric Speech
Luigi De Russis
 
Semantic Web: an Introduction
Semantic Web: an IntroductionSemantic Web: an Introduction
Semantic Web: an Introduction
Luigi De Russis
 
Programming the Semantic Web
Programming the Semantic WebProgramming the Semantic Web
Programming the Semantic Web
Luigi De Russis
 
Semantic Web - Ontology 101
Semantic Web - Ontology 101Semantic Web - Ontology 101
Semantic Web - Ontology 101
Luigi De Russis
 
AmI 2017 - Python intermediate
AmI 2017 - Python intermediateAmI 2017 - Python intermediate
AmI 2017 - Python intermediate
Luigi De Russis
 
AmI 2017 - Python basics
AmI 2017 - Python basicsAmI 2017 - Python basics
AmI 2017 - Python basics
Luigi De Russis
 
AngularJS: an introduction
AngularJS: an introductionAngularJS: an introduction
AngularJS: an introduction
Luigi De Russis
 
AmI 2016 - Python basics
AmI 2016 - Python basicsAmI 2016 - Python basics
AmI 2016 - Python basics
Luigi De Russis
 
Introduction to OpenCV 3.x (with Java)
Introduction to OpenCV 3.x (with Java)Introduction to OpenCV 3.x (with Java)
Introduction to OpenCV 3.x (with Java)
Luigi De Russis
 
Ambient Intelligence: An Overview
Ambient Intelligence: An OverviewAmbient Intelligence: An Overview
Ambient Intelligence: An Overview
Luigi De Russis
 
Version Control with Git
Version Control with GitVersion Control with Git
Version Control with Git
Luigi De Russis
 
LAM 2015 - Social Networks Technologies
LAM 2015 - Social Networks TechnologiesLAM 2015 - Social Networks Technologies
LAM 2015 - Social Networks Technologies
Luigi De Russis
 
AmI 2015 - Python basics
AmI 2015 - Python basicsAmI 2015 - Python basics
AmI 2015 - Python basics
Luigi De Russis
 
PowerOnt: an ontology-based approach for power consumption estimation in Smar...
PowerOnt: an ontology-based approach for power consumption estimation in Smar...PowerOnt: an ontology-based approach for power consumption estimation in Smar...
PowerOnt: an ontology-based approach for power consumption estimation in Smar...
Luigi De Russis
 
Interacting with Smart Environments - Ph.D. Thesis Presentation
Interacting with Smart Environments - Ph.D. Thesis PresentationInteracting with Smart Environments - Ph.D. Thesis Presentation
Interacting with Smart Environments - Ph.D. Thesis Presentation
Luigi De Russis
 
Semantic Web: an introduction
Semantic Web: an introductionSemantic Web: an introduction
Semantic Web: an introduction
Luigi De Russis
 
Introduction to OpenCV (with Java)
Introduction to OpenCV (with Java)Introduction to OpenCV (with Java)
Introduction to OpenCV (with Java)
Luigi De Russis
 
Living in Smart Environments - 3rd year PhD Report
Living in Smart Environments - 3rd year PhD ReportLiving in Smart Environments - 3rd year PhD Report
Living in Smart Environments - 3rd year PhD Report
Luigi De Russis
 
Semantic Web: an introduction
Semantic Web: an introductionSemantic Web: an introduction
Semantic Web: an introduction
Luigi De Russis
 
Social Network Technologies
Social Network TechnologiesSocial Network Technologies
Social Network Technologies
Luigi De Russis
 

More from Luigi De Russis (20)

Assessing Virtual Assistant Capabilities with Italian Dysarthric Speech
Assessing Virtual Assistant Capabilities with Italian Dysarthric SpeechAssessing Virtual Assistant Capabilities with Italian Dysarthric Speech
Assessing Virtual Assistant Capabilities with Italian Dysarthric Speech
 
Semantic Web: an Introduction
Semantic Web: an IntroductionSemantic Web: an Introduction
Semantic Web: an Introduction
 
Programming the Semantic Web
Programming the Semantic WebProgramming the Semantic Web
Programming the Semantic Web
 
Semantic Web - Ontology 101
Semantic Web - Ontology 101Semantic Web - Ontology 101
Semantic Web - Ontology 101
 
AmI 2017 - Python intermediate
AmI 2017 - Python intermediateAmI 2017 - Python intermediate
AmI 2017 - Python intermediate
 
AmI 2017 - Python basics
AmI 2017 - Python basicsAmI 2017 - Python basics
AmI 2017 - Python basics
 
AngularJS: an introduction
AngularJS: an introductionAngularJS: an introduction
AngularJS: an introduction
 
AmI 2016 - Python basics
AmI 2016 - Python basicsAmI 2016 - Python basics
AmI 2016 - Python basics
 
Introduction to OpenCV 3.x (with Java)
Introduction to OpenCV 3.x (with Java)Introduction to OpenCV 3.x (with Java)
Introduction to OpenCV 3.x (with Java)
 
Ambient Intelligence: An Overview
Ambient Intelligence: An OverviewAmbient Intelligence: An Overview
Ambient Intelligence: An Overview
 
Version Control with Git
Version Control with GitVersion Control with Git
Version Control with Git
 
LAM 2015 - Social Networks Technologies
LAM 2015 - Social Networks TechnologiesLAM 2015 - Social Networks Technologies
LAM 2015 - Social Networks Technologies
 
AmI 2015 - Python basics
AmI 2015 - Python basicsAmI 2015 - Python basics
AmI 2015 - Python basics
 
PowerOnt: an ontology-based approach for power consumption estimation in Smar...
PowerOnt: an ontology-based approach for power consumption estimation in Smar...PowerOnt: an ontology-based approach for power consumption estimation in Smar...
PowerOnt: an ontology-based approach for power consumption estimation in Smar...
 
Interacting with Smart Environments - Ph.D. Thesis Presentation
Interacting with Smart Environments - Ph.D. Thesis PresentationInteracting with Smart Environments - Ph.D. Thesis Presentation
Interacting with Smart Environments - Ph.D. Thesis Presentation
 
Semantic Web: an introduction
Semantic Web: an introductionSemantic Web: an introduction
Semantic Web: an introduction
 
Introduction to OpenCV (with Java)
Introduction to OpenCV (with Java)Introduction to OpenCV (with Java)
Introduction to OpenCV (with Java)
 
Living in Smart Environments - 3rd year PhD Report
Living in Smart Environments - 3rd year PhD ReportLiving in Smart Environments - 3rd year PhD Report
Living in Smart Environments - 3rd year PhD Report
 
Semantic Web: an introduction
Semantic Web: an introductionSemantic Web: an introduction
Semantic Web: an introduction
 
Social Network Technologies
Social Network TechnologiesSocial Network Technologies
Social Network Technologies
 

Recently uploaded

A Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in EducationA Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in Education
Peter Windle
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
Mohd Adib Abd Muin, Senior Lecturer at Universiti Utara Malaysia
 
Best Digital Marketing Institute In NOIDA
Best Digital Marketing Institute In NOIDABest Digital Marketing Institute In NOIDA
Best Digital Marketing Institute In NOIDA
deeptiverma2406
 
Model Attribute Check Company Auto Property
Model Attribute  Check Company Auto PropertyModel Attribute  Check Company Auto Property
Model Attribute Check Company Auto Property
Celine George
 
"Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe..."Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe...
SACHIN R KONDAGURI
 
Chapter 4 - Islamic Financial Institutions in Malaysia.pptx
Chapter 4 - Islamic Financial Institutions in Malaysia.pptxChapter 4 - Islamic Financial Institutions in Malaysia.pptx
Chapter 4 - Islamic Financial Institutions in Malaysia.pptx
Mohd Adib Abd Muin, Senior Lecturer at Universiti Utara Malaysia
 
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Thiyagu K
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
Jisc
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
EverAndrsGuerraGuerr
 
A Survey of Techniques for Maximizing LLM Performance.pptx
A Survey of Techniques for Maximizing LLM Performance.pptxA Survey of Techniques for Maximizing LLM Performance.pptx
A Survey of Techniques for Maximizing LLM Performance.pptx
thanhdowork
 
Supporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptxSupporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptx
Jisc
 
Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
DeeptiGupta154
 
The approach at University of Liverpool.pptx
The approach at University of Liverpool.pptxThe approach at University of Liverpool.pptx
The approach at University of Liverpool.pptx
Jisc
 
Pride Month Slides 2024 David Douglas School District
Pride Month Slides 2024 David Douglas School DistrictPride Month Slides 2024 David Douglas School District
Pride Month Slides 2024 David Douglas School District
David Douglas School District
 
Synthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptxSynthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptx
Pavel ( NSTU)
 
The Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collectionThe Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collection
Israel Genealogy Research Association
 
Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.
Ashokrao Mane college of Pharmacy Peth-Vadgaon
 
Advantages and Disadvantages of CMS from an SEO Perspective
Advantages and Disadvantages of CMS from an SEO PerspectiveAdvantages and Disadvantages of CMS from an SEO Perspective
Advantages and Disadvantages of CMS from an SEO Perspective
Krisztián Száraz
 
S1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptxS1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptx
tarandeep35
 
Digital Artifact 2 - Investigating Pavilion Designs
Digital Artifact 2 - Investigating Pavilion DesignsDigital Artifact 2 - Investigating Pavilion Designs
Digital Artifact 2 - Investigating Pavilion Designs
chanes7
 

Recently uploaded (20)

A Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in EducationA Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in Education
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
 
Best Digital Marketing Institute In NOIDA
Best Digital Marketing Institute In NOIDABest Digital Marketing Institute In NOIDA
Best Digital Marketing Institute In NOIDA
 
Model Attribute Check Company Auto Property
Model Attribute  Check Company Auto PropertyModel Attribute  Check Company Auto Property
Model Attribute Check Company Auto Property
 
"Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe..."Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe...
 
Chapter 4 - Islamic Financial Institutions in Malaysia.pptx
Chapter 4 - Islamic Financial Institutions in Malaysia.pptxChapter 4 - Islamic Financial Institutions in Malaysia.pptx
Chapter 4 - Islamic Financial Institutions in Malaysia.pptx
 
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
 
A Survey of Techniques for Maximizing LLM Performance.pptx
A Survey of Techniques for Maximizing LLM Performance.pptxA Survey of Techniques for Maximizing LLM Performance.pptx
A Survey of Techniques for Maximizing LLM Performance.pptx
 
Supporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptxSupporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptx
 
Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
 
The approach at University of Liverpool.pptx
The approach at University of Liverpool.pptxThe approach at University of Liverpool.pptx
The approach at University of Liverpool.pptx
 
Pride Month Slides 2024 David Douglas School District
Pride Month Slides 2024 David Douglas School DistrictPride Month Slides 2024 David Douglas School District
Pride Month Slides 2024 David Douglas School District
 
Synthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptxSynthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptx
 
The Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collectionThe Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collection
 
Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.
 
Advantages and Disadvantages of CMS from an SEO Perspective
Advantages and Disadvantages of CMS from an SEO PerspectiveAdvantages and Disadvantages of CMS from an SEO Perspective
Advantages and Disadvantages of CMS from an SEO Perspective
 
S1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptxS1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptx
 
Digital Artifact 2 - Investigating Pavilion Designs
Digital Artifact 2 - Investigating Pavilion DesignsDigital Artifact 2 - Investigating Pavilion Designs
Digital Artifact 2 - Investigating Pavilion Designs
 

Clean Code

  • 1. Best practice Luigi De Russis Clean Code
  • 2. 2 Measuring code quality Clean Code 07/03/2013
  • 3. The only valid measurement: WTFs/min 3 Good code Bad code WTF, WTF WTF this is shit! CODE CODE REVIEW WTF REVIEW WTF WTF Dude, WTF WTF Clean Code 07/03/2013
  • 4. 4 Goals Clean Code 07/03/2013
  • 5. Code MUST be… 5 Readable Maintainable Extendable Testable Clean Code 07/03/2013
  • 6. 6 How? Clean Code 07/03/2013
  • 7. 7 Clean Code 07/03/2013
  • 8. 8 Meaningful names Clean Code 07/03/2013
  • 9. An example… 9 public List<int[]> getThem() { List<int[]> list = new ArrayList<int[]>(); for (int[] x : theList) if (x[0] == 4) list.add(x); return list; } What does this code do? Clean Code 07/03/2013
  • 10. An example… 10 public List<int[]> getFlaggedCells() { List<int[]> flaggedCells = new ArrayList<int[]>(); for (int[] cell : gameBoard) if (cell[STATUS_VALUE] == FLAGGED) flaggedCell.add(cell); return flaggedCells; } Better? Clean Code 07/03/2013
  • 11. An example… 11 public List<Cell> getFlaggedCells() { List<Cell> flaggedCells = new ArrayList<Cell>(); for (Cell cell : gameBoard) if (cell.isFlagged()) flaggedCell.add(cell); return flaggedCells; } What about this? Clean Code 07/03/2013
  • 12. What we have done 12 Used intention flaggedCells rather revealing names than list Replaced magic cell[STATUS_VALUE] numbers with constants rather than x[0] Created an appropriate Cell cell rather than abstract data type int[] cell Clean Code 07/03/2013
  • 13. Another example… 13 class DtaRcrd102 { private Date genymdhms; private Date modymdhms; private final String pszqint = “102”; /* ... */ } Use pronounceable and searchable names (please!) Clean Code 07/03/2013
  • 14. Another example… 14 class Customer { private Date generationTimeStamp; private Date modificationTimeStamp; private final String recordId = “102”; /* ... */ } Better? Clean Code 07/03/2013
  • 15. 15 Functions Clean Code 07/03/2013
  • 16. Functions 16 Small Do One Thing Clean Code 07/03/2013
  • 17. Do One Thing 17 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? Clean Code 07/03/2013
  • 18. Do One Thing 18 public bool isEdible() { return isFresh() && isApproved() && isInspected(); } Now the function is doing one thing! A change in the specification turns into a single change in the code. Clean Code 07/03/2013
  • 19. Functions 19 Handle errors (and use exceptions) Don’t Repeat Yourself (avoid copy-and-paste code) Clean Code 07/03/2013
  • 20. 20 Comments Clean Code 07/03/2013
  • 21. Explain yourself in the code 21 Which one is cleaner? //check to see if the employee is eligible for full benefits if((employee.flags & HOURLY_FLAG) && (employee.age > 65)) if(employee.isEligibleForFullBenefits()) Clean Code 07/03/2013
  • 22. Explain yourself in the code 22 Which one is cleaner? //check to see if the employee is eligible for full benefits if((employee.flags & HOURLY_FLAG) && (employee.age > 65)) if(employee.isEligibleForFullBenefits()) Clean Code 07/03/2013
  • 23. API Documentation YES Explanation of intent Clarification Warning of consequences Orphan comments NO Obsolete comments Noise comments Code commented-out 23 Clean Code 07/03/2013
  • 24. 24 Formatting Clean Code 07/03/2013
  • 25. Formatting 25 Communication is the purpose of formatting Vertical openness between concepts Each blank line is a visual cue that identifies a new and separate concept Clean Code 07/03/2013
  • 26. Breaking Indentation 26 public class CommentWidget extends TextWidget { public static final String REGEXP = “^#[rn]*(?:(?:rn)|n|r)?”; public CommentWidget(String text) { super(text); } public String render() throws Exception { return “”; } } Eh? Clean Code 07/03/2013
  • 27. Breaking Indentation 27 public class CommentWidget extends TextWidget { public static final String REGEXP = “^#[rn]*(?:(?:rn)|n|r)?”; public CommentWidget(String text) { Better? super(text); } public String render() throws Exception { return “”; } } Clean Code 07/03/2013
  • 28. 28 Conventions Clean Code 07/03/2013
  • 29. Conventions 29 Conventions enable common understanding Stick to the language-specific conventions Respect team-level conventions Still complying with the language-specific conventions… Clean Code 07/03/2013
  • 30. References 30  Robert C. Martin Series, “Clean Code - A Handbook of Agile Software Craftsmanship”, Prentice Hall  Geek and Poke, http://geekandpoke.typepad.com/  OSNews Comics, http://www.osnews.com/comics Clean Code 07/03/2013
  • 31. License 31  This work is licensed under the Creative Commons “Attribution- NonCommercial-ShareAlike Unported (CC BY-NC-SA 3,0)” License.  You are free:  to Share - to copy, distribute and transmit the work  to Remix - to adapt the work  Under the following conditions:  Attribution - You must attribute the work in the manner specified by the author or licensor (but not in any way that suggests that they endorse you or your use of the work).  Noncommercial - You may not use this work for commercial purposes.  Share Alike - If you alter, transform, or build upon this work, you may distribute the resulting work only under the same or similar license to this one.  To view a copy of this license, visit http://creativecommons.org/licenses/by-nc-sa/3.0/ Clean Code 07/03/2013