SlideShare ist ein Scribd-Unternehmen logo
1 von 31
Downloaden Sie, um offline zu lesen
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

Weitere ähnliche Inhalte

Was ist angesagt?

Clean code - DSC DYPCOE
Clean code - DSC DYPCOEClean code - DSC DYPCOE
Clean code - DSC DYPCOEPatil Shreyas
 
Clean code: meaningful Name
Clean code: meaningful NameClean code: meaningful Name
Clean code: meaningful Namenahid035
 
The Art of Clean code
The Art of Clean codeThe Art of Clean code
The Art of Clean codeVictor Rentea
 
Javascript Clean Code
Javascript Clean CodeJavascript Clean Code
Javascript Clean CodePetra Barus
 
Clean code presentation
Clean code presentationClean code presentation
Clean code presentationBhavin Gandhi
 
Software Craftsmanship @Code Camp Festival 2022.pdf
Software Craftsmanship @Code Camp Festival 2022.pdfSoftware Craftsmanship @Code Camp Festival 2022.pdf
Software Craftsmanship @Code Camp Festival 2022.pdfVictor Rentea
 
Clean Code summary
Clean Code summaryClean Code summary
Clean Code summaryJan de Vries
 
How to write good comments
How to write good commentsHow to write good comments
How to write good commentsPeter Hilton
 
The tests are trying to tell you something@VoxxedBucharest.pptx
The tests are trying to tell you something@VoxxedBucharest.pptxThe tests are trying to tell you something@VoxxedBucharest.pptx
The tests are trying to tell you something@VoxxedBucharest.pptxVictor Rentea
 
Unit Testing like a Pro - The Circle of Purity
Unit Testing like a Pro - The Circle of PurityUnit Testing like a Pro - The Circle of Purity
Unit Testing like a Pro - The Circle of PurityVictor Rentea
 
The Art of Unit Testing - Towards a Testable Design
The Art of Unit Testing - Towards a Testable DesignThe Art of Unit Testing - Towards a Testable Design
The Art of Unit Testing - Towards a Testable DesignVictor Rentea
 
Clean Code I - Best Practices
Clean Code I - Best PracticesClean Code I - Best Practices
Clean Code I - Best PracticesTheo Jungeblut
 

Was ist angesagt? (20)

Clean code
Clean code Clean code
Clean code
 
Clean code - DSC DYPCOE
Clean code - DSC DYPCOEClean code - DSC DYPCOE
Clean code - DSC DYPCOE
 
Clean code: meaningful Name
Clean code: meaningful NameClean code: meaningful Name
Clean code: meaningful Name
 
Clean code
Clean codeClean code
Clean code
 
The Art of Clean code
The Art of Clean codeThe Art of Clean code
The Art of Clean code
 
Clean code
Clean codeClean code
Clean code
 
Clean Code
Clean CodeClean Code
Clean Code
 
Javascript Clean Code
Javascript Clean CodeJavascript Clean Code
Javascript Clean Code
 
Clean code presentation
Clean code presentationClean code presentation
Clean code presentation
 
Clean code slide
Clean code slideClean code slide
Clean code slide
 
Software Craftsmanship @Code Camp Festival 2022.pdf
Software Craftsmanship @Code Camp Festival 2022.pdfSoftware Craftsmanship @Code Camp Festival 2022.pdf
Software Craftsmanship @Code Camp Festival 2022.pdf
 
Clean Code summary
Clean Code summaryClean Code summary
Clean Code summary
 
Clean coding-practices
Clean coding-practicesClean coding-practices
Clean coding-practices
 
How to write good comments
How to write good commentsHow to write good comments
How to write good comments
 
The tests are trying to tell you something@VoxxedBucharest.pptx
The tests are trying to tell you something@VoxxedBucharest.pptxThe tests are trying to tell you something@VoxxedBucharest.pptx
The tests are trying to tell you something@VoxxedBucharest.pptx
 
Chapter17 of clean code
Chapter17 of clean codeChapter17 of clean code
Chapter17 of clean code
 
Unit Testing like a Pro - The Circle of Purity
Unit Testing like a Pro - The Circle of PurityUnit Testing like a Pro - The Circle of Purity
Unit Testing like a Pro - The Circle of Purity
 
The Art of Unit Testing - Towards a Testable Design
The Art of Unit Testing - Towards a Testable DesignThe Art of Unit Testing - Towards a Testable Design
The Art of Unit Testing - Towards a Testable Design
 
Clean Code I - Best Practices
Clean Code I - Best PracticesClean Code I - Best Practices
Clean Code I - Best Practices
 
