SlideShare a Scribd company logo
“A Handbook of Agile Software Craftsmanship”
Meaningful Names
Meaningful Names
 “Variables should be named with the
  same level of care given to naming a
  newborn child”
 Use pronounceable names
     genymdhms
   Use searchable names
     Length of a name should correspond to the
     size of its scope
   Avoid disinformation
     Inconsistent spellings
Meaningful Names
   Make meaningful distinctions
     Writing code solely to appease the compiler
     Noise words
     Product/ProductInfo/ProductData
   Use intention-revealing names
     Why does it exist?
     What does it do?
     How is it used?
 One word per concept...but don’t pun
 Don’t add gratuitous context
Functions
Functions
   Small
     Smaller
      ○   Smaller than that

 if/else/while: 1 line blocks
 Do One Thing
     Problem: What is “one thing”?
      ○ “If a function does only those steps that are one
        level below the stated name of the function, then
        the function is doing one thing”
      ○ “A function is doing more than one thing if you can
        extract another function from it with a name that is
        not merely a restatement of its implementation”
     Sections within functions – obviously doing
      more than one thing
Functions
   The stepdown rule
     Top-down narrative
   switch statements – always do N things
     Should appear only once to create polymorphic
      objects, hidden from rest of system
   Function arguments
     Ideal # of arguments: 0
     includeSetupPage() easier to understand
      than
      includeSetupPageInto(newPagecontent)
     If the input’s going to be transformed, it should
      be returned
Functions
   Flag arguments
     Immediately imply that the function does
     more than one thing!
   Command query separation
     Either change the state of an object, or
     return some information about that object
   Extract try/catch blocks
     Allows you to understand, then ignore, error
      processing
     Error handling is one thing!
Comments
Comments
   “Comments are always failures”
     Compensate for failure to express in code
 They lie – we can’t realistically maintain
  them
 Explain yourself in code
     // Check to see if the employee is eligible for
      full benefits
      if ((employee.flags & HOURLY_FLAG) &&
          (employee.age > 65))
    vs.
       if (employee.isEligibleForFullBenefits())
Comments
   Good comments
       Informative
       Explain of intent
       Clarification – when it’s code you can’t alter
       Warning of consequences
   Bad comments
       Redundant
       Misleading
       Mandated
       Journal comments
       Noise comments (“Default constructor”)
       Closing brace comments
       Commented-out code
       HTML comments
       Nonlocal information
       TMI
       Javadocs in nonpublic code
Formatting
“Eastern Polish Christmas Tree Notation”
    public
    DataPair[] getHotelInformation(String hotelId, String informationId)
                                          {
                                            return getHotelInfo("EN", hotelId, informationId);
                                          }
    public
    DataPair[] getHotelInformation(String lang, String hotelId, String informationId)
                                          {
                              String key = "_HOINF_"+lng+"_"+hotelId+"_"+informationId;
                          DataPair[] tbl = (DataPair[])csh.getObject(key);
                            if(tbl!=null) return tbl;
                           Connection cn = null;
              OracleCallableStatement cs = null;
                                     try {
                              String qry = " begin HotelServices.getHotelInfo(?, ?, ?, ?, ?); end; ";
                                  logger . debug("---"+qry+" "+hotelId+" "+informationId);
                                      cn = DriverManager.getConnection("jdbc:weblogic:pool:oraclePool",null);
                                      cs = (OracleCallableStatement)cn.prepareCall(qry);
                                      cs . registerOutParameter(1,java.sql.Types.INTEGER);
                                      cs . registerOutParameter(2,java.sql.Types.OTHER);
                                      cs . setString(3,hotelId);
                                      cs . setString(4,informationId);
                                      cs . setString(5,lang);
                                      cs . execute();
                                 int sta = cs.getInt(1);
                               if(sta!=0) throw new Exception("status not zero sta="+sta);
                            ResultSet rs = cs.getResultSet(2);
                                     tbl = getDataPairArray(rs);
                                  logger . debug("sta="+sta+" key="+key+" cn="+cn);
                                     csh . put(key,tbl);
                                         }
                                    catch(Exception e)
                                         {
                                  logger . debug("!!! "+e.toString()+" "+key);
                                         }
                                  finally
                                         {
                                     try {
                         if(cs!=null) cs . close();
                         if(cn!=null) cn . close();
                                         }
                                    catch(Exception x)
                                         {
                                  logger . debug("!!! "+x.toString()+" "+key);
                                  logger . error("!!! "+x.toString());
                                         }
                                         }
                                   return tbl;
                                         }
