SlideShare une entreprise Scribd logo
1  sur  37
Télécharger pour lire hors ligne
CLEAN CODE
                          By: Sharevison Team




8º Simpósio Brasileiro de Linguagens de Programação
How do you know, how bad your code is?
Bjarne Stroustrup, inventor of C++
     and author of The C++ Programming
                  Language
I like my code to be elegant and efficient. The logic should be
straightforward to make it hard for bugs to hide, the
dependencies minimal to ease maintenance, error handling
complete according to an articulated strategy, and per-
formance close to optimal so as not to tempt people to make
the code messy with unprinci-pled optimizations. Clean code
does one thing well.
“Big” Dave Thomas, founder
           of OTI, godfather of the
                Eclipse strategy
Clean code can be read, and enhanced by a developer other
than its original author. It has unit and acceptance tests. It has
meaningful names. It provides one way rather than many ways
for doing one thing. It has minimal depen dencies, which are
explicitly defined, and pro- vides a clear and minimal API. Code
should be literate since depending on the language, not all
necessary information can be expressed clearly in code alone.
Michael Feathers, author of Working
         Effectively with Legacy Code

I could list all of the qualities that I notice in clean code, but
there is one overarching quality that leads to all of them.
Clean code always looks like it was written by someone who
cares. There is nothing obvious that you can do to make it
better. All of those things were thought about by the code’s
author, and if you try to imagine improvements, you’re led
back to where you are, sitting in appreciation of the code
someone left for you—code left by some one who cares
deeply about the craft.
My personal View

The code considered to be clean will need these:
   Well written test (Unit test) for every public methods.
   A class should be small and does one thing only
   A method should be small enough( not longer then 20 lines)
   A method should does only one thing and does it well
   After all, I should able to hand over my code to other, and they should
   able to carry on the work.
Productivity vs. Time
Meaningfull Names


Use Intention-Revealing Names:
    Intention-
  It should tell you why it exists, what it does, and how it is
  used.

             int d; // elapsed time in days


                       OR

               int   elapsedTimeInDays;
               int   daysSinceCreation;
               int   daysSinceModification;
               int   fileAgeInDays;
Avoid Disinformation


avoid words whose entrenched meanings vary from
our intended meaning.
Eg. grouping of accounts -> var accountList
Use Pronounceable Names


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


                       To

class Customer {
       private Date generationTimestamp;
       private Date modificationTimestamp;;
       private final String recordId = "102";
       /* ... */
};
Avoid Encodings

Hungarian Notation
          PhoneNumber phoneString;
          // name not changed when type changed!
Member Prefixes
  public class Part {
         private String m_dsc; // The textual
         description
         void setName(String name) {
                m_dsc = name;
         }
  }                  To

public class Part {
       String description;
       void setDescription(String description) {
              this.description = description;
       }
}
Avoid Mental Mapping


Readers shouldn’t have to mentally translate your
names into other names they already know.
This problem generally arises from a choice to use
neither problem domain terms nor solution domain
terms.
           var r; //url
           var fn; //first name
Method


Method should be a verbphrase like getAccount,
displayTest ...etc.
Don’t Be Cute


What about this


   HolyHandGrenade or DeleteItems
Pick One Word per Concept


Pick one word for one abstract concept and stick with it
Eg.
  Fetch(), retrieve(), get() as equivalent
  methods of different classes.

  controller and a manager and a driver in the same code base.
Don’t Pun


Avoid using the same word for two purposes
Eg.
  add(firstItem, secondItem), concatinat two items.
  add(newItem), append to existing item
Use Solution Domain Names


Do not afraid of using computer science team like:
  Name of patters
  Algorithm


        • getMinWidthComposite()

        •AccountVisitor
Add Meaningful Context


enclosing them in well-named classes, functions, or
namespaces

      private void thereIsOneLetter() {
          number = "1";
          verb = "is";
          pluralModifier = "";
      }
Function


Small, should be hardly every 20 lines long
Does one thing, it should does one thing, does it well,
and does it only.
Function: One Level of Abstraction per
               Function
