Smelling Your Code
Raju Mazumder
Sr. Software Engineer
Tasawr Interactive

Rubyist, Java and PHP Developer
like to work fun and challenging environment

Web: www.rajumazumder.com
Twitter: @rajuniit
What is Code Smell?
Wikipedia Definition

“ code smell is any symptom in the source code of a program
  that possibly indicates a deeper problem. ”
Speculative Generality

Large Class            Long Method

Dead Code             Comment
Switch Case        Primitive Obsession

    Duplicated Code
          Long Parameter List
   Meaningful Names
Divergent Change      Shotgun Surgery
Dead Code
Harder to comprehend the code base.

Wasted time - reading through, or even changing dead code.



Meaningful Names
public $d; // what does it mean? Days or diameter

public $days; // clean

public function getinvcdtlmt() {
    //do something
}

public function getInvoiceableCreditLimit() {
    //do something
}
Comment is smell

Which one is clearer?

//check is employee active
if ( $employee->isActive() ) {
      //do something;
}

if ( $employee->isActive() ) {
      //do something;
}
Duplicate Code
Code repeated in multiple places.
Bad Example
<?php
function displayPHPExperSpeakerInfo($speakerId)
{
    $speaker = new Speaker();
    $speaker = $speaker->find($speakerId);

   if($speaker->isSixMinuteSpeaker()) {
        $name = $speaker->getName();
        $designation = $speaker->getDesignation();
        echo "Name: ". $name;
        echo "Designation:". $designation;
   } else {
        $name = $speaker->getName();
        $designation = $speaker->getDesignation();
        $topic = $speaker->getTopicName();
        echo "Name:". $name;
        echo "Designation: " . $designation;
        echo "Topic: ". $topic;
   }
}
displayPHPExperSpeakerInfo(2);
Refactor continue...
<?php
function displayPHPExperSpeakerInfo($speakerId)
{
    $speaker = new Speaker();
    $speaker = $speaker->find($speakerId);

    displayGeneralInformation($speaker);

    if ($speaker->isTwelveMinuteSpeaker()) {
          $topic = $speaker->getTopicName();
          echo "Topic: " . $topic;
    }
}
function displayGeneralInformation($speaker)
{
  $name = $speaker->getName();
  $designation = $speaker->getDesignation();
  echo "Name: " . $name;
  echo "Designation:" . $designation;
}

displayPHPExperSpeakerInfo(2);

                            Note: We can imrove it more. Its just an example
Long Method
Longer Methods are difficult to understand
Too many conditions and loops

Long Class
Single responsibility Principle Violated
Bad Example

function gotoPhpExpertsSeminar2011() {
   //wake up morning
    //taking my breakfast
    //take vehicle
    //check confirmation code
   //take a seat
}
Refactor Continue...


function gotoPhpExpertsSeminar2011() {
    wakeUpMorning();
    takeBreakFast();
    takeVehicle();
    checkConfirmationCode();
   takeSeat();
}




                      Note: We can imrove it more. Its just an example
