SlideShare une entreprise Scribd logo
1  sur  38
CLEAN CODE
The lecture is based on
 “Clean Code”, A Handbook of Agile Software Craftsmanship by
  Robert C. Martin
 Software Craftsmanship in Israel group meetings.




                                               Coby Sternlicht
                                                    Feb 2012
Agenda

1   • Why?

2   • Guidelines

3   • Good Methods

4   • Design Principles

5   • Code Smells
Why Clean Code?
Why clean code
•   Does what my customer needs
•   Is error free
•   Performs well
•   Is easy to change
•   Is as simple as possible
•   Maintainable
•   The psychological element

                      4
Clean Code definition




                5
Guidelines
• You are the author, writing for readers
• Keep clean over time
• “Leave the campground cleaner than you
  found it”




                                            6
How to write a

Good Method
The newspaper paradigm

Title

Summary


Details

http://www.heraldsun.com.au/news/breaking-news/apple-seeks-us-injunction-against-samsungs-galaxy-nexus/story-e6frf7jx-1226269183958
A “long” method - HtmlUtil.java /FitNesse
• Do you understand the function after three
  minutes of study?
  – Probably not




                        9
A “long” method - refactored
• What did I do?
  – method extractions
  – some renaming
  – A little restructuring


• Can you understand what the code does?



                             10
Writing a good method


    Principles
1. Smaller than a screenful
• Small, Small, Small
• Minimum lines of code
• Maximal nesting level of 2




                      12
2. Do one thing - do it well, do it only.
• The original code is:
  –   Creating buffers
  –   Fetching pages
  –   Searching for inherited pages
  –   Rendering paths
  –   Appending arcane strings
  –   Generating HTML…
• The re-factored code is:
  – including setups and teardowns into test pages



                              13
3. Choose Good Names
• Use intention-revealing, pronounceable, searchable
  names
   – bad: int d; // elapsed time in days
   – Good: int elapsedTimeInDays;
• Don’t use Hungarian Notation
   – // name not changed when type changed!
   – PhoneNumber   stPhone;
• Don’t be afraid to make a name long
• Don’t be afraid to spend time choosing a name
• Remember, if you can’t choose a descriptive name
   – Your function is probably too big
   – And does more than ONE THING
                                   14
4. Minimize the use of arguments
• Which is easier to understand?
   – includeSetupPage()
   – includeSetupPageInto(newPageContent)
• Arguments are hard
   – They take a lot of conceptual power.
   – They are at a different level of abstraction than the
     function name
   – Output arguments are difficult to understand
   – They are even harder from a testing point of view


                               15
5. Avoid flag arguments
• Passing a boolean into a function is bad practice
   – It complicates the signature of the method
   – This function does more than one thing
• Example:
   – render(true) is just plain confusing to a poor reader
       • Your IDE tells you that it is render(boolean isSuite)
       • Helps a little, but not that much
   – We should have split the function into two:
       • renderForSuite() and renderForSingleTest()




                                      16
6. No more than 3 arguments

• Zero arguments is ideal (niladic)
• Next comes one (monadic)
• Followed closely by two (dyadic)
• Three arguments (triadic) should be avoided where
  possible
• More than three (polyadic) requires very special
  justification



                         17
Dyadic functions
• A function with two arguments is harder to understand

• Example: Frequency.cs (GetNextDate)
• As a general rule, Dyadic aren’t that bad and sometimes
  necessary:
   – Point centerPosition = new Point(x, y);




                              18
Three arguments (Triads)
• Significantly harder to understand
   – Argument ordering
   – Pausing when reading
   – Ignoring unimportant details
• Example - assertEquals:
   – assertEquals(message, expected, actual)
   – Is first argument message or expected?
   – You do a double-take and then learn to ignore the message




                                    19
7. Side-effects are lies
• A function also does other hidden things
   – to the variables of it’s own class
   – to the parameters passed into the function
   – to system globals
• Creates temporal couplings and order dependencies
• If you must have a temporal coupling, you should make it
  clear in the name of the function