Formatting
 Small files usually easier to understand
  than large files
 Newspaper metaphor
     Detail should increase as we move
     downward
 Vertical openness between concepts
 Vertical density & closeness implies
  close association
 Horizontal openness
     Accentuate operator precedence?
Objects and Data Structures
Objects and Data Structures
   Objects: hide data behind abstractions
    and expose functions that operate on
    that data
     OO code: easy to add new classes; hard to
     add new functions
   Data structures: expose their data and
    have no meaningful functions
     Procedural code: easy to add new functions;
     hard to add new data structures
Objects and Data Structures
   Law of Demeter: module shouldn’t know
    about the innards of the objects it
    manipulates
     Don’t expose internal structure through
        accessors
   “Train wrecks”
       final String outputDir =
        ctxt.getOptions().getScratchDir().getAbsolutePath();

   Hybrids
     Functions that do significant things, but also
      public variables/accessors
     Hard to add both new functions and new data
      structures
     Leads to feature envy
Error handling
 If it obscures logic, it’s wrong
 Exceptions rather than return codes
 Use unchecked exceptions
     Checked: low level changes propagate up
     Breaks encapsulation
 Wrap 3rd-party APIs
 Don’t return null – throw exception or
  return a special-case object
 Don’t pass null
Classes
   ...should also be small
     In terms of responsibilities
 SRP – should have ONE reason to
  change
 Big # of small classes vs. Small # of
  large classes
 Cohesion
 OCP – open for extension, closed for
  modification

More Related Content

What's hot

What's New In C# 7
What's New In C# 7What's New In C# 7
What's New In C# 7
Paulo Morgado
 
Java Puzzle
Java PuzzleJava Puzzle
Java Puzzle
SFilipp
 
code for quiz in my sql
code for quiz  in my sql code for quiz  in my sql
code for quiz in my sql
JOYITAKUNDU1
 
Programming Java - Lection 07 - Puzzlers - Lavrentyev Fedor
Programming Java - Lection 07 - Puzzlers - Lavrentyev FedorProgramming Java - Lection 07 - Puzzlers - Lavrentyev Fedor
Programming Java - Lection 07 - Puzzlers - Lavrentyev Fedor
Fedor Lavrentyev
 
Code as data as code.
Code as data as code.Code as data as code.
Code as data as code.
Mike Fogus
 
JDays Lviv 2014: Java8 vs Scala: Difference points & innovation stream
JDays Lviv 2014:  Java8 vs Scala:  Difference points & innovation streamJDays Lviv 2014:  Java8 vs Scala:  Difference points & innovation stream
JDays Lviv 2014: Java8 vs Scala: Difference points & innovation stream
Ruslan Shevchenko
 
Java VS Python
Java VS PythonJava VS Python
Java VS Python
Simone Federici
 
Tuga IT 2017 - What's new in C# 7
Tuga IT 2017 - What's new in C# 7Tuga IT 2017 - What's new in C# 7
Tuga IT 2017 - What's new in C# 7
Paulo Morgado
 
Ip project visual mobile
Ip project visual mobileIp project visual mobile
The Ring programming language version 1.7 book - Part 91 of 196
The Ring programming language version 1.7 book - Part 91 of 196The Ring programming language version 1.7 book - Part 91 of 196
The Ring programming language version 1.7 book - Part 91 of 196
Mahmoud Samir Fayed
 
Fee managment system
Fee managment systemFee managment system
Fee managment system
fairy9912
 
Ensure code quality with vs2012
Ensure code quality with vs2012Ensure code quality with vs2012
Ensure code quality with vs2012
Sandeep Joshi
 
Generics
GenericsGenerics
Generics
Simon Smith
 
Software architecture2008 ejbql-quickref
Software architecture2008 ejbql-quickrefSoftware architecture2008 ejbql-quickref
Software architecture2008 ejbql-quickref
jaiverlh
 
Writing Good Tests
Writing Good TestsWriting Good Tests
Writing Good Tests
Matteo Baglini
 
Scala vs java 8
Scala vs java 8Scala vs java 8
Scala vs java 8
François Sarradin
 