gtk.Button.prototype.setImage = function(image){
         this._widget2 = image;
         this.resize(this._minWidth, this._minHeight);
         this._widget2._domObj.style.display = "";
         this._imageDom.appendChild(this._widget2._domObj);
};

                        To

gtk.Button.prototype.setImage = function(image){
         this._widget2 = image;
         this.resize(this._minWidth, this._minHeight);
         this.hide(this._widget2);
         this._appendImage(this._widget2._domObj);
};

gtk.Button.prototype.hideWidget = function(widget){
         widget._domObj.style.display = "";
};

gtk.Button.prototype.appendImage = function(){
         this._imageDom.appendChild(this._widget2._domObj);
};
Function Arguments


What is the best number of arugments passed in:
     Zero (niladic)
     Two (dyadic)
     Three (polyadic)
     More then this is evil

Reasons not to have many arguments:
     For public methods, user fine it hard to use the method.
     For private method, it should able to access the class
     properties, why have to pass in.
Function Arguments


Flag Arguments: Passing a boolean into a function is a truly
terrible practice

                    render(true)

                         OR

          renderForSuite() and renderForSingleTest()
Function Arguments


Argument Objects: more than two or three arguments, they
ought to be wrapped into a class of their own.

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

                     OR


         Circle(circleProperties);
Don’t repeat yourself


If you see the same code structure more than one
place, then extract the method and invoke the code
from both places
Switch Statement


How to make switch statement does one thing?
  public Money calculatePay(Employee e)
  throws InvalidEmployeeType {
      switch (e.type) {
        case COMMISSIONED:
          return calculateCommissionedPay(e);
        case HOURLY:
          return calculateHourlyPay(e);
        case SALARIED:
          return calculateSalariedPay(e);
        default:
          throw new InvalidEmployeeType(e.type);
      }
    }
Comment


Comments Do Not Make Up for Bad Code:
    “Ooh, I’d better comment that!” No! You’d better
    clean it!”
// Check to see if the employee is eligible for full
benefits
if ((employee.flags & HOURLY_FLAG) && (employee.age >
65))

                      OR


  if (employee.isEligibleForFullBenefits())
Good Comments
Comment


    Legal Comments
// Copyright (C) 2003,2004,2005 by Object Mentor, Inc. All rights reserved.
// Released under terms of the GNU General Public License version 2 or later.




    Informative Comments
     // Returns an instance of the Responder being tested.
     protected abstract Responder responderInstance();


                             OR
  protected abstract Responder getResponderInstance();
Warning of Consequences


Warning of Consequences
// Don't run unless you
// have some time to kill.
public void _testWithReallyBigFile()
{
         writeLinesToFile(10000000);
         response.setBody(testFile);
         response.readyToSend(this);
         String responseString = output.toString();
         assertSubString("Content-Length: 1000000000", responseString);
         assertTrue(bytesSent > 1000000000);
}
TODO Comments


Leave TODO comment

  //TODO-MdM these are not needed
  // We expect this to go away when we do the checkout model
  protected VersionInfo makeVersion() throws Exception
  {
          return null;
  }
Bad Comments
Redundant Comments


     The comment that takes longer to read than the code
     itself

