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

Clean code

  • 1.
    CLEAN CODE By: Sharevison Team 8º Simpósio Brasileiro de Linguagens de Programação
  • 2.
    How do youknow, how bad your code is?
  • 3.
    Bjarne Stroustrup, inventorof 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, authorof 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 Thecode 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.
  • 7.
  • 8.
    Meaningfull Names Use Intention-RevealingNames: 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 wordswhose 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 Readersshouldn’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 bea verbphrase like getAccount, displayTest ...etc.
  • 14.
    Don’t Be Cute Whatabout this HolyHandGrenade or DeleteItems
  • 15.
    Pick One Wordper 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 usingthe same word for two purposes Eg. add(firstItem, secondItem), concatinat two items. add(newItem), append to existing item
  • 17.
    Use Solution DomainNames Do not afraid of using computer science team like: Name of patters Algorithm • getMinWidthComposite() •AccountVisitor
  • 18.
    Add Meaningful Context enclosingthem in well-named classes, functions, or namespaces private void thereIsOneLetter() { number = "1"; verb = "is"; pluralModifier = ""; }
  • 19.
    Function Small, should behardly every 20 lines long Does one thing, it should does one thing, does it well, and does it only.
  • 20.
    Function: One Levelof 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 isthe 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 Ifyou see the same code structure more than one place, then extract the method and invoke the code from both places
  • 25.
    Switch Statement How tomake 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 NotMake 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())
  • 27.
  • 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 Warningof 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 TODOcomment //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; }
  • 31.
  • 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 yousee 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 aComment 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 aparticular position in a source file // Actions //////////////////////////////////
  • 36.
    Class Names Classes andobjects should have noun or noun phrase names like Customer, WikiPage, Account, and AddressParser.
  • 37.
    Reference Clean Code: ahand book of agile software craftmanship by Robert C. Martin Refactoring, Improving the design of existing code by Martin Fowler