The Ring programming language version 1.10 book - Part 101 of 212
The Ring programming language version 1.10 book - Part 101 of 212The Ring programming language version 1.10 book - Part 101 of 212
The Ring programming language version 1.10 book - Part 101 of 212
Mahmoud Samir Fayed
 
VISUALIZAR REGISTROS EN UN JTABLE
VISUALIZAR REGISTROS EN UN JTABLEVISUALIZAR REGISTROS EN UN JTABLE
VISUALIZAR REGISTROS EN UN JTABLE
Darwin Durand
 
Xm lparsers
Xm lparsersXm lparsers
Xm lparsers
Suman Lata
 
Scala best practices
Scala best practicesScala best practices
Scala best practices
Alexander Zaidel
 

What's hot (20)

What's New In C# 7
What's New In C# 7What's New In C# 7
What's New In C# 7
 
Java Puzzle
Java PuzzleJava Puzzle
Java Puzzle
 
code for quiz in my sql
code for quiz  in my sql code for quiz  in my sql
code for quiz in my sql
 
Programming Java - Lection 07 - Puzzlers - Lavrentyev Fedor
Programming Java - Lection 07 - Puzzlers - Lavrentyev FedorProgramming Java - Lection 07 - Puzzlers - Lavrentyev Fedor
Programming Java - Lection 07 - Puzzlers - Lavrentyev Fedor
 
Code as data as code.
Code as data as code.Code as data as code.
Code as data as code.
 
JDays Lviv 2014: Java8 vs Scala: Difference points & innovation stream
JDays Lviv 2014:  Java8 vs Scala:  Difference points & innovation streamJDays Lviv 2014:  Java8 vs Scala:  Difference points & innovation stream
JDays Lviv 2014: Java8 vs Scala: Difference points & innovation stream
 
Java VS Python
Java VS PythonJava VS Python
Java VS Python
 
Tuga IT 2017 - What's new in C# 7
Tuga IT 2017 - What's new in C# 7Tuga IT 2017 - What's new in C# 7
Tuga IT 2017 - What's new in C# 7
 
Ip project visual mobile
Ip project visual mobileIp project visual mobile
Ip project visual mobile
 
The Ring programming language version 1.7 book - Part 91 of 196
The Ring programming language version 1.7 book - Part 91 of 196The Ring programming language version 1.7 book - Part 91 of 196
The Ring programming language version 1.7 book - Part 91 of 196
 
Fee managment system
Fee managment systemFee managment system
Fee managment system
 
Ensure code quality with vs2012
Ensure code quality with vs2012Ensure code quality with vs2012
Ensure code quality with vs2012
 
Generics
GenericsGenerics
Generics
 
Software architecture2008 ejbql-quickref
Software architecture2008 ejbql-quickrefSoftware architecture2008 ejbql-quickref
Software architecture2008 ejbql-quickref
 
Writing Good Tests
Writing Good TestsWriting Good Tests
Writing Good Tests
 
Scala vs java 8
Scala vs java 8Scala vs java 8
Scala vs java 8
 
The Ring programming language version 1.10 book - Part 101 of 212
The Ring programming language version 1.10 book - Part 101 of 212The Ring programming language version 1.10 book - Part 101 of 212
The Ring programming language version 1.10 book - Part 101 of 212
 
VISUALIZAR REGISTROS EN UN JTABLE
VISUALIZAR REGISTROS EN UN JTABLEVISUALIZAR REGISTROS EN UN JTABLE
VISUALIZAR REGISTROS EN UN JTABLE
 
Xm lparsers
Xm lparsersXm lparsers
Xm lparsers
 
Scala best practices
Scala best practicesScala best practices
Scala best practices
 

Similar to Clean code

Introduction to Client-Side Javascript
Introduction to Client-Side JavascriptIntroduction to Client-Side Javascript
Introduction to Client-Side Javascript
Julie Iskander
 
For Beginners - C#
For Beginners - C#For Beginners - C#
For Beginners - C#
Snehal Harawande
 
Look Ma, “update DB to HTML5 using C++”, no hands! 
Look Ma, “update DB to HTML5 using C++”, no hands! Look Ma, “update DB to HTML5 using C++”, no hands! 
Look Ma, “update DB to HTML5 using C++”, no hands! 
aleks-f
 