// Utility method that returns when this.closed is true. Throws an exception
// if the timeout is reached.
public synchronized void waitForClose(final long timeoutMillis) throws Exception
{
         if(!closed)
         {
                  wait(timeoutMillis);
                  if(!closed)
                           throw new Exception("MockResponseSender could not be
closed");
         }
}
Noise Comments


Sometimes you see comments that are nothing but noise.
They restate the obvious and provide no new information.


          /**
           * Returns the day of the month.
           *
           * @return the day of the month.
           */
          public int getDayOfMonth() {
            return dayOfMonth;
          }
Don’t Use a Comment When You Can Use a
               Function or a Variable

// does the module from the global list <mod> depend on the
// subsystem we are part of?
if (smodule.getDependSubsystems().contains(subSysMod.getSubSystem()))


                               OR

     ArrayList moduleDependees = smodule.getDependSubsystems();
     String ourSubSystem = subSysMod.getSubSystem();
     if (moduleDependees.contains(ourSubSystem))
Position Markers


Mark a particular position in a source file


     // Actions //////////////////////////////////
Class Names


Classes and objects should have noun or noun phrase
names like Customer, WikiPage, Account, and
AddressParser.
Reference


Clean Code: a hand book of agile software
craftmanship by Robert C. Martin
Refactoring, Improving the design of existing
code by Martin Fowler

Contenu connexe

Tendances

Back-2-Basics: .NET Coding Standards For The Real World (2011)
Back-2-Basics: .NET Coding Standards For The Real World (2011)Back-2-Basics: .NET Coding Standards For The Real World (2011)
Back-2-Basics: .NET Coding Standards For The Real World (2011)David McCarter
 
Rock Your Code with Code Contracts
Rock Your Code with Code ContractsRock Your Code with Code Contracts
Rock Your Code with Code ContractsDavid McCarter
 
Strategy Design Pattern
Strategy Design PatternStrategy Design Pattern
Strategy Design PatternGanesh Kolhe
 
Generics and collections in Java
Generics and collections in JavaGenerics and collections in Java
Generics and collections in JavaGurpreet singh
 
[2012 02 03]clean_code 4장
[2012 02 03]clean_code 4장[2012 02 03]clean_code 4장
[2012 02 03]clean_code 4장Jong Pil Won
 
Generic Programming in java
Generic Programming in javaGeneric Programming in java
Generic Programming in javaGarik Kalashyan
 
Java căn bản - Chapter8
Java căn bản - Chapter8Java căn bản - Chapter8
Java căn bản - Chapter8Vince Vo
 
Chapter 9 - Characters and Strings
Chapter 9 - Characters and StringsChapter 9 - Characters and Strings
Chapter 9 - Characters and StringsEduardo Bergavera
 
Unit I Advanced Java Programming Course
Unit I   Advanced Java Programming CourseUnit I   Advanced Java Programming Course
Unit I Advanced Java Programming Courseparveen837153
 
Chapter 4:Object-Oriented Basic Concepts
Chapter 4:Object-Oriented Basic ConceptsChapter 4:Object-Oriented Basic Concepts
Chapter 4:Object-Oriented Basic ConceptsIt Academy
 
Chapter 7:Understanding Class Inheritance
Chapter 7:Understanding Class InheritanceChapter 7:Understanding Class Inheritance
Chapter 7:Understanding Class InheritanceIt Academy
 
C# for-java-developers
C# for-java-developersC# for-java-developers
C# for-java-developersDhaval Dalal
 
Lecture 4_Java Method-constructor_imp_keywords
Lecture   4_Java Method-constructor_imp_keywordsLecture   4_Java Method-constructor_imp_keywords
Lecture 4_Java Method-constructor_imp_keywordsmanish kumar
 
Lecture 6 inheritance
Lecture   6 inheritanceLecture   6 inheritance
Lecture 6 inheritancemanish kumar
 

Tendances (20)

Back-2-Basics: .NET Coding Standards For The Real World (2011)
Back-2-Basics: .NET Coding Standards For The Real World (2011)Back-2-Basics: .NET Coding Standards For The Real World (2011)
Back-2-Basics: .NET Coding Standards For The Real World (2011)
 
Creational Design Patterns
Creational Design PatternsCreational Design Patterns
Creational Design Patterns
 
Rock Your Code with Code Contracts
Rock Your Code with Code ContractsRock Your Code with Code Contracts
Rock Your Code with Code Contracts
 
Strategy Design Pattern
Strategy Design PatternStrategy Design Pattern
Strategy Design Pattern
 
Generics and collections in Java
Generics and collections in JavaGenerics and collections in Java
Generics and collections in Java
 
[2012 02 03]clean_code 4장
[2012 02 03]clean_code 4장[2012 02 03]clean_code 4장
[2012 02 03]clean_code 4장
 
Generic Programming in java
Generic Programming in javaGeneric Programming in java
Generic Programming in java
 
Java Programming - 03 java control flow
Java Programming - 03 java control flowJava Programming - 03 java control flow
Java Programming - 03 java control flow
 
Java căn bản - Chapter8
Java căn bản - Chapter8Java căn bản - Chapter8
Java căn bản - Chapter8
 
Chapter 9 - Characters and Strings
Chapter 9 - Characters and StringsChapter 9 - Characters and Strings
Chapter 9 - Characters and Strings
 
Unit I Advanced Java Programming Course
Unit I   Advanced Java Programming CourseUnit I   Advanced Java Programming Course
Unit I Advanced Java Programming Course
 
One Careful Owner
One Careful OwnerOne Careful Owner
One Careful Owner
 
Chapter 4:Object-Oriented Basic Concepts
Chapter 4:Object-Oriented Basic ConceptsChapter 4:Object-Oriented Basic Concepts
Chapter 4:Object-Oriented Basic Concepts
 
Chapter 7:Understanding Class Inheritance
Chapter 7:Understanding Class InheritanceChapter 7:Understanding Class Inheritance
Chapter 7:Understanding Class Inheritance
 
Making an Exception
Making an ExceptionMaking an Exception
Making an Exception
 
C# for-java-developers
C# for-java-developersC# for-java-developers
C# for-java-developers
 
Lecture 4_Java Method-constructor_imp_keywords
Lecture   4_Java Method-constructor_imp_keywordsLecture   4_Java Method-constructor_imp_keywords
Lecture 4_Java Method-constructor_imp_keywords
 
Java Persistence API
Java Persistence APIJava Persistence API
Java Persistence API
 
Lecture 6 inheritance
Lecture   6 inheritanceLecture   6 inheritance
Lecture 6 inheritance
 
Test Engine
Test EngineTest Engine
Test Engine
 

En vedette

An Apocalypse of Ice; chapter 3
An Apocalypse of Ice; chapter 3An Apocalypse of Ice; chapter 3
An Apocalypse of Ice; chapter 3cobaltazure
 
Share Vision First Trip
Share Vision First TripShare Vision First Trip
Share Vision First TripKhou Suylong
 
Apocalypse of Ice Chapter 12 Part 1
Apocalypse of Ice Chapter 12 Part 1Apocalypse of Ice Chapter 12 Part 1
Apocalypse of Ice Chapter 12 Part 1cobaltazure
 
An Apocalypse of Ice; chapter 7
An Apocalypse of Ice; chapter 7An Apocalypse of Ice; chapter 7
An Apocalypse of Ice; chapter 7cobaltazure
 
Flex_rest_optimization
Flex_rest_optimizationFlex_rest_optimization
Flex_rest_optimizationKhou Suylong
 
TDD sharevison team
TDD sharevison teamTDD sharevison team
TDD sharevison teamKhou Suylong
 

En vedette (8)

An Apocalypse of Ice; chapter 3
An Apocalypse of Ice; chapter 3An Apocalypse of Ice; chapter 3
An Apocalypse of Ice; chapter 3
 
Share Vision First Trip
Share Vision First TripShare Vision First Trip
Share Vision First Trip
 
Aao ichapter11
Aao ichapter11Aao ichapter11
Aao ichapter11
 
Apocalypse of Ice Chapter 12 Part 1
Apocalypse of Ice Chapter 12 Part 1Apocalypse of Ice Chapter 12 Part 1
Apocalypse of Ice Chapter 12 Part 1
 
An Apocalypse of Ice; chapter 7
An Apocalypse of Ice; chapter 7An Apocalypse of Ice; chapter 7
An Apocalypse of Ice; chapter 7
 
Flex_rest_optimization
Flex_rest_optimizationFlex_rest_optimization
Flex_rest_optimization
 
TDD sharevison team
TDD sharevison teamTDD sharevison team
TDD sharevison team
 
Will bc day3
Will bc day3Will bc day3
Will bc day3
 

Similaire à Clean code

Presentacion clean code
Presentacion clean codePresentacion clean code
Presentacion clean codeIBM
 
Working Effectively With Legacy Code
Working Effectively With Legacy CodeWorking Effectively With Legacy Code
Working Effectively With Legacy CodeNaresh Jain
 
Clean code _v2003
 Clean code _v2003 Clean code _v2003
Clean code _v2003R696
 
clean code book summary - uncle bob - English version
clean code book summary - uncle bob - English versionclean code book summary - uncle bob - English version
clean code book summary - uncle bob - English versionsaber tabatabaee
 
Refactoring Tips by Martin Fowler
Refactoring Tips by Martin FowlerRefactoring Tips by Martin Fowler
Refactoring Tips by Martin FowlerIgor Crvenov
 
Addressing Scenario
Addressing ScenarioAddressing Scenario
Addressing ScenarioTara Hardin
 
Tdd is not about testing (OOP)
Tdd is not about testing (OOP)Tdd is not about testing (OOP)
Tdd is not about testing (OOP)Gianluca Padovani
 
20.1 Java working with abstraction
20.1 Java working with abstraction20.1 Java working with abstraction
20.1 Java working with abstractionIntro C# Book
 
INTRODUCTION TO OBJECT ORIENTED PROGRAMMING.pptx
INTRODUCTION TO OBJECT ORIENTED PROGRAMMING.pptxINTRODUCTION TO OBJECT ORIENTED PROGRAMMING.pptx
INTRODUCTION TO OBJECT ORIENTED PROGRAMMING.pptxDeepasCSE
 
Bring the fun back to java
Bring the fun back to javaBring the fun back to java
Bring the fun back to javaciklum_ods
 
TDD And Refactoring
TDD And RefactoringTDD And Refactoring
TDD And RefactoringNaresh Jain
 
I assignmnt(oops)
I assignmnt(oops)I assignmnt(oops)
I assignmnt(oops)Jay Patel
 
DTS s03e02 Handling the code
DTS s03e02 Handling the codeDTS s03e02 Handling the code
DTS s03e02 Handling the codeTuenti
 

Similaire à Clean code (20)

Clean Code
Clean CodeClean Code
Clean Code
 
Clean code
Clean codeClean code
Clean code
 
Presentacion clean code
Presentacion clean codePresentacion clean code
Presentacion clean code
 
Working Effectively With Legacy Code
Working Effectively With Legacy CodeWorking Effectively With Legacy Code
Working Effectively With Legacy Code
 
Clean code _v2003
 Clean code _v2003 Clean code _v2003
Clean code _v2003
 
clean code book summary - uncle bob - English version
clean code book summary - uncle bob - English versionclean code book summary - uncle bob - English version
clean code book summary - uncle bob - English version
 
Clean Code 2
Clean Code 2Clean Code 2
Clean Code 2
 
Refactoring Tips by Martin Fowler
Refactoring Tips by Martin FowlerRefactoring Tips by Martin Fowler
Refactoring Tips by Martin Fowler
 
Clean Code
Clean CodeClean Code
Clean Code
 
Addressing Scenario
Addressing ScenarioAddressing Scenario
Addressing Scenario
 
Tdd is not about testing (OOP)
Tdd is not about testing (OOP)Tdd is not about testing (OOP)
Tdd is not about testing (OOP)
 
Clean code
Clean codeClean code
Clean code
 
20.1 Java working with abstraction
20.1 Java working with abstraction20.1 Java working with abstraction
20.1 Java working with abstraction
 
INTRODUCTION TO OBJECT ORIENTED PROGRAMMING.pptx
INTRODUCTION TO OBJECT ORIENTED PROGRAMMING.pptxINTRODUCTION TO OBJECT ORIENTED PROGRAMMING.pptx
INTRODUCTION TO OBJECT ORIENTED PROGRAMMING.pptx
 
Intake 37 5
Intake 37 5Intake 37 5
Intake 37 5
 
Bring the fun back to java
Bring the fun back to javaBring the fun back to java
Bring the fun back to java
 
Clean code slide
Clean code slideClean code slide
Clean code slide
 
TDD And Refactoring
TDD And RefactoringTDD And Refactoring
TDD And Refactoring
 
I assignmnt(oops)
I assignmnt(oops)I assignmnt(oops)
I assignmnt(oops)
 
DTS s03e02 Handling the code
DTS s03e02 Handling the codeDTS s03e02 Handling the code
DTS s03e02 Handling the code
 

Clean code

  • 1. CLEAN CODE By: Sharevison Team 8º Simpósio Brasileiro de Linguagens de Programação
  • 2. How do you know, how bad your code is?
  • 3. Bjarne Stroustrup, inventor of C++ and author of The C++ Programming Language I like my code to be elegant and efficient. The logic should be straightforward to make it hard for bugs to hide, the dependencies minimal to ease maintenance, error handling complete according to an articulated strategy, and per- formance close to optimal so as not to tempt people to make the code messy with unprinci-pled optimizations. Clean code does one thing well.
  • 4. “Big” Dave Thomas, founder of OTI, godfather of the Eclipse strategy Clean code can be read, and enhanced by a developer other than its original author. It has unit and acceptance tests. It has meaningful names. It provides one way rather than many ways for doing one thing. It has minimal depen dencies, which are explicitly defined, and pro- vides a clear and minimal API. Code should be literate since depending on the language, not all necessary information can be expressed clearly in code alone.
  • 5. Michael Feathers, author of Working Effectively with Legacy Code I could list all of the qualities that I notice in clean code, but there is one overarching quality that leads to all of them. Clean code always looks like it was written by someone who cares. There is nothing obvious that you can do to make it better. All of those things were thought about by the code’s author, and if you try to imagine improvements, you’re led back to where you are, sitting in appreciation of the code someone left for you—code left by some one who cares deeply about the craft.
  • 6. My personal View The code considered to be clean will need these: Well written test (Unit test) for every public methods. A class should be small and does one thing only A method should be small enough( not longer then 20 lines) A method should does only one thing and does it well After all, I should able to hand over my code to other, and they should able to carry on the work.
  • 8. Meaningfull Names Use Intention-Revealing Names: Intention- It should tell you why it exists, what it does, and how it is used. int d; // elapsed time in days OR int elapsedTimeInDays; int daysSinceCreation; int daysSinceModification; int fileAgeInDays;
  • 9. Avoid Disinformation avoid words whose entrenched meanings vary from our intended meaning. Eg. grouping of accounts -> var accountList
  • 10. Use Pronounceable Names class DtaRcrd102 { private Date genymdhms; private Date modymdhms; private final String pszqint = "102"; /* ... */ }; To class Customer { private Date generationTimestamp; private Date modificationTimestamp;; private final String recordId = "102"; /* ... */ };
  • 11. Avoid Encodings Hungarian Notation PhoneNumber phoneString; // name not changed when type changed! Member Prefixes public class Part { private String m_dsc; // The textual description void setName(String name) { m_dsc = name; } } To public class Part { String description; void setDescription(String description) { this.description = description; } }
  • 12. Avoid Mental Mapping Readers shouldn’t have to mentally translate your names into other names they already know. This problem generally arises from a choice to use neither problem domain terms nor solution domain terms. var r; //url var fn; //first name
  • 13. Method Method should be a verbphrase like getAccount, displayTest ...etc.
  • 14. Don’t Be Cute What about this HolyHandGrenade or DeleteItems
  • 15. Pick One Word per Concept Pick one word for one abstract concept and stick with it Eg. Fetch(), retrieve(), get() as equivalent methods of different classes. controller and a manager and a driver in the same code base.
  • 16. Don’t Pun Avoid using the same word for two purposes Eg. add(firstItem, secondItem), concatinat two items. add(newItem), append to existing item
  • 17. Use Solution Domain Names Do not afraid of using computer science team like: Name of patters Algorithm • getMinWidthComposite() •AccountVisitor
  • 18. Add Meaningful Context enclosing them in well-named classes, functions, or namespaces private void thereIsOneLetter() { number = "1"; verb = "is"; pluralModifier = ""; }
  • 19. Function Small, should be hardly every 20 lines long Does one thing, it should does one thing, does it well, and does it only.
  • 20. Function: One Level of Abstraction per Function gtk.Button.prototype.setImage = function(image){ this._widget2 = image; this.resize(this._minWidth, this._minHeight); this._widget2._domObj.style.display = ""; this._imageDom.appendChild(this._widget2._domObj); }; To gtk.Button.prototype.setImage = function(image){ this._widget2 = image; this.resize(this._minWidth, this._minHeight); this.hide(this._widget2); this._appendImage(this._widget2._domObj); }; gtk.Button.prototype.hideWidget = function(widget){ widget._domObj.style.display = ""; }; gtk.Button.prototype.appendImage = function(){ this._imageDom.appendChild(this._widget2._domObj); };
  • 21. Function Arguments What is the best number of arugments passed in: Zero (niladic) Two (dyadic) Three (polyadic) More then this is evil Reasons not to have many arguments: For public methods, user fine it hard to use the method. For private method, it should able to access the class properties, why have to pass in.
  • 22. Function Arguments Flag Arguments: Passing a boolean into a function is a truly terrible practice render(true) OR renderForSuite() and renderForSingleTest()
  • 23. Function Arguments Argument Objects: more than two or three arguments, they ought to be wrapped into a class of their own. Circle makeCircle(double x, double y, double radius); OR Circle(circleProperties);
  • 24. Don’t repeat yourself If you see the same code structure more than one place, then extract the method and invoke the code from both places
  • 25. Switch Statement How to make switch statement does one thing? public Money calculatePay(Employee e) throws InvalidEmployeeType { switch (e.type) { case COMMISSIONED: return calculateCommissionedPay(e); case HOURLY: return calculateHourlyPay(e); case SALARIED: return calculateSalariedPay(e); default: throw new InvalidEmployeeType(e.type); } }
  • 26. Comment Comments Do Not Make Up for Bad Code: “Ooh, I’d better comment that!” No! You’d better clean it!” // Check to see if the employee is eligible for full benefits if ((employee.flags & HOURLY_FLAG) && (employee.age > 65)) OR if (employee.isEligibleForFullBenefits())
  • 28. Comment Legal Comments // Copyright (C) 2003,2004,2005 by Object Mentor, Inc. All rights reserved. // Released under terms of the GNU General Public License version 2 or later. Informative Comments // Returns an instance of the Responder being tested. protected abstract Responder responderInstance(); OR protected abstract Responder getResponderInstance();
  • 29. Warning of Consequences Warning of Consequences // Don't run unless you // have some time to kill. public void _testWithReallyBigFile() { writeLinesToFile(10000000); response.setBody(testFile); response.readyToSend(this); String responseString = output.toString(); assertSubString("Content-Length: 1000000000", responseString); assertTrue(bytesSent > 1000000000); }
  • 30. TODO Comments Leave TODO comment //TODO-MdM these are not needed // We expect this to go away when we do the checkout model protected VersionInfo makeVersion() throws Exception { return null; }
  • 32. Redundant Comments The comment that takes longer to read than the code itself // Utility method that returns when this.closed is true. Throws an exception // if the timeout is reached. public synchronized void waitForClose(final long timeoutMillis) throws Exception { if(!closed) { wait(timeoutMillis); if(!closed) throw new Exception("MockResponseSender could not be closed"); } }
  • 33. Noise Comments Sometimes you see comments that are nothing but noise. They restate the obvious and provide no new information. /** * Returns the day of the month. * * @return the day of the month. */ public int getDayOfMonth() { return dayOfMonth; }
  • 34. Don’t Use a Comment When You Can Use a Function or a Variable // does the module from the global list <mod> depend on the // subsystem we are part of? if (smodule.getDependSubsystems().contains(subSysMod.getSubSystem())) OR ArrayList moduleDependees = smodule.getDependSubsystems(); String ourSubSystem = subSysMod.getSubSystem(); if (moduleDependees.contains(ourSubSystem))
  • 35. Position Markers Mark a particular position in a source file // Actions //////////////////////////////////
  • 36. Class Names Classes and objects should have noun or noun phrase names like Customer, WikiPage, Account, and AddressParser.
  • 37. Reference Clean Code: a hand book of agile software craftmanship by Robert C. Martin Refactoring, Improving the design of existing code by Martin Fowler