Clean code
Clean codeClean code
Clean code
 

Ähnlich wie 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 bites
Clean code bitesClean code bites
Clean code bitesRoy Nitert
 
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 & refactoringEyob 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 CoumansAMD Developer Central
 
Presentacion clean code
Presentacion clean codePresentacion clean code
Presentacion clean codeIBM
 
Javascript Deofuscation A manual Approach
Javascript Deofuscation A manual ApproachJavascript Deofuscation A manual Approach
Javascript Deofuscation A manual ApproachGregory Hanis
 
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 2017Codemotion
 
Oleksandr Valetskyy - DI vs. IoC
Oleksandr Valetskyy - DI vs. IoCOleksandr Valetskyy - DI vs. IoC
Oleksandr Valetskyy - DI vs. IoCOleksandr Valetskyy
 
Eclipse Democamp Zurich
Eclipse Democamp ZurichEclipse Democamp Zurich
Eclipse Democamp ZurichMarcel Bruch
 
Object Oriented Concepts and Principles
Object Oriented Concepts and PrinciplesObject Oriented Concepts and Principles
Object Oriented Concepts and Principlesdeonpmeyer
 
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
 

Ähnlich wie 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#
 

Mehr von 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 SpeechLuigi De Russis
 
Semantic Web: an Introduction
Semantic Web: an IntroductionSemantic Web: an Introduction
Semantic Web: an IntroductionLuigi De Russis
 
Programming the Semantic Web
Programming the Semantic WebProgramming the Semantic Web
Programming the Semantic WebLuigi De Russis
 
Semantic Web - Ontology 101
Semantic Web - Ontology 101Semantic Web - Ontology 101
Semantic Web - Ontology 101Luigi De Russis
 
AmI 2017 - Python intermediate
AmI 2017 - Python intermediateAmI 2017 - Python intermediate
AmI 2017 - Python intermediateLuigi De Russis
 
AmI 2017 - Python basics
AmI 2017 - Python basicsAmI 2017 - Python basics
AmI 2017 - Python basicsLuigi De Russis
 
AngularJS: an introduction
AngularJS: an introductionAngularJS: an introduction
AngularJS: an introductionLuigi De Russis
 
AmI 2016 - Python basics
AmI 2016 - Python basicsAmI 2016 - Python basics
AmI 2016 - Python basicsLuigi 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 OverviewLuigi De Russis
 
Version Control with Git
Version Control with GitVersion Control with Git
Version Control with GitLuigi De Russis
 
LAM 2015 - Social Networks Technologies
LAM 2015 - Social Networks TechnologiesLAM 2015 - Social Networks Technologies
LAM 2015 - Social Networks TechnologiesLuigi De Russis
 
AmI 2015 - Python basics
AmI 2015 - Python basicsAmI 2015 - Python basics
AmI 2015 - Python basicsLuigi 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 PresentationLuigi De Russis
 
Semantic Web: an introduction
Semantic Web: an introductionSemantic Web: an introduction
Semantic Web: an introductionLuigi 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 ReportLuigi De Russis
 
Semantic Web: an introduction
Semantic Web: an introductionSemantic Web: an introduction
Semantic Web: an introductionLuigi De Russis
 
Social Network Technologies
Social Network TechnologiesSocial Network Technologies
Social Network TechnologiesLuigi De Russis
 

Mehr von 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
 

Kürzlich hochgeladen

A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxRoyAbrique
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
MENTAL STATUS EXAMINATION format.docx
MENTAL     STATUS EXAMINATION format.docxMENTAL     STATUS EXAMINATION format.docx
MENTAL STATUS EXAMINATION format.docxPoojaSen20
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application ) Sakshi Ghasle
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAssociation for Project Management
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 
PSYCHIATRIC History collection FORMAT.pptx
PSYCHIATRIC   History collection FORMAT.pptxPSYCHIATRIC   History collection FORMAT.pptx
PSYCHIATRIC History collection FORMAT.pptxPoojaSen20
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppCeline George
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Celine George
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesFatimaKhan178732
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 

Kürzlich hochgeladen (20)

A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
MENTAL STATUS EXAMINATION format.docx
MENTAL     STATUS EXAMINATION format.docxMENTAL     STATUS EXAMINATION format.docx
MENTAL STATUS EXAMINATION format.docx
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application )
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
PSYCHIATRIC History collection FORMAT.pptx
PSYCHIATRIC   History collection FORMAT.pptxPSYCHIATRIC   History collection FORMAT.pptx
PSYCHIATRIC History collection FORMAT.pptx
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website App
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and Actinides
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 

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