Art of Javascript
Art of JavascriptArt of Javascript
Art of Javascript
Tarek Yehia
 
Apache Commons - Don\'t re-invent the wheel
Apache Commons - Don\'t re-invent the wheelApache Commons - Don\'t re-invent the wheel
Apache Commons - Don\'t re-invent the wheel
tcurdt
 
Taming that client side mess with Backbone.js
Taming that client side mess with Backbone.jsTaming that client side mess with Backbone.js
Taming that client side mess with Backbone.js
Jarod Ferguson
 
Introduction To Csharp
Introduction To CsharpIntroduction To Csharp
Introduction To Csharp
g_hemanth17
 
Introduction to-csharp-1229579367461426-1
Introduction to-csharp-1229579367461426-1Introduction to-csharp-1229579367461426-1
Introduction to-csharp-1229579367461426-1
Sachin Singh
 
Introduction to CSharp
Introduction to CSharpIntroduction to CSharp
Introduction to CSharp
Mody Farouk
 
Introduction to csharp
Introduction to csharpIntroduction to csharp
Introduction to csharp
Raga Vahini
 
Introduction to csharp
Introduction to csharpIntroduction to csharp
Introduction to csharp
Satish Verma
 
Introduction to csharp
Introduction to csharpIntroduction to csharp
Introduction to csharp
singhadarsh
 
Lo Mejor Del Pdc2008 El Futrode C#
Lo Mejor Del Pdc2008 El Futrode C#Lo Mejor Del Pdc2008 El Futrode C#
Lo Mejor Del Pdc2008 El Futrode C#
Juan Pablo
 
Cluj.py Meetup: Extending Python in C
Cluj.py Meetup: Extending Python in CCluj.py Meetup: Extending Python in C
Cluj.py Meetup: Extending Python in C
Steffen Wenz
 
Java best practices
Java best practicesJava best practices
Java best practices
Ray Toal
 
The Ring programming language version 1.5 book - Part 8 of 31
The Ring programming language version 1.5 book - Part 8 of 31The Ring programming language version 1.5 book - Part 8 of 31
The Ring programming language version 1.5 book - Part 8 of 31
Mahmoud Samir Fayed
 
Erlang for data ops
Erlang for data opsErlang for data ops
Erlang for data ops
mnacos
 
The Ring programming language version 1.8 book - Part 50 of 202
The Ring programming language version 1.8 book - Part 50 of 202The Ring programming language version 1.8 book - Part 50 of 202
The Ring programming language version 1.8 book - Part 50 of 202
Mahmoud Samir Fayed
 
Clean code
Clean codeClean code
Clean code
Mahmoud Zizo
 
The Ring programming language version 1.4.1 book - Part 13 of 31
The Ring programming language version 1.4.1 book - Part 13 of 31The Ring programming language version 1.4.1 book - Part 13 of 31
The Ring programming language version 1.4.1 book - Part 13 of 31
Mahmoud Samir Fayed
 

Similar to Clean code (20)

Introduction to Client-Side Javascript
Introduction to Client-Side JavascriptIntroduction to Client-Side Javascript
Introduction to Client-Side Javascript
 
For Beginners - C#
For Beginners - C#For Beginners - C#
For Beginners - C#
 
Look Ma, “update DB to HTML5 using C++”, no hands! 
Look Ma, “update DB to HTML5 using C++”, no hands! Look Ma, “update DB to HTML5 using C++”, no hands! 
Look Ma, “update DB to HTML5 using C++”, no hands! 
 
Art of Javascript
Art of JavascriptArt of Javascript
Art of Javascript
 
Apache Commons - Don\'t re-invent the wheel
Apache Commons - Don\'t re-invent the wheelApache Commons - Don\'t re-invent the wheel
Apache Commons - Don\'t re-invent the wheel
 
Taming that client side mess with Backbone.js
Taming that client side mess with Backbone.jsTaming that client side mess with Backbone.js
Taming that client side mess with Backbone.js
 
Introduction To Csharp
Introduction To CsharpIntroduction To Csharp
Introduction To Csharp
 
Introduction to-csharp-1229579367461426-1
Introduction to-csharp-1229579367461426-1Introduction to-csharp-1229579367461426-1
Introduction to-csharp-1229579367461426-1
 
Introduction to CSharp
Introduction to CSharpIntroduction to CSharp
Introduction to CSharp
 