• Example:
   – checkPasswordAndInitializeSession
   – Obviously this does more than one thing




                                  20
7. Side-effects are lies
• Command and Query separation
• Example:
  public boolean set(String attribute, String value);

• This leads to:
     if (set("username", “unclebob"))...
• What does that mean?
   – Is it asking whether the “username” attribute was
       • previously set to “unclebob”?
       • successfully set to “unclebob”?
   – Is “set” a verb or an adjective


                                       21
7. Side-effects are lies – continued
• Renaming to checkIfAttributeExistsAndSet
   – helps a bit
• The real solution is to separate the command from the query

   if (attributeExists("username"))
   {
     setAttribute("username", "unclebob");
     ...
   }



                              22
8. Use exceptions and not error codes
• Error codes are a violation of command query
  separation
• Create lots of if statements
  – if (deletePage(page) == E_OK)
• Deeply nested structures
• The caller must deal with the error
  immediately


                       23
8. Use exceptions – Bad example
if (deletePage(page) == E_OK)
 {
   if (registry.deleteReference(page.name) == E_OK) {
     if (configKeys.deleteKey(page.name.makeKey()) == E_OK){
       logger.log("page deleted");
     } else {
       logger.log("configKey not deleted");
     }
   } else {
     logger.log("deleteReference from registry failed");
   }
} else {
   logger.log("delete failed");
   return E_ERROR;
}



                              24
8. Use exceptions – Good example
try {
  deletePage(page);
  registry.deleteReference(page.name);
  configKeys.deleteKey(page.name.makeKey());
}
catch (Exception e) {
  logger.log(e.getMessage());
}


• Happy-path is easy to read
• Error processing code is separated


                           25
9. Don’t comment bad code—rewrite it

•   Failure to express ourselves in code
•   Not maintained
•   Don’t comment messy code, clean it!
•   Don’t comment-out code – DELETE IT
•   Example:
    // Check to see if the employee is eligible for full benefits
    if ((employee.flags & HOURLY_FLAG) &&
        (employee.age > 65))


• Instead - descriptive Method Name

     if (employee.isEligibleForFullBenefits())

                                 26
THREE SIMPLE DESIGN PRINCIPLES
1. DRY – Don’t repeat yourself
• Clone and modify programming
  – Creates Rogue Tile: bugs show up again and again
• When writing “DRY”:
  – Modification of any single element of a system does
    not change other logically-unrelated elements
  – All elements that are logically related, change
    predictably and uniformly




                            28
2. YAGNI - You aint gonna need it
• Maybe in the future…
• Disadvantages:
   – The time spent
   – Must be debugged, documented, and supported
   – May prevent implementing a necessary feature in the future due
     to constraints
   – Difficult to fully define when not needed
   – Code bloat
   – May not be known to programmers when they need it
   – Snowball effect – “Featuritis Crawleritis”
• Must be balanced: upcoming vital features, team
  expectations, part-time expert assistance, and logical
  completeness
                                 29
3. KISS - keep it short and simple
• Simplicity should be a key goal in design
• Unnecessary complexity should be avoided




                         30
CODE SMELLS
Code smells
• A symptom in a program that possibly
  indicates a deeper problem




                      32
Code smells - Comments
• Comments:
  –   Obsolete
  –   Redundant
  –   Poorly written
  –   Commented out code




                           33
Code smells - Methods
• Methods:
  –   Long
  –   Too many arguments
  –   Flags
  –   Dead Code




                           34
Code smells - DRY
• Code Duplication




                     35
Code smells - Obscured Intent
• Obscured Intent
• Code should be as expressive as possible
 public int m_otCalc()
  {
      return iThsWkd * iThsRte +
      (int) Math.round(0.5 * iThsRte *
      Math.max(0, iThsWkd – 400));
  }


                       36
Resources




                 Robert C.Martin



• Software Craftsmanship in Israel – a LinkedIn
  group.
Questions?




             38

Contenu connexe

Tendances

How To Become A Good C# Programmer
How To Become A Good C# ProgrammerHow To Become A Good C# Programmer
How To Become A Good C# ProgrammerLearnItFirst.com
 
YAGNI Principle and Clean Code
YAGNI Principle and Clean CodeYAGNI Principle and Clean Code
YAGNI Principle and Clean CodeLuan Reffatti
 
Clean code - Getting your R&D on board
Clean code - Getting your R&D on boardClean code - Getting your R&D on board
Clean code - Getting your R&D on boardRuth Sperer
 
Coding Standard And Code Review
Coding Standard And Code ReviewCoding Standard And Code Review
Coding Standard And Code ReviewMilan Vukoje
 
Stop wasting-time-by-applying-clean-code-principles
Stop wasting-time-by-applying-clean-code-principlesStop wasting-time-by-applying-clean-code-principles
Stop wasting-time-by-applying-clean-code-principlesEdorian
 
Technical screening .Net Developer
Technical screening  .Net DeveloperTechnical screening  .Net Developer
Technical screening .Net DeveloperTom Henricksen
 
Common design patterns in php
Common design patterns in phpCommon design patterns in php
Common design patterns in phpDavid Stockton
 
Training methdology testers to developers
Training methdology   testers to developersTraining methdology   testers to developers
Training methdology testers to developersGurumurthy Ramamurthy
 
Best Practices of Software Development
Best Practices of Software DevelopmentBest Practices of Software Development
Best Practices of Software DevelopmentFolio3 Software
 
Software development best practices & coding guidelines
Software development best practices & coding guidelinesSoftware development best practices & coding guidelines
Software development best practices & coding guidelinesAnkur Goyal
 
Coding standard and coding guideline
Coding standard and coding guidelineCoding standard and coding guideline
Coding standard and coding guidelineDhananjaysinh Jhala
 
Behavior Driven Development
Behavior Driven Development Behavior Driven Development
Behavior Driven Development Dhawal Joshi
 
Test Driven Development - For Girl Geeks Night Sydney
Test Driven Development - For Girl Geeks Night SydneyTest Driven Development - For Girl Geeks Night Sydney
Test Driven Development - For Girl Geeks Night SydneyJo Cranford
 
Writing clean code in C# and .NET
Writing clean code in C# and .NETWriting clean code in C# and .NET
Writing clean code in C# and .NETDror Helper
 

Tendances (20)

How To Become A Good C# Programmer
How To Become A Good C# ProgrammerHow To Become A Good C# Programmer
How To Become A Good C# Programmer
 
YAGNI Principle and Clean Code
YAGNI Principle and Clean CodeYAGNI Principle and Clean Code
YAGNI Principle and Clean Code
 
Clean code - Getting your R&D on board
Clean code - Getting your R&D on boardClean code - Getting your R&D on board
Clean code - Getting your R&D on board
 
Coding Standard And Code Review
Coding Standard And Code ReviewCoding Standard And Code Review
Coding Standard And Code Review
 
Design Without Types
Design Without TypesDesign Without Types
Design Without Types
 
Stop wasting-time-by-applying-clean-code-principles
Stop wasting-time-by-applying-clean-code-principlesStop wasting-time-by-applying-clean-code-principles
Stop wasting-time-by-applying-clean-code-principles
 
Technical screening .Net Developer
Technical screening  .Net DeveloperTechnical screening  .Net Developer
Technical screening .Net Developer
 
Common design patterns in php
Common design patterns in phpCommon design patterns in php
Common design patterns in php
 
Clean code
Clean codeClean code
Clean code
 
JetBrains MPS
JetBrains MPSJetBrains MPS
JetBrains MPS
 
Coding standard
Coding standardCoding standard
Coding standard
 
Code Review
Code ReviewCode Review
Code Review
 
Training methdology testers to developers
Training methdology   testers to developersTraining methdology   testers to developers
Training methdology testers to developers
 
Best Practices of Software Development
Best Practices of Software DevelopmentBest Practices of Software Development
Best Practices of Software Development
 
Software development best practices & coding guidelines
Software development best practices & coding guidelinesSoftware development best practices & coding guidelines
Software development best practices & coding guidelines
 
Java script ppt
Java script pptJava script ppt
Java script ppt
 
Coding standard and coding guideline
Coding standard and coding guidelineCoding standard and coding guideline
Coding standard and coding guideline
 
Behavior Driven Development
Behavior Driven Development Behavior Driven Development
Behavior Driven Development
 
Test Driven Development - For Girl Geeks Night Sydney
Test Driven Development - For Girl Geeks Night SydneyTest Driven Development - For Girl Geeks Night Sydney
Test Driven Development - For Girl Geeks Night Sydney
 
Writing clean code in C# and .NET
Writing clean code in C# and .NETWriting clean code in C# and .NET
Writing clean code in C# and .NET
 

En vedette

Scub Foundation, usine logicielle Java libre
Scub Foundation, usine logicielle Java libreScub Foundation, usine logicielle Java libre
Scub Foundation, usine logicielle Java libreStéphane Traumat
 
Clean Coders Hate What Happens To Your Code When You Use These Enterprise Pro...
Clean Coders Hate What Happens To Your Code When You Use These Enterprise Pro...Clean Coders Hate What Happens To Your Code When You Use These Enterprise Pro...
Clean Coders Hate What Happens To Your Code When You Use These Enterprise Pro...Kevlin Henney
 
Seven Ineffective Coding Habits of Many Programmers
Seven Ineffective Coding Habits of Many ProgrammersSeven Ineffective Coding Habits of Many Programmers
Seven Ineffective Coding Habits of Many ProgrammersKevlin Henney
 

En vedette (7)

Clean Code
Clean CodeClean Code
Clean Code
 
Scub Foundation, usine logicielle Java libre
Scub Foundation, usine logicielle Java libreScub Foundation, usine logicielle Java libre
Scub Foundation, usine logicielle Java libre
 
Clean architectures
Clean architecturesClean architectures
Clean architectures
 
Clean code
Clean codeClean code
Clean code
 
Clean Coders Hate What Happens To Your Code When You Use These Enterprise Pro...
Clean Coders Hate What Happens To Your Code When You Use These Enterprise Pro...Clean Coders Hate What Happens To Your Code When You Use These Enterprise Pro...
Clean Coders Hate What Happens To Your Code When You Use These Enterprise Pro...
 
Seven Ineffective Coding Habits of Many Programmers
Seven Ineffective Coding Habits of Many ProgrammersSeven Ineffective Coding Habits of Many Programmers
Seven Ineffective Coding Habits of Many Programmers
 
Clean code
Clean codeClean code
Clean code
 

Similaire à Clean code, Feb 2012

Dev buchan 30 proven tips
Dev buchan 30 proven tipsDev buchan 30 proven tips
Dev buchan 30 proven tipsBill Buchan
 
Code reviews
Code reviewsCode reviews
Code reviewsRoger Xia
 
How I Learned to Stop Worrying and Love Legacy Code.....
How I Learned to Stop Worrying and Love Legacy Code.....How I Learned to Stop Worrying and Love Legacy Code.....
How I Learned to Stop Worrying and Love Legacy Code.....Mike Harris
 
Reading Notes : the practice of programming
Reading Notes : the practice of programmingReading Notes : the practice of programming
Reading Notes : the practice of programmingJuggernaut Liu
 
How I Learned to Stop Worrying and Love Legacy Code - Ox:Agile 2018
How I Learned to Stop Worrying and Love Legacy Code - Ox:Agile 2018How I Learned to Stop Worrying and Love Legacy Code - Ox:Agile 2018
How I Learned to Stop Worrying and Love Legacy Code - Ox:Agile 2018Mike Harris
 
Code reviews
Code reviewsCode reviews
Code reviewsRoger Xia
 
Writing Readable Code
Writing Readable CodeWriting Readable Code
Writing Readable Codeeddiehaber
 
Principled And Clean Coding
Principled And Clean CodingPrincipled And Clean Coding
Principled And Clean CodingMetin Ogurlu
 
Architecting a Large Software Project - Lessons Learned
Architecting a Large Software Project - Lessons LearnedArchitecting a Large Software Project - Lessons Learned
Architecting a Large Software Project - Lessons LearnedJoão Pedro Martins
 
Guide to Destroying Codebases The Demise of Clever Code
Guide to Destroying Codebases   The Demise of Clever CodeGuide to Destroying Codebases   The Demise of Clever Code
Guide to Destroying Codebases The Demise of Clever CodeGabor Varadi
 
ITARC15 Workshop - Architecting a Large Software Project - Lessons Learned
ITARC15 Workshop - Architecting a Large Software Project - Lessons LearnedITARC15 Workshop - Architecting a Large Software Project - Lessons Learned
ITARC15 Workshop - Architecting a Large Software Project - Lessons LearnedJoão Pedro Martins
 
TDD and Related Techniques for Non Developers (2012)
TDD and Related Techniques for Non Developers (2012)TDD and Related Techniques for Non Developers (2012)
TDD and Related Techniques for Non Developers (2012)Peter Kofler
 
Polyglot and Poly-paradigm Programming for Better Agility
Polyglot and Poly-paradigm Programming for Better AgilityPolyglot and Poly-paradigm Programming for Better Agility
Polyglot and Poly-paradigm Programming for Better Agilityelliando dias
 
Introduction to the intermediate Python - v1.1
Introduction to the intermediate Python - v1.1Introduction to the intermediate Python - v1.1
Introduction to the intermediate Python - v1.1Andrei KUCHARAVY
 
Clean code presentation
Clean code presentationClean code presentation
Clean code presentationBhavin Gandhi
 
How to Achieve Scale with MongoDB
How to Achieve Scale with MongoDBHow to Achieve Scale with MongoDB
How to Achieve Scale with MongoDBMongoDB
 

Similaire à Clean code, Feb 2012 (20)

Clean code
Clean codeClean code
Clean code
 
Dev buchan 30 proven tips
Dev buchan 30 proven tipsDev buchan 30 proven tips
Dev buchan 30 proven tips
 
Code reviews
Code reviewsCode reviews
Code reviews
 
How I Learned to Stop Worrying and Love Legacy Code.....
How I Learned to Stop Worrying and Love Legacy Code.....How I Learned to Stop Worrying and Love Legacy Code.....
How I Learned to Stop Worrying and Love Legacy Code.....
 
Reading Notes : the practice of programming
Reading Notes : the practice of programmingReading Notes : the practice of programming
Reading Notes : the practice of programming
 
How I Learned to Stop Worrying and Love Legacy Code - Ox:Agile 2018
How I Learned to Stop Worrying and Love Legacy Code - Ox:Agile 2018How I Learned to Stop Worrying and Love Legacy Code - Ox:Agile 2018
How I Learned to Stop Worrying and Love Legacy Code - Ox:Agile 2018
 
Coding Standards
Coding StandardsCoding Standards
Coding Standards
 
Code reviews
Code reviewsCode reviews
Code reviews
 
Writing Readable Code
Writing Readable CodeWriting Readable Code
Writing Readable Code
 
Code Review
Code ReviewCode Review
Code Review
 
Principled And Clean Coding
Principled And Clean CodingPrincipled And Clean Coding
Principled And Clean Coding
 
Architecting a Large Software Project - Lessons Learned
Architecting a Large Software Project - Lessons LearnedArchitecting a Large Software Project - Lessons Learned
Architecting a Large Software Project - Lessons Learned
 
Guide to Destroying Codebases The Demise of Clever Code
Guide to Destroying Codebases   The Demise of Clever CodeGuide to Destroying Codebases   The Demise of Clever Code
Guide to Destroying Codebases The Demise of Clever Code
 
ITARC15 Workshop - Architecting a Large Software Project - Lessons Learned
ITARC15 Workshop - Architecting a Large Software Project - Lessons LearnedITARC15 Workshop - Architecting a Large Software Project - Lessons Learned
ITARC15 Workshop - Architecting a Large Software Project - Lessons Learned
 
TDD and Related Techniques for Non Developers (2012)
TDD and Related Techniques for Non Developers (2012)TDD and Related Techniques for Non Developers (2012)
TDD and Related Techniques for Non Developers (2012)
 
Polyglot and Poly-paradigm Programming for Better Agility
Polyglot and Poly-paradigm Programming for Better AgilityPolyglot and Poly-paradigm Programming for Better Agility
Polyglot and Poly-paradigm Programming for Better Agility
 
CQRS recepies
CQRS recepiesCQRS recepies
CQRS recepies
 
Introduction to the intermediate Python - v1.1
Introduction to the intermediate Python - v1.1Introduction to the intermediate Python - v1.1
Introduction to the intermediate Python - v1.1
 
Clean code presentation
Clean code presentationClean code presentation
Clean code presentation
 
How to Achieve Scale with MongoDB
How to Achieve Scale with MongoDBHow to Achieve Scale with MongoDB
How to Achieve Scale with MongoDB
 

Dernier

Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DayH2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DaySri Ambati
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 

Dernier (20)

Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DayH2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 

Clean code, Feb 2012

  • 1. CLEAN CODE The lecture is based on  “Clean Code”, A Handbook of Agile Software Craftsmanship by Robert C. Martin  Software Craftsmanship in Israel group meetings. Coby Sternlicht Feb 2012
  • 2. Agenda 1 • Why? 2 • Guidelines 3 • Good Methods 4 • Design Principles 5 • Code Smells
  • 4. Why clean code • Does what my customer needs • Is error free • Performs well • Is easy to change • Is as simple as possible • Maintainable • The psychological element 4
  • 6. Guidelines • You are the author, writing for readers • Keep clean over time • “Leave the campground cleaner than you found it” 6
  • 7. How to write a Good Method
  • 9. A “long” method - HtmlUtil.java /FitNesse • Do you understand the function after three minutes of study? – Probably not 9
  • 10. A “long” method - refactored • What did I do? – method extractions – some renaming – A little restructuring • Can you understand what the code does? 10
  • 11. Writing a good method Principles
  • 12. 1. Smaller than a screenful • Small, Small, Small • Minimum lines of code • Maximal nesting level of 2 12
  • 13. 2. Do one thing - do it well, do it only. • The original code is: – Creating buffers – Fetching pages – Searching for inherited pages – Rendering paths – Appending arcane strings – Generating HTML… • The re-factored code is: – including setups and teardowns into test pages 13
  • 14. 3. Choose Good Names • Use intention-revealing, pronounceable, searchable names – bad: int d; // elapsed time in days – Good: int elapsedTimeInDays; • Don’t use Hungarian Notation – // name not changed when type changed! – PhoneNumber stPhone; • Don’t be afraid to make a name long • Don’t be afraid to spend time choosing a name • Remember, if you can’t choose a descriptive name – Your function is probably too big – And does more than ONE THING 14
  • 15. 4. Minimize the use of arguments • Which is easier to understand? – includeSetupPage() – includeSetupPageInto(newPageContent) • Arguments are hard – They take a lot of conceptual power. – They are at a different level of abstraction than the function name – Output arguments are difficult to understand – They are even harder from a testing point of view 15
  • 16. 5. Avoid flag arguments • Passing a boolean into a function is bad practice – It complicates the signature of the method – This function does more than one thing • Example: – render(true) is just plain confusing to a poor reader • Your IDE tells you that it is render(boolean isSuite) • Helps a little, but not that much – We should have split the function into two: • renderForSuite() and renderForSingleTest() 16
  • 17. 6. No more than 3 arguments • Zero arguments is ideal (niladic) • Next comes one (monadic) • Followed closely by two (dyadic) • Three arguments (triadic) should be avoided where possible • More than three (polyadic) requires very special justification 17
  • 18. Dyadic functions • A function with two arguments is harder to understand • Example: Frequency.cs (GetNextDate) • As a general rule, Dyadic aren’t that bad and sometimes necessary: – Point centerPosition = new Point(x, y); 18
  • 19. Three arguments (Triads) • Significantly harder to understand – Argument ordering – Pausing when reading – Ignoring unimportant details • Example - assertEquals: – assertEquals(message, expected, actual) – Is first argument message or expected? – You do a double-take and then learn to ignore the message 19
  • 20. 7. Side-effects are lies • A function also does other hidden things – to the variables of it’s own class – to the parameters passed into the function – to system globals • Creates temporal couplings and order dependencies • If you must have a temporal coupling, you should make it clear in the name of the function • Example: – checkPasswordAndInitializeSession – Obviously this does more than one thing 20
  • 21. 7. Side-effects are lies • Command and Query separation • Example: public boolean set(String attribute, String value); • This leads to: if (set("username", “unclebob"))... • What does that mean? – Is it asking whether the “username” attribute was • previously set to “unclebob”? • successfully set to “unclebob”? – Is “set” a verb or an adjective 21
  • 22. 7. Side-effects are lies – continued • Renaming to checkIfAttributeExistsAndSet – helps a bit • The real solution is to separate the command from the query if (attributeExists("username")) { setAttribute("username", "unclebob"); ... } 22
  • 23. 8. Use exceptions and not error codes • Error codes are a violation of command query separation • Create lots of if statements – if (deletePage(page) == E_OK) • Deeply nested structures • The caller must deal with the error immediately 23
  • 24. 8. Use exceptions – Bad example if (deletePage(page) == E_OK) { if (registry.deleteReference(page.name) == E_OK) { if (configKeys.deleteKey(page.name.makeKey()) == E_OK){ logger.log("page deleted"); } else { logger.log("configKey not deleted"); } } else { logger.log("deleteReference from registry failed"); } } else { logger.log("delete failed"); return E_ERROR; } 24
  • 25. 8. Use exceptions – Good example try { deletePage(page); registry.deleteReference(page.name); configKeys.deleteKey(page.name.makeKey()); } catch (Exception e) { logger.log(e.getMessage()); } • Happy-path is easy to read • Error processing code is separated 25
  • 26. 9. Don’t comment bad code—rewrite it • Failure to express ourselves in code • Not maintained • Don’t comment messy code, clean it! • Don’t comment-out code – DELETE IT • Example: // Check to see if the employee is eligible for full benefits if ((employee.flags & HOURLY_FLAG) && (employee.age > 65)) • Instead - descriptive Method Name if (employee.isEligibleForFullBenefits()) 26
  • 27. THREE SIMPLE DESIGN PRINCIPLES
  • 28. 1. DRY – Don’t repeat yourself • Clone and modify programming – Creates Rogue Tile: bugs show up again and again • When writing “DRY”: – Modification of any single element of a system does not change other logically-unrelated elements – All elements that are logically related, change predictably and uniformly 28
  • 29. 2. YAGNI - You aint gonna need it • Maybe in the future… • Disadvantages: – The time spent – Must be debugged, documented, and supported – May prevent implementing a necessary feature in the future due to constraints – Difficult to fully define when not needed – Code bloat – May not be known to programmers when they need it – Snowball effect – “Featuritis Crawleritis” • Must be balanced: upcoming vital features, team expectations, part-time expert assistance, and logical completeness 29
  • 30. 3. KISS - keep it short and simple • Simplicity should be a key goal in design • Unnecessary complexity should be avoided 30
  • 32. Code smells • A symptom in a program that possibly indicates a deeper problem 32
  • 33. Code smells - Comments • Comments: – Obsolete – Redundant – Poorly written – Commented out code 33
  • 34. Code smells - Methods • Methods: – Long – Too many arguments – Flags – Dead Code 34
  • 35. Code smells - DRY • Code Duplication 35
  • 36. Code smells - Obscured Intent • Obscured Intent • Code should be as expressive as possible public int m_otCalc() { return iThsWkd * iThsRte + (int) Math.round(0.5 * iThsRte * Math.max(0, iThsWkd – 400)); } 36
  • 37. Resources Robert C.Martin • Software Craftsmanship in Israel – a LinkedIn group.

Notes de l'éditeur

  1. There is no clear definitionA result of experience
  2. Functions should hardly ever be 20 lines long
  3. Don’t be afraid to spend time choosing a name - Modern IDEs make it easy to rename.