Long Parameter List
Lots of parameters will make code harder to
understand.
Bad Example..
function getSpeakers($type = '', $experience = 0,
  $zce = null, $newSpeaker = null)
{
  $criteria = array();
  if ($type) {
      $criteria[] = "type = '{$type}' ";
  }
  .......
  ........
  if ($criteria) {
      $condition = implode('AND ', $criteria);
  } else {
      $condition = '1=1';
  }
  $speakers = $db->fetchQuery("select * from speakers
           WHERE {$condition}");
  return $speakers;
}

$sixMinuteSpeakers = getSpeakers('six_minute');
$zecSpeakers = getSpeakers('',0,true);
$tweleveMinuteSpeakers = getSpeakers('twelve_minute');
Refactor continue..
function getSpeakersByType($type = 'six_minute')
{
  $speakers = $db->fetchQuery("select * from speakers
         WHERE type = '{$type}'");
  return $speakers;
}

function getZceSpeakers()
{
  $speakers = $db->fetchQuery("select * from speakers
         WHERE zce = 1");
  return $speakers;
}

$sixMinuteSpeakers = getSpeakersByType();
$zecSpeakers = getZceSpeakers();
$tweleveMinuteSpeakers = getSpeakersByType('twelve_minute');




                           Note: We can imrove it more. Its just an example
Refactor continue..
function getSpeakersByOptions(array $options)
{
  $condition = prepareWhere($options);
  $speakers = $db->fetchQuery("select * from speakers
           WHERE {$condition}");
  return $speakers;
}
function prepareWhere($options)
{
  $criteria = array();
  foreach ($options as $option => $value) {
      switch ($option) {
        case 'type': $criteria[] = "type = '{$value}' "; break;
        case 'zce': $criteria[] = "zce = '{$value}' "; break;
        case 'experience': $criteria[] = "experience = '{$value}' "; break;
        default: break;
      }
  }
  if ($criteria) {
      $condition = implode('AND ', $criteria);
  } else {
      $condition = '1=1';
  }
  return $condition;
}                                   Note: We can imrove it more. Its just an example
Refactor Continue...
$options = array('type' => 'six_minute');
$sixFameSpeakers = getSpeakersByOptions($options);

$options = array('zce' => 1);
$zecSpeakers = getSpeakersByOptions($options);

$options = array('type' => 'twelve_minute');
$tweleveMinuteSpeakers = getSpeakersByOptions($options);




                          Note: We can imrove it more. Its just an example
Smell Detection Tools
Phpcpd
https://github.com/sebastianbergmann/phpcpd

PHP Code Sniffer
http://pear.php.net/package/PHP_CodeSniffer/redirected

Phpdepend
http://pdepend.org/download/index.html

phploc
https://github.com/sebastianbergmann/phploc

phpmd
http://phpmd.org/
Resources
Clean Code
– Robert C. Martin
Refactoring: Improved the design of existing code
– Martin Fowler
Thanks
“Code is the mirror of the developer”
“So let's Write Beautiful Code”



Questions?

Smelling your code

  • 1.
    Smelling Your Code RajuMazumder Sr. Software Engineer Tasawr Interactive Rubyist, Java and PHP Developer like to work fun and challenging environment Web: www.rajumazumder.com Twitter: @rajuniit
  • 2.
  • 3.
    Wikipedia Definition “ codesmell is any symptom in the source code of a program that possibly indicates a deeper problem. ”
  • 4.
    Speculative Generality Large Class Long Method Dead Code Comment Switch Case Primitive Obsession Duplicated Code Long Parameter List Meaningful Names Divergent Change Shotgun Surgery
  • 5.
    Dead Code Harder tocomprehend the code base. Wasted time - reading through, or even changing dead code. Meaningful Names public $d; // what does it mean? Days or diameter public $days; // clean public function getinvcdtlmt() { //do something } public function getInvoiceableCreditLimit() { //do something }
  • 6.
    Comment is smell Whichone is clearer? //check is employee active if ( $employee->isActive() ) { //do something; } if ( $employee->isActive() ) { //do something; }
  • 7.
    Duplicate Code Code repeatedin multiple places.
  • 8.
    Bad Example <?php function displayPHPExperSpeakerInfo($speakerId) { $speaker = new Speaker(); $speaker = $speaker->find($speakerId); if($speaker->isSixMinuteSpeaker()) { $name = $speaker->getName(); $designation = $speaker->getDesignation(); echo "Name: ". $name; echo "Designation:". $designation; } else { $name = $speaker->getName(); $designation = $speaker->getDesignation(); $topic = $speaker->getTopicName(); echo "Name:". $name; echo "Designation: " . $designation; echo "Topic: ". $topic; } } displayPHPExperSpeakerInfo(2);
  • 9.
    Refactor continue... <?php function displayPHPExperSpeakerInfo($speakerId) { $speaker = new Speaker(); $speaker = $speaker->find($speakerId); displayGeneralInformation($speaker); if ($speaker->isTwelveMinuteSpeaker()) { $topic = $speaker->getTopicName(); echo "Topic: " . $topic; } } function displayGeneralInformation($speaker) { $name = $speaker->getName(); $designation = $speaker->getDesignation(); echo "Name: " . $name; echo "Designation:" . $designation; } displayPHPExperSpeakerInfo(2); Note: We can imrove it more. Its just an example
  • 10.
    Long Method Longer Methodsare difficult to understand Too many conditions and loops Long Class Single responsibility Principle Violated
  • 11.
    Bad Example function gotoPhpExpertsSeminar2011(){ //wake up morning //taking my breakfast //take vehicle //check confirmation code //take a seat }
  • 12.
    Refactor Continue... function gotoPhpExpertsSeminar2011(){ wakeUpMorning(); takeBreakFast(); takeVehicle(); checkConfirmationCode(); takeSeat(); } Note: We can imrove it more. Its just an example
  • 13.
    Long Parameter List Lotsof parameters will make code harder to understand.
  • 14.
    Bad Example.. function getSpeakers($type= '', $experience = 0, $zce = null, $newSpeaker = null) { $criteria = array(); if ($type) { $criteria[] = "type = '{$type}' "; } ....... ........ if ($criteria) { $condition = implode('AND ', $criteria); } else { $condition = '1=1'; } $speakers = $db->fetchQuery("select * from speakers WHERE {$condition}"); return $speakers; } $sixMinuteSpeakers = getSpeakers('six_minute'); $zecSpeakers = getSpeakers('',0,true); $tweleveMinuteSpeakers = getSpeakers('twelve_minute');
  • 15.
    Refactor continue.. function getSpeakersByType($type= 'six_minute') { $speakers = $db->fetchQuery("select * from speakers WHERE type = '{$type}'"); return $speakers; } function getZceSpeakers() { $speakers = $db->fetchQuery("select * from speakers WHERE zce = 1"); return $speakers; } $sixMinuteSpeakers = getSpeakersByType(); $zecSpeakers = getZceSpeakers(); $tweleveMinuteSpeakers = getSpeakersByType('twelve_minute'); Note: We can imrove it more. Its just an example
  • 16.
    Refactor continue.. function getSpeakersByOptions(array$options) { $condition = prepareWhere($options); $speakers = $db->fetchQuery("select * from speakers WHERE {$condition}"); return $speakers; } function prepareWhere($options) { $criteria = array(); foreach ($options as $option => $value) { switch ($option) { case 'type': $criteria[] = "type = '{$value}' "; break; case 'zce': $criteria[] = "zce = '{$value}' "; break; case 'experience': $criteria[] = "experience = '{$value}' "; break; default: break; } } if ($criteria) { $condition = implode('AND ', $criteria); } else { $condition = '1=1'; } return $condition; } Note: We can imrove it more. Its just an example
  • 17.
    Refactor Continue... $options =array('type' => 'six_minute'); $sixFameSpeakers = getSpeakersByOptions($options); $options = array('zce' => 1); $zecSpeakers = getSpeakersByOptions($options); $options = array('type' => 'twelve_minute'); $tweleveMinuteSpeakers = getSpeakersByOptions($options); Note: We can imrove it more. Its just an example
  • 18.
    Smell Detection Tools Phpcpd https://github.com/sebastianbergmann/phpcpd PHPCode Sniffer http://pear.php.net/package/PHP_CodeSniffer/redirected Phpdepend http://pdepend.org/download/index.html phploc https://github.com/sebastianbergmann/phploc phpmd http://phpmd.org/
  • 19.
    Resources Clean Code – RobertC. Martin Refactoring: Improved the design of existing code – Martin Fowler
  • 20.
    Thanks “Code is themirror of the developer” “So let's Write Beautiful Code” Questions?