Introduction to csharp
Introduction to csharpIntroduction to csharp
Introduction to csharp
 
Introduction to csharp
Introduction to csharpIntroduction to csharp
Introduction to csharp
 
Introduction to csharp
Introduction to csharpIntroduction to csharp
Introduction to csharp
 
Lo Mejor Del Pdc2008 El Futrode C#
Lo Mejor Del Pdc2008 El Futrode C#Lo Mejor Del Pdc2008 El Futrode C#
Lo Mejor Del Pdc2008 El Futrode C#
 
Cluj.py Meetup: Extending Python in C
Cluj.py Meetup: Extending Python in CCluj.py Meetup: Extending Python in C
Cluj.py Meetup: Extending Python in C
 
Java best practices
Java best practicesJava best practices
Java best practices
 
The Ring programming language version 1.5 book - Part 8 of 31
The Ring programming language version 1.5 book - Part 8 of 31The Ring programming language version 1.5 book - Part 8 of 31
The Ring programming language version 1.5 book - Part 8 of 31
 
Erlang for data ops
Erlang for data opsErlang for data ops
Erlang for data ops
 
The Ring programming language version 1.8 book - Part 50 of 202
The Ring programming language version 1.8 book - Part 50 of 202The Ring programming language version 1.8 book - Part 50 of 202
The Ring programming language version 1.8 book - Part 50 of 202
 
Clean code
Clean codeClean code
Clean code
 
The Ring programming language version 1.4.1 book - Part 13 of 31
The Ring programming language version 1.4.1 book - Part 13 of 31The Ring programming language version 1.4.1 book - Part 13 of 31
The Ring programming language version 1.4.1 book - Part 13 of 31
 

Recently uploaded

Project Management Semester Long Project - Acuity
Project Management Semester Long Project - AcuityProject Management Semester Long Project - Acuity
Project Management Semester Long Project - Acuity
jpupo2018
 
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with SlackLet's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
shyamraj55
 
Nordic Marketo Engage User Group_June 13_ 2024.pptx
Nordic Marketo Engage User Group_June 13_ 2024.pptxNordic Marketo Engage User Group_June 13_ 2024.pptx
Nordic Marketo Engage User Group_June 13_ 2024.pptx
MichaelKnudsen27
 
Generating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and MilvusGenerating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and Milvus
Zilliz
 
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
saastr
 
Energy Efficient Video Encoding for Cloud and Edge Computing Instances
Energy Efficient Video Encoding for Cloud and Edge Computing InstancesEnergy Efficient Video Encoding for Cloud and Edge Computing Instances
Energy Efficient Video Encoding for Cloud and Edge Computing Instances
Alpen-Adria-Universität
 
