SlideShare a Scribd company logo
1 of 25
Clean code Bites
Applying clean code




Roy Nitert




28-3-2012
Agenda

 Why clean code
 What is clean code
 Examples:
  o SRP
  o Small methods
  o Descriptive names
  o Parameters
  o DRY
                        © Sioux 2012 | Confidential | 2
Why clean code ?

 So it is easier to understand (readability) and
  cheaper to modify (maintainability) software
 The code you write will be read more times
  than it was written and by more people.
 Focus on the small things that make us better
  programmers.




                                        © Sioux 2012 | Confidential | 3
What is clean code ?




            © Sioux 2012 | Confidential | 4
What is clean code ?

http://en.wiktionary.org/wiki/clean_code
Noun
clean code (plural clean codes)
(idiomatic) software code that is formatted
   correctly and in an organized manner so that
   another coder can easily read or modify it.




                                           © Sioux 2012 | Confidential | 5
What is clean code ?

Characteristics of clean code:
 Small methods and classes
 Descriptive names
 Not too many parameters in methods (and no flags)
 No obvious or irrelevant comments (code must be
  self describing)
 No redundancy (DRY: don‟t repeat yourself)
 No magic numbers
 Single responsibility principle (SRP)
 Uniform coding style

                                          © Sioux 2012 | Confidential | 6
SRP: Single Responsibility
                                         Principle

 every object should have a
  single responsibility, and that
  responsibility should be entirely
  encapsulated by the class.
 a class or module should have
  one, and only one, reason to change
 If class names have „manager‟ or „processor‟ in
  them, they probably have multiple
  responsibilities
 the "S" in "SOLID" stands for the single
  responsibility principle (“Principles Of OOD”, Robert C. Martin)

                                                       © Sioux 2012 | Confidential | 7
SRP example

Public class DashboardManager {
  public Component getLastFocusedComponent();
  public void setLastFocused(Component
  lastFocused);
  public int getMajorVersionNumber();
  public int getMinorVersionNumber();
  public int getBuildNumber();
}


                                    © Sioux 2012 | Confidential | 8
SRP example