Salesforce Integration for Bonterra Impact Management (fka Social Solutions A...
Salesforce Integration for Bonterra Impact Management (fka Social Solutions A...Salesforce Integration for Bonterra Impact Management (fka Social Solutions A...
Salesforce Integration for Bonterra Impact Management (fka Social Solutions A...
Jeffrey Haguewood
 
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
Edge AI and Vision Alliance
 
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAUHCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
panagenda
 
Monitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdfMonitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdf
Tosin Akinosho
 
OpenID AuthZEN Interop Read Out - Authorization
OpenID AuthZEN Interop Read Out - AuthorizationOpenID AuthZEN Interop Read Out - Authorization
OpenID AuthZEN Interop Read Out - Authorization
David Brossard
 
20240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 202420240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 2024
Matthew Sinclair
 
TrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy SurveyTrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy Survey
TrustArc
 
AI 101: An Introduction to the Basics and Impact of Artificial Intelligence
AI 101: An Introduction to the Basics and Impact of Artificial IntelligenceAI 101: An Introduction to the Basics and Impact of Artificial Intelligence
AI 101: An Introduction to the Basics and Impact of Artificial Intelligence
IndexBug
 
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
Speck&Tech
 
Skybuffer SAM4U tool for SAP license adoption
Skybuffer SAM4U tool for SAP license adoptionSkybuffer SAM4U tool for SAP license adoption
Skybuffer SAM4U tool for SAP license adoption
Tatiana Kojar
 
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
名前 です男
 
Building Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and MilvusBuilding Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and Milvus
Zilliz
 
GenAI Pilot Implementation in the organizations
GenAI Pilot Implementation in the organizationsGenAI Pilot Implementation in the organizations
GenAI Pilot Implementation in the organizations
kumardaparthi1024
 
Ocean lotus Threat actors project by John Sitima 2024 (1).pptx
Ocean lotus Threat actors project by John Sitima 2024 (1).pptxOcean lotus Threat actors project by John Sitima 2024 (1).pptx
Ocean lotus Threat actors project by John Sitima 2024 (1).pptx
SitimaJohn
 

Recently uploaded (20)

Project Management Semester Long Project - Acuity
Project Management Semester Long Project - AcuityProject Management Semester Long Project - Acuity
Project Management Semester Long Project - Acuity
 
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with SlackLet's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
 
Nordic Marketo Engage User Group_June 13_ 2024.pptx
Nordic Marketo Engage User Group_June 13_ 2024.pptxNordic Marketo Engage User Group_June 13_ 2024.pptx
Nordic Marketo Engage User Group_June 13_ 2024.pptx
 
Generating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and MilvusGenerating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and Milvus
 
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
 
Energy Efficient Video Encoding for Cloud and Edge Computing Instances
Energy Efficient Video Encoding for Cloud and Edge Computing InstancesEnergy Efficient Video Encoding for Cloud and Edge Computing Instances
Energy Efficient Video Encoding for Cloud and Edge Computing Instances
 
Salesforce Integration for Bonterra Impact Management (fka Social Solutions A...
Salesforce Integration for Bonterra Impact Management (fka Social Solutions A...Salesforce Integration for Bonterra Impact Management (fka Social Solutions A...
Salesforce Integration for Bonterra Impact Management (fka Social Solutions A...
 
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
 
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAUHCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
 
Monitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdfMonitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdf
 
OpenID AuthZEN Interop Read Out - Authorization
OpenID AuthZEN Interop Read Out - AuthorizationOpenID AuthZEN Interop Read Out - Authorization
OpenID AuthZEN Interop Read Out - Authorization
 
20240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 202420240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 2024
 
TrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy SurveyTrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy Survey
 
AI 101: An Introduction to the Basics and Impact of Artificial Intelligence
AI 101: An Introduction to the Basics and Impact of Artificial IntelligenceAI 101: An Introduction to the Basics and Impact of Artificial Intelligence
AI 101: An Introduction to the Basics and Impact of Artificial Intelligence
 
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
 
Skybuffer SAM4U tool for SAP license adoption
Skybuffer SAM4U tool for SAP license adoptionSkybuffer SAM4U tool for SAP license adoption
Skybuffer SAM4U tool for SAP license adoption
 
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
 
Building Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and MilvusBuilding Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and Milvus
 
GenAI Pilot Implementation in the organizations
GenAI Pilot Implementation in the organizationsGenAI Pilot Implementation in the organizations
GenAI Pilot Implementation in the organizations
 
Ocean lotus Threat actors project by John Sitima 2024 (1).pptx
Ocean lotus Threat actors project by John Sitima 2024 (1).pptxOcean lotus Threat actors project by John Sitima 2024 (1).pptx
Ocean lotus Threat actors project by John Sitima 2024 (1).pptx
 

Clean code

  • 1. “A Handbook of Agile Software Craftsmanship”
  • 3. Meaningful Names  “Variables should be named with the same level of care given to naming a newborn child”  Use pronounceable names  genymdhms  Use searchable names  Length of a name should correspond to the size of its scope  Avoid disinformation  Inconsistent spellings
  • 4. Meaningful Names  Make meaningful distinctions  Writing code solely to appease the compiler  Noise words Product/ProductInfo/ProductData  Use intention-revealing names  Why does it exist?  What does it do?  How is it used?  One word per concept...but don’t pun  Don’t add gratuitous context
  • 6. Functions  Small  Smaller ○ Smaller than that  if/else/while: 1 line blocks  Do One Thing  Problem: What is “one thing”? ○ “If a function does only those steps that are one level below the stated name of the function, then the function is doing one thing” ○ “A function is doing more than one thing if you can extract another function from it with a name that is not merely a restatement of its implementation”  Sections within functions – obviously doing more than one thing
  • 7. Functions  The stepdown rule  Top-down narrative  switch statements – always do N things  Should appear only once to create polymorphic objects, hidden from rest of system  Function arguments  Ideal # of arguments: 0  includeSetupPage() easier to understand than includeSetupPageInto(newPagecontent)  If the input’s going to be transformed, it should be returned
  • 8. Functions  Flag arguments  Immediately imply that the function does more than one thing!  Command query separation  Either change the state of an object, or return some information about that object  Extract try/catch blocks  Allows you to understand, then ignore, error processing  Error handling is one thing!
  • 10. Comments  “Comments are always failures”  Compensate for failure to express in code  They lie – we can’t realistically maintain them  Explain yourself in code  // Check to see if the employee is eligible for full benefits if ((employee.flags & HOURLY_FLAG) && (employee.age > 65)) vs. if (employee.isEligibleForFullBenefits())
  • 11. Comments  Good comments  Informative  Explain of intent  Clarification – when it’s code you can’t alter  Warning of consequences  Bad comments  Redundant  Misleading  Mandated  Journal comments  Noise comments (“Default constructor”)  Closing brace comments  Commented-out code  HTML comments  Nonlocal information  TMI  Javadocs in nonpublic code
  • 12. Formatting “Eastern Polish Christmas Tree Notation” public DataPair[] getHotelInformation(String hotelId, String informationId) { return getHotelInfo("EN", hotelId, informationId); } public DataPair[] getHotelInformation(String lang, String hotelId, String informationId) { String key = "_HOINF_"+lng+"_"+hotelId+"_"+informationId; DataPair[] tbl = (DataPair[])csh.getObject(key); if(tbl!=null) return tbl; Connection cn = null; OracleCallableStatement cs = null; try { String qry = " begin HotelServices.getHotelInfo(?, ?, ?, ?, ?); end; "; logger . debug("---"+qry+" "+hotelId+" "+informationId); cn = DriverManager.getConnection("jdbc:weblogic:pool:oraclePool",null); cs = (OracleCallableStatement)cn.prepareCall(qry); cs . registerOutParameter(1,java.sql.Types.INTEGER); cs . registerOutParameter(2,java.sql.Types.OTHER); cs . setString(3,hotelId); cs . setString(4,informationId); cs . setString(5,lang); cs . execute(); int sta = cs.getInt(1); if(sta!=0) throw new Exception("status not zero sta="+sta); ResultSet rs = cs.getResultSet(2); tbl = getDataPairArray(rs); logger . debug("sta="+sta+" key="+key+" cn="+cn); csh . put(key,tbl); } catch(Exception e) { logger . debug("!!! "+e.toString()+" "+key); } finally { try { if(cs!=null) cs . close(); if(cn!=null) cn . close(); } catch(Exception x) { logger . debug("!!! "+x.toString()+" "+key); logger . error("!!! "+x.toString()); } } return tbl; }
  • 13. Formatting  Small files usually easier to understand than large files  Newspaper metaphor  Detail should increase as we move downward  Vertical openness between concepts  Vertical density & closeness implies close association  Horizontal openness  Accentuate operator precedence?
  • 14. Objects and Data Structures
  • 15. Objects and Data Structures  Objects: hide data behind abstractions and expose functions that operate on that data  OO code: easy to add new classes; hard to add new functions  Data structures: expose their data and have no meaningful functions  Procedural code: easy to add new functions; hard to add new data structures
  • 16. Objects and Data Structures  Law of Demeter: module shouldn’t know about the innards of the objects it manipulates  Don’t expose internal structure through accessors  “Train wrecks”  final String outputDir = ctxt.getOptions().getScratchDir().getAbsolutePath();  Hybrids  Functions that do significant things, but also public variables/accessors  Hard to add both new functions and new data structures  Leads to feature envy
  • 17. Error handling  If it obscures logic, it’s wrong  Exceptions rather than return codes  Use unchecked exceptions  Checked: low level changes propagate up  Breaks encapsulation  Wrap 3rd-party APIs  Don’t return null – throw exception or return a special-case object  Don’t pass null
  • 18. Classes  ...should also be small  In terms of responsibilities  SRP – should have ONE reason to change  Big # of small classes vs. Small # of large classes  Cohesion  OCP – open for extension, closed for modification

Editor's Notes

  1. Can split the train wreck into 3 variables. Whether this breaks Law of Demeter depends on whether or not those variables are objects or data structures
  2. Error codes: caller has to check for errors immediately after the callWrap APIs: make it returns a common exception type