Public class FocusedComponent {
  public Component getLastFocusedComponent();
  public void setLastFocused(Component
  lastFocused);

Public class Version {
  public int getMajorVersionNumber();
  public int getMinorVersionNumber();
  public int getBuildNumber();
}

                                        © Sioux 2012 | Confidential | 9
Small methods

   They should be very very small
   Should do one thing, do it well, do it only
   One level of abstraction
   Should read like a narrative
   Should not have sections
   Blocks within if, else and while
    statements should be one line long



                                              © Sioux 2012 | Confidential | 10
Small methods example

public static String renderPageWithSetupsAndTeardowns(
    PageData pageData, boolean isSuite
) throws Exception {
    boolean isTestPage = pageData.hasAttribute(“Test”);
    if (isTestPage) {
           WikiPage testPage = pageData.getWikiPage();
           StringBuffer newPageContent = new StringBuffer();
           includeSetupPages(testPage, newPageContent, isSuite);
           newPageContent.append(pageData.getContent());
           includeTeardownPages(testPage, newPageContent, isSuite);
           pageData.setContent(newPageContent.toString());
    }
    return pageData.getHTML();
}


                                                        © Sioux 2012 | Confidential | 11
Small methods example

public static String renderPageWithSetupsAndTeardowns(
    PageData pageData, boolean isSuite
) throws Exception {
    if (isTestPage(pageData))
          includeSetupAndTeardownPages(pageData, isSuite);

    return pageData.getHTML();
}




                                                  © Sioux 2012 | Confidential | 12
Descriptive names

   Names make software readable
   Helps clarify the design in your mind
   Use long names for long scopes
   Avoid encodings




                                            © Sioux 2012 | Confidential | 13
Descriptive names example

Public int x() {
   int q = 0;
   int z = 0;
   for (int kk = 0; kk < 10; kk++) {
           if (l[z] == 10) {
                        q += 10 + (l[z + 1] + l[z + 2]);
                        z += 1;
           } else if (l[z] + l[z + 1] == 10) {
                        q += 10 + l[z + 2];
                        z += 2;
           } else {
                        q += l[z] + l[z + 1];
                        z += 2;
           }
   }
   return q;
}



                                                           © Sioux 2012 | Confidential | 14
Descriptive names example

Public int score() {
   int score = 0;
   int frame = 0;
   for (int frameNumber = 0; frameNumber < 10; frameNumber++) {
           if (isStrike(frame)) {
                        score += 10 + nextTwoBallsForStrike(frame);
                        frame += 1;
           } else if (isSpare(frame)) {
                        score += 10 + nextBallForSpare(frame);
                        frame += 2;
           } else {
                        score += TwoBallsInFrame(frame);
                        frame += 2;
           }
   }
   return score;
}                                                                     © Sioux 2012 | Confidential | 15
Parameters / arguments

 Small number: Zero is best, followed by one, two
  or three
 More than three is questionable
 Output arguments are counterintuitive
 Boolean arguments (flags) loudly declare than
  the function does more than one thing
 Simpler is easy to understand and easy to test
 Reduce number of arguments by creating
  objects out of them

                                        © Sioux 2012 | Confidential | 16
Parameters example

Circle makeCircle(double x, double y, double
  radius);



public void AlignTaskCanBeStopped(bool
  useRealXps);

AlignTaskCanBeStopped(true);


                                         © Sioux 2012 | Confidential | 17
Parameters example

Circle makeCircle(Point center, double radius);




public void AlignTaskCanBeStoppedWith
  RealXps();
public void AlignTaskCanBeStoppedWith
  SimulatedXps();


                                          © Sioux 2012 | Confidential | 18
Don‟t repeat yourself

 Duplication
 DRY principle (Dave Thomas)
 Once, and only once (Kent Beck)
 Duplication is a missed opportunity for abstraction
 Examples:
  o Identical code (copy/paste)
  o Switch/case (or if/else) chains
  o Similar algorithms
 Design patterns and OO itself are strategies for
  eliminating duplication

                                             © Sioux 2012 | Confidential | 19
DRY example

public void scaleToOneDimension( float desiredDimension, float imageDimension) {
    if (Math.abs(desiredDimension – imageDimension) < errorThreshold)
            return;
    float scalingFactor = desiredDimension / imageDimension;
    scalingFactor = (float)(Math.floor(scalingFactor * 100) * 0.01f);

    RenderOp newImage = ImageUtilities.getScaledImage( image, scalingFactor,
    scalingFactor);
    image.dispose();
    System.gc();
    image = newImage;
}

public synchronized void rotate(int degrees) {
    RenderOp newImage = ImageUtilities.getRotatedImage( image, degrees);
    image.dispose();
    System.gc();
    image = newImage;
}


                                                                          © Sioux 2012 | Confidential | 20
DRY example

public void scaleToOneDimension( float desiredDimension, float imageDimension) {
    if (Math.abs(desiredDimension – imageDimension) < errorThreshold)
            return;
    float scalingFactor = desiredDimension / imageDimension;
    scalingFactor = (float)(Math.floor(scalingFactor * 100) * 0.01f);

    replaceImage(ImageUtilities.getScaledImage( image, scalingFactor, scalingFactor));
}

public synchronized void rotate(int degrees) {
    replaceImage(ImageUtilities.getRotatedImage( image, degrees));
}

private void replaceImage(RenderedOp newImage) {
    image.dispose();
    System.gc();
    image = newImage;
}



                                                                           © Sioux 2012 | Confidential | 21
Applying clean code

 Know how to write clean code
 Think about these small improvements
  during:
  o New development
  o Code reviews
  o Changing code
  o Fixing bugs
 So code will be easier to understand and
  cheaper to modify

                                      © Sioux 2012 | Confidential | 22
Conclusion

Write code as if the person who is going to
  maintain it, is a psychopath who knows
                where you live.




                                    © Sioux 2012 | Confidential | 23
Questions?




   © Sioux 2012 | Confidential | 24
+31 (0)40 2677100
roy.nitert@sioux.eu

                      © Sioux 2012 | Confidential | 25

More Related Content

Similar to Clean code bites

Universal Declarative Services - Simon Chemouil
Universal Declarative Services - Simon ChemouilUniversal Declarative Services - Simon Chemouil
Universal Declarative Services - Simon Chemouilmfrancis
 
.NET Coding Standards For The Real World (2012)
.NET Coding Standards For The Real World (2012).NET Coding Standards For The Real World (2012)
.NET Coding Standards For The Real World (2012)David McCarter
 
Evolving a Clean, Pragmatic Architecture at JBCNConf 2019
Evolving a Clean, Pragmatic Architecture at JBCNConf 2019Evolving a Clean, Pragmatic Architecture at JBCNConf 2019
Evolving a Clean, Pragmatic Architecture at JBCNConf 2019Victor Rentea
 
Integrating DDS into AXCIOMA, the component approach
Integrating DDS into AXCIOMA, the component approachIntegrating DDS into AXCIOMA, the component approach
Integrating DDS into AXCIOMA, the component approachRemedy IT
 
Integrating DDS into AXCIOMA - The Component Approach
Integrating DDS into AXCIOMA - The Component ApproachIntegrating DDS into AXCIOMA - The Component Approach
Integrating DDS into AXCIOMA - The Component ApproachReal-Time Innovations (RTI)
 
Addressing Scenario
Addressing ScenarioAddressing Scenario
Addressing ScenarioTara Hardin
 
Combating software entropy 2-roc1-
Combating software entropy 2-roc1-Combating software entropy 2-roc1-
Combating software entropy 2-roc1-Hammad Rajjoub
 
Integrating DDS into AXCIOMA, the component approach
Integrating DDS into AXCIOMA, the component approachIntegrating DDS into AXCIOMA, the component approach
Integrating DDS into AXCIOMA, the component approachRemedy IT
 
Data-centric Invocable Services
Data-centric Invocable ServicesData-centric Invocable Services
Data-centric Invocable ServicesRick Warren
 
An Introduction to the SOLID Principles
An Introduction to the SOLID PrinciplesAn Introduction to the SOLID Principles
An Introduction to the SOLID PrinciplesAttila Bertók
 
JavaFX 2.1 - следующее поколение клиентской Java
JavaFX 2.1 - следующее поколение клиентской JavaJavaFX 2.1 - следующее поколение клиентской Java
JavaFX 2.1 - следующее поколение клиентской JavaAlexander_K
 
C:\Fakepath\Combating Software Entropy 2
C:\Fakepath\Combating Software Entropy 2C:\Fakepath\Combating Software Entropy 2
C:\Fakepath\Combating Software Entropy 2Hammad Rajjoub
 
C:\Fakepath\Combating Software Entropy 2
C:\Fakepath\Combating Software Entropy 2C:\Fakepath\Combating Software Entropy 2
C:\Fakepath\Combating Software Entropy 2Hammad Rajjoub
 
Open source report writing tools for IBM i Vienna 2012
Open source report writing tools for IBM i  Vienna 2012Open source report writing tools for IBM i  Vienna 2012
Open source report writing tools for IBM i Vienna 2012COMMON Europe
 
DDS Programming with IDL to C++11 tutorial
DDS Programming with IDL to C++11 tutorialDDS Programming with IDL to C++11 tutorial
DDS Programming with IDL to C++11 tutorialRemedy IT
 

Similar to Clean code bites (20)

L04 Software Design Examples
L04 Software Design ExamplesL04 Software Design Examples
L04 Software Design Examples
 
Universal Declarative Services - Simon Chemouil
Universal Declarative Services - Simon ChemouilUniversal Declarative Services - Simon Chemouil
Universal Declarative Services - Simon Chemouil
 
C# in depth
C# in depthC# in depth
C# in depth
 
Sightly_techInsight
Sightly_techInsightSightly_techInsight
Sightly_techInsight
 
.NET Coding Standards For The Real World (2012)
.NET Coding Standards For The Real World (2012).NET Coding Standards For The Real World (2012)
.NET Coding Standards For The Real World (2012)
 
Evolving a Clean, Pragmatic Architecture at JBCNConf 2019
Evolving a Clean, Pragmatic Architecture at JBCNConf 2019Evolving a Clean, Pragmatic Architecture at JBCNConf 2019
Evolving a Clean, Pragmatic Architecture at JBCNConf 2019
 
Integrating DDS into AXCIOMA, the component approach
Integrating DDS into AXCIOMA, the component approachIntegrating DDS into AXCIOMA, the component approach
Integrating DDS into AXCIOMA, the component approach
 
Integrating DDS into AXCIOMA - The Component Approach
Integrating DDS into AXCIOMA - The Component ApproachIntegrating DDS into AXCIOMA - The Component Approach
Integrating DDS into AXCIOMA - The Component Approach
 
Clean code
Clean codeClean code
Clean code
 
Addressing Scenario
Addressing ScenarioAddressing Scenario
Addressing Scenario
 
Combating software entropy 2-roc1-
Combating software entropy 2-roc1-Combating software entropy 2-roc1-
Combating software entropy 2-roc1-
 
Integrating DDS into AXCIOMA, the component approach
Integrating DDS into AXCIOMA, the component approachIntegrating DDS into AXCIOMA, the component approach
Integrating DDS into AXCIOMA, the component approach
 
Data-centric Invocable Services
Data-centric Invocable ServicesData-centric Invocable Services
Data-centric Invocable Services
 
Clean Code 2
Clean Code 2Clean Code 2
Clean Code 2
 
An Introduction to the SOLID Principles
An Introduction to the SOLID PrinciplesAn Introduction to the SOLID Principles
An Introduction to the SOLID Principles
 
JavaFX 2.1 - следующее поколение клиентской Java
JavaFX 2.1 - следующее поколение клиентской JavaJavaFX 2.1 - следующее поколение клиентской Java
JavaFX 2.1 - следующее поколение клиентской Java
 
C:\Fakepath\Combating Software Entropy 2
C:\Fakepath\Combating Software Entropy 2C:\Fakepath\Combating Software Entropy 2
C:\Fakepath\Combating Software Entropy 2
 
C:\Fakepath\Combating Software Entropy 2
C:\Fakepath\Combating Software Entropy 2C:\Fakepath\Combating Software Entropy 2
C:\Fakepath\Combating Software Entropy 2
 
Open source report writing tools for IBM i Vienna 2012
Open source report writing tools for IBM i  Vienna 2012Open source report writing tools for IBM i  Vienna 2012
Open source report writing tools for IBM i Vienna 2012
 
DDS Programming with IDL to C++11 tutorial
DDS Programming with IDL to C++11 tutorialDDS Programming with IDL to C++11 tutorial
DDS Programming with IDL to C++11 tutorial
 

Recently uploaded

[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Google AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGGoogle AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGSujit Pal
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...gurkirankumar98700
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 

Recently uploaded (20)

[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Google AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGGoogle AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAG
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 

Clean code bites

  • 1. Clean code Bites Applying clean code Roy Nitert 28-3-2012
  • 2. Agenda  Why clean code  What is clean code  Examples: o SRP o Small methods o Descriptive names o Parameters o DRY © Sioux 2012 | Confidential | 2
  • 3. Why clean code ?  So it is easier to understand (readability) and cheaper to modify (maintainability) software  The code you write will be read more times than it was written and by more people.  Focus on the small things that make us better programmers. © Sioux 2012 | Confidential | 3
  • 4. What is clean code ? © Sioux 2012 | Confidential | 4
  • 5. What is clean code ? http://en.wiktionary.org/wiki/clean_code Noun clean code (plural clean codes) (idiomatic) software code that is formatted correctly and in an organized manner so that another coder can easily read or modify it. © Sioux 2012 | Confidential | 5
  • 6. What is clean code ? Characteristics of clean code:  Small methods and classes  Descriptive names  Not too many parameters in methods (and no flags)  No obvious or irrelevant comments (code must be self describing)  No redundancy (DRY: don‟t repeat yourself)  No magic numbers  Single responsibility principle (SRP)  Uniform coding style © Sioux 2012 | Confidential | 6
  • 7. SRP: Single Responsibility Principle  every object should have a single responsibility, and that responsibility should be entirely encapsulated by the class.  a class or module should have one, and only one, reason to change  If class names have „manager‟ or „processor‟ in them, they probably have multiple responsibilities  the "S" in "SOLID" stands for the single responsibility principle (“Principles Of OOD”, Robert C. Martin) © Sioux 2012 | Confidential | 7
  • 8. SRP example Public class DashboardManager { public Component getLastFocusedComponent(); public void setLastFocused(Component lastFocused); public int getMajorVersionNumber(); public int getMinorVersionNumber(); public int getBuildNumber(); } © Sioux 2012 | Confidential | 8
  • 9. SRP example Public class FocusedComponent { public Component getLastFocusedComponent(); public void setLastFocused(Component lastFocused); Public class Version { public int getMajorVersionNumber(); public int getMinorVersionNumber(); public int getBuildNumber(); } © Sioux 2012 | Confidential | 9
  • 10. Small methods  They should be very very small  Should do one thing, do it well, do it only  One level of abstraction  Should read like a narrative  Should not have sections  Blocks within if, else and while statements should be one line long © Sioux 2012 | Confidential | 10
  • 11. Small methods example public static String renderPageWithSetupsAndTeardowns( PageData pageData, boolean isSuite ) throws Exception { boolean isTestPage = pageData.hasAttribute(“Test”); if (isTestPage) { WikiPage testPage = pageData.getWikiPage(); StringBuffer newPageContent = new StringBuffer(); includeSetupPages(testPage, newPageContent, isSuite); newPageContent.append(pageData.getContent()); includeTeardownPages(testPage, newPageContent, isSuite); pageData.setContent(newPageContent.toString()); } return pageData.getHTML(); } © Sioux 2012 | Confidential | 11
  • 12. Small methods example public static String renderPageWithSetupsAndTeardowns( PageData pageData, boolean isSuite ) throws Exception { if (isTestPage(pageData)) includeSetupAndTeardownPages(pageData, isSuite); return pageData.getHTML(); } © Sioux 2012 | Confidential | 12
  • 13. Descriptive names  Names make software readable  Helps clarify the design in your mind  Use long names for long scopes  Avoid encodings © Sioux 2012 | Confidential | 13
  • 14. Descriptive names example Public int x() { int q = 0; int z = 0; for (int kk = 0; kk < 10; kk++) { if (l[z] == 10) { q += 10 + (l[z + 1] + l[z + 2]); z += 1; } else if (l[z] + l[z + 1] == 10) { q += 10 + l[z + 2]; z += 2; } else { q += l[z] + l[z + 1]; z += 2; } } return q; } © Sioux 2012 | Confidential | 14
  • 15. Descriptive names example Public int score() { int score = 0; int frame = 0; for (int frameNumber = 0; frameNumber < 10; frameNumber++) { if (isStrike(frame)) { score += 10 + nextTwoBallsForStrike(frame); frame += 1; } else if (isSpare(frame)) { score += 10 + nextBallForSpare(frame); frame += 2; } else { score += TwoBallsInFrame(frame); frame += 2; } } return score; } © Sioux 2012 | Confidential | 15
  • 16. Parameters / arguments  Small number: Zero is best, followed by one, two or three  More than three is questionable  Output arguments are counterintuitive  Boolean arguments (flags) loudly declare than the function does more than one thing  Simpler is easy to understand and easy to test  Reduce number of arguments by creating objects out of them © Sioux 2012 | Confidential | 16
  • 17. Parameters example Circle makeCircle(double x, double y, double radius); public void AlignTaskCanBeStopped(bool useRealXps); AlignTaskCanBeStopped(true); © Sioux 2012 | Confidential | 17
  • 18. Parameters example Circle makeCircle(Point center, double radius); public void AlignTaskCanBeStoppedWith RealXps(); public void AlignTaskCanBeStoppedWith SimulatedXps(); © Sioux 2012 | Confidential | 18
  • 19. Don‟t repeat yourself  Duplication  DRY principle (Dave Thomas)  Once, and only once (Kent Beck)  Duplication is a missed opportunity for abstraction  Examples: o Identical code (copy/paste) o Switch/case (or if/else) chains o Similar algorithms  Design patterns and OO itself are strategies for eliminating duplication © Sioux 2012 | Confidential | 19
  • 20. DRY example public void scaleToOneDimension( float desiredDimension, float imageDimension) { if (Math.abs(desiredDimension – imageDimension) < errorThreshold) return; float scalingFactor = desiredDimension / imageDimension; scalingFactor = (float)(Math.floor(scalingFactor * 100) * 0.01f); RenderOp newImage = ImageUtilities.getScaledImage( image, scalingFactor, scalingFactor); image.dispose(); System.gc(); image = newImage; } public synchronized void rotate(int degrees) { RenderOp newImage = ImageUtilities.getRotatedImage( image, degrees); image.dispose(); System.gc(); image = newImage; } © Sioux 2012 | Confidential | 20
  • 21. DRY example public void scaleToOneDimension( float desiredDimension, float imageDimension) { if (Math.abs(desiredDimension – imageDimension) < errorThreshold) return; float scalingFactor = desiredDimension / imageDimension; scalingFactor = (float)(Math.floor(scalingFactor * 100) * 0.01f); replaceImage(ImageUtilities.getScaledImage( image, scalingFactor, scalingFactor)); } public synchronized void rotate(int degrees) { replaceImage(ImageUtilities.getRotatedImage( image, degrees)); } private void replaceImage(RenderedOp newImage) { image.dispose(); System.gc(); image = newImage; } © Sioux 2012 | Confidential | 21
  • 22. Applying clean code  Know how to write clean code  Think about these small improvements during: o New development o Code reviews o Changing code o Fixing bugs  So code will be easier to understand and cheaper to modify © Sioux 2012 | Confidential | 22
  • 23. Conclusion Write code as if the person who is going to maintain it, is a psychopath who knows where you live. © Sioux 2012 | Confidential | 23
  • 24. Questions? © Sioux 2012 | Confidential | 24
  • 25. +31 (0)40 2677100 roy.nitert@sioux.eu © Sioux 2012 | Confidential | 25

Editor's Notes

  1. 1 slide on why, 3 slides on what, examples are a good way to communicate about clean code. Some examples using code.I use the book Clean code by Robert Martin.
  2. 1,2: Communication : So to minimize the cost of maintenance, your code should be clear to those people (or yourself) reading it a later date. It should be nice to read, it should clearly communicate its design, and it should not be overly complex.3: After we all read GoF’sDesign Patterns, a lot of books were talking about design patterns and then about architecture patterns. And after that our attention shifted towards process (XP, Agile). It is good to remember that the “mundane” task of writing code is something we still can and must improve.
  3. From the book Clean code by Robert Martin.
  4. Does this help ?
  5. Clean code – A Handbook of Agile Software Craftsmanship – Robert MartinDon’t use comments to describe code. . Only use comments when the code can not tell it.No magic numbers -&gt; use constantsStyle -&gt; indenting
  6. SOLID: SRP, OCP, LSP, DIP, ISP
  7. Does two thingsTwo differentreasons to change
  8. =&gt; Split it up in two classes
  9. Only about 10 lines. But it tests for testpage and then also includes pages
  10. isTestPage() should be defined just below. And below that should be includeSetup….
  11. For loop can have a inti as variable, when the scope is smallEncodings: it should read well (don’t abbriviate). Also don’t use hungarian notation etc.
  12. Two/three: ordering of arguments is a problem. =&gt; mix upassertEquals(expected, actual);Flag: the call is confusing ! =&gt; split it up
  13. Duplication is a problem for maintenance. You have to remember to change it in multiple locationsBeck (XP)Also Ron Jeffries says it is the second most important rule, just after getting the tests to passSwitch/case can be solved with polymorphismsDuplication is one of the big code smells that prgrammers have to solve
  14. Easy: 3 lines of identical code=&gt; Create new method
  15. Higher level of abstraction: new method name describing what it doesTotal is 1 line less code
  16. Every time you have an opportunity to change code, make sure it is a little cleaner.