SlideShare ist ein Scribd-Unternehmen logo
1 von 132
Downloaden Sie, um offline zu lesen
Your code sucks,
   let’s !x it!
   Object Calisthenics and Code readability




            Rafael Dohms
                 @rdohms
Rafael Dohms




                           photo credit: Eli White
        @rdohms


 Evangelist, Speaker and
      Contributor.

Developer at WEBclusive.

Enabler at AmsterdamPHP.
What’s the talk about?


• Why does my code suck?

• How can we fix it?
Why does my
code suck?
Is it Readable?


Why does my
code suck?
Is it Readable?


Why does my
code suck?
        Is it Testable?
Is it Maintainable?   Is it Readable?


           Why does my
           code suck?
                      Is it Testable?
Is it Maintainable?   Is it Readable?


           Why does my
           code suck?
  Is it Reusable?     Is it Testable?
<?php                                                 Does it look like this?
$list=mysql_connect("******","*******","*****");
if(!$list)echo 'Cannot login.';
else{
    mysql_select_db("******", $list);
    $best=array("0","0","0","0","0","0");
    $id=mysql_num_rows(mysql_query("SELECT * FROM allnews"));
    $count=0;
    for($i=0;$i<6;$i++){
        while(mysql_query("SELECT language FROM allnews WHERE id=$id-$count")!="he")$count+
+;
        $best[$i]=mysql_query("SELECT id FROM allnews WHERE id=$id-$count");}
    $id=$id-$count;
    $maxdate=mktime(0,0,0,date('m'),date('d')-7,date('Y'));
    while(mysql_query("SELECT date FROM allnews WHERE id=$id-$count")>=$maxdate){
        if(mysql_query("SELECT language FROM allnews WHERE id=$id-$count")=="he"){
            $small=$best[0];
            while($i=0;$i<6;$i++){
                if(mysql_query("SELECT score FROM allnews WHERE id=
$small)"<mysql_query("SELECT score FROM allnews WHERE id=$best[i+1]"))
                         $small=$best[i+1];}
                    if(mysql_query("SELECT score FROM allnews WHERE id=
$small")<mysql_query("SELECT score FROM allnews WHERE id=$id-$count")){
                         while($i=0;$i<6;$i++){
                             if($small==$best[i])$best[i]=mysql_query("SELECT id FROM
allnews WHERE id=$id-$count");}}}}
    while($i=0;$i<6;$i++)
    echo '<a href="news-page.php?id='.$best[i].'"><div class="box '.mysql_query("SELECT
type FROM allnews WHERE id=$best[i]").'">'.mysql_query("SELECT title FROM allnews WHERE id=
$best[i]").'<div class="img" style="background-image:url(images/'.mysql_query("SELECT
image1 FROM allnews WHERE id=$best[i]").');"></div></div></a>';
    mysql_close($list);
}
?>
<?php                                                 Does it look like this?
$list=mysql_connect("******","*******","*****");
if(!$list)echo 'Cannot login.';
else{
    mysql_select_db("******", $list);
    $best=array("0","0","0","0","0","0");
    $id=mysql_num_rows(mysql_query("SELECT * FROM allnews"));
    $count=0;
    for($i=0;$i<6;$i++){
        while(mysql_query("SELECT language FROM allnews WHERE id=$id-$count")!="he")$count+
+;
        $best[$i]=mysql_query("SELECT id FROM allnews WHERE id=$id-$count");}
    $id=$id-$count;
    $maxdate=mktime(0,0,0,date('m'),date('d')-7,date('Y'));
    while(mysql_query("SELECT date FROM allnews WHERE id=$id-$count")>=$maxdate){
        if(mysql_query("SELECT language FROM allnews WHERE id=$id-$count")=="he"){
            $small=$best[0];
            while($i=0;$i<6;$i++){
                if(mysql_query("SELECT score FROM allnews WHERE id=
$small)"<mysql_query("SELECT score FROM allnews WHERE id=$best[i+1]"))
                         $small=$best[i+1];}
                    if(mysql_query("SELECT score FROM allnews WHERE id=
$small")<mysql_query("SELECT score FROM Rebecca WHERE id=$id-$count")){
                                      If allnews Black was a developer
                         while($i=0;$i<6;$i++){
                             if($small==$best[i])$best[i]=mysql_query("SELECT id FROM
allnews WHERE id=$id-$count");}}}}
    while($i=0;$i<6;$i++)
    echo '<a href="news-page.php?id='.$best[i].'"><div class="box '.mysql_query("SELECT
type FROM allnews WHERE id=$best[i]").'">'.mysql_query("SELECT title FROM allnews WHERE id=
$best[i]").'<div class="img" style="background-image:url(images/'.mysql_query("SELECT
image1 FROM allnews WHERE id=$best[i]").');"></div></div></a>';
    mysql_close($list);
}
?>
How do we fix it?
Object Calisthenics
cal·is·then·ics - noun - /ˌkaləsˈTHeniks/
     Calisthenics are a form of dynamic
      exercise consisting of a variety of
    simple, often rhythmical, movements,
    generally using minimal equipment or
                  apparatus.



Object Calisthenics
cal·is·then·ics - noun - /ˌkaləsˈTHeniks/
     Calisthenics are a form of dynamic
      exercise consisting of a variety of
    simple, often rhythmical, movements,
    generally using minimal equipment or
                  apparatus.



Object Calisthenics
                             A variety of simple, often
                          rhythmical, exercises to achieve
                           better OO and code quality
“So here’s an exercise that can help you to internalize
      principles of good object-oriented design and actually
                                       use them in real life.”

                                                -- Jeff Bay




Object Calisthenics
“So here’s an exercise that can help you to internalize
      principles of good object-oriented design and actually
                                       use them in real life.”

                                                -- Jeff Bay




Object Calisthenics
                            Important:

                         PHP != JAVA

                    Adaptations will be done
Object Calisthenics
         +
 Readability Tips
“You need to write code that minimizes the time it would


Object Calisthenics
          take someone else to understand it—even if that
                                     someone else is you.”



         +
          -- Dustin Boswell and Trevor Foucher




 Readability Tips
“You need to write code that minimizes the time it would


Object Calisthenics
          take someone else to understand it—even if that
                                     someone else is you.”



         +
          -- Dustin Boswell and Trevor Foucher




 Readability Tips
                                I’m a tip
Disclaimer:
“These are guidelines, not rules”
OC #1
“Only one indentation
  level per method”
function validateProducts($products) {

    // Check to make sure that our valid fields are in there
    $requiredFields = array(
        'price',
        'name',
        'description',
        'type',
    );

    $valid = true;

    foreach ($products as $rawProduct) {

        $fields = array_keys($rawProduct);

        foreach ($requiredFields as $requiredField) {
            if (!in_array($requiredField, $fields)) {
                $valid = false;
            }
        }
    }

    return $valid;
}
function validateProducts($products) {

        // Check to make sure that our valid fields are in there
        $requiredFields = array(
            'price',
            'name',
            'description',
            'type',
        );

        $valid = true;

    0   foreach ($products as $rawProduct) {

            1   $fields = array_keys($rawProduct);

                foreach ($requiredFields as $requiredField) {
                  2 if (!in_array($requiredField, $fields)) {
                      3 $valid = false;
                    }
                }
        }

        return $valid;
}
function validateProducts($products) {

        // Check to make sure that our valid fields are in there
        $requiredFields = array(
            'price',
            'name',
            'description',
            'type',
        );

        $valid = true;

    0   foreach ($products as $rawProduct) {

            1   $fields = array_keys($rawProduct);

                foreach ($requiredFields as $requiredField) {
                  2 if (!in_array($requiredField, $fields)) {
                      3 $valid = false;
                    }
                }
        }

        return $valid;
}
function validateProducts($products) {

    // Check to make sure that our valid fields are in there
    $requiredFields = array(
        'price',
        'name',
        'description',
        'type',
    );

    $valid = true;

    foreach ($products as $rawProduct) {
        $validationResult = validateSingleProduct($rawProduct, $requiredFields);

        if ( ! $validationResult){
            $valid = false;
        }
    }

    return $valid;
}

function validateSingleProduct($product, $requiredFields)
{
    $valid = true;

    $fields = array_keys($rawProduct);

    foreach ($requiredFields as $requiredField) {
        if (!in_array($requiredField, $fields)) {
            $valid = false;
        }
    }
    return $valid;
}
function validateProducts($products) {

    // Check to make sure that our valid fields are in there
    $requiredFields = array(
        'price',
        'name',
        'description',
        'type',
    );

    $valid = true;

        whitespace
    foreach ($products as $rawProduct) {
        $validationResult = validateSingleProduct($rawProduct, $requiredFields);

        if ( ! $validationResult){
            $valid = false;
        }
    }

    return $valid;
}

function validateSingleProduct($product, $requiredFields)
{
    $valid = true;

    $fields = array_keys($rawProduct);

    foreach ($requiredFields as $requiredField) {
        if (!in_array($requiredField, $fields)) {
            $valid = false;
        }
    }
    return $valid;
}
function validateProducts($products) {

    // Check to make sure that our valid fields are in there
    $requiredFields = array(
        'price',
        'name',
        'description',
        'type',
    );

    $valid = true;

        whitespace
    foreach ($products as $rawProduct) {
        $validationResult = validateSingleProduct($rawProduct, $requiredFields);

        if ( ! $validationResult){
            $valid = false;
        }
    }

    return $valid;
}

function validateSingleProduct($product, $requiredFields)
{
    $valid = true;         duplicated logic
    $fields = array_keys($rawProduct);

    foreach ($requiredFields as $requiredField) {
        if (!in_array($requiredField, $fields)) {
            $valid = false;
        }
    }
    return $valid;
}
function validateProducts($products) {

      // Check to make sure that our valid fields are in there
      $requiredFields = array(
          'price',
          'name',
          'description',
          'type',
      );

      $valid = true;

    0 foreach ($products as
          whitespace
          $validationResult
                                $rawProduct) {
                                = validateSingleProduct($rawProduct, $requiredFields);

          1   if ( ! $validationResult){

              }
               2  $valid = false;

      }

      return $valid;
}

function validateSingleProduct($product, $requiredFields)
{
    $valid = true;               duplicated logic
      $fields = array_keys($rawProduct);

    0 foreach(!in_array($requiredField, $fields))
              ($requiredFields as $requiredField)     {

        1 if                                          {

          } 2
              $valid = false;

      }
      return $valid;
}
function validateProducts($products) {

      // Check to make sure that our valid fields are in there
      $requiredFields = array(
          'price',
          'name',
          'description',
          'type',
      );

      $valid = true;

    0 foreach ($products as
          $validationResult
                                $rawProduct) {
                                = validateSingleProduct($rawProduct, $requiredFields);

          1   if ( ! $validationResult){

              }
               2  $valid = false;

      }

      return $valid;
}

function validateSingleProduct($product, $requiredFields)
{
    $valid = true;

      $fields = array_keys($rawProduct);

    0 foreach(!in_array($requiredField, $fields))
              ($requiredFields as $requiredField)     {

        1 if                                          {

          } 2
              $valid = false;

      }
      return $valid;
}
function validateProducts($products) {

      // Check to make sure that our valid fields are in there
      $requiredFields = array(
          'price',
          'name',
          'description',
          'type',
      );

      $valid = true;

    0 foreach ($products as
          $validationResult
                                $rawProduct) {
                                = validateSingleProduct($rawProduct, $requiredFields);

          1   if ( ! $validationResult){

              }
               2  $valid = false;

      }

      return $valid;
}

function validateSingleProduct($product, $requiredFields)
{
    $valid = true;

      $fields = array_keys($rawProduct);

    0 foreach(!in_array($requiredField, $fields))
              ($requiredFields as $requiredField)     {

        1 if                                          {

          } 2
              $valid = false;

      }
      return $valid;
}
function validateProducts($storeData) {

    $requiredFields = array('price','name','description','type');

    foreach ($storeData['products'] as $rawProduct) {
        if ( ! validateSingleProduct($rawProduct, $requiredFields)) return false;
    }

    return true;
}

function validateSingleProduct($product, $requiredFields)
{
    $fields = array_keys($rawProduct);
    $missingFields = array_diff($requiredFields, $fields);

    return (count($missingFields) == 0);
}
function validateProducts($storeData) {

    $requiredFields = array('price','name','description','type'); cheating!
                                                            I see
    foreach ($storeData['products'] as $rawProduct) {
        if ( ! validateSingleProduct($rawProduct, $requiredFields)) return false;
    }

    return true;
}

function validateSingleProduct($product, $requiredFields)
{
    $fields = array_keys($rawProduct);
    $missingFields = array_diff($requiredFields, $fields);

    return (count($missingFields) == 0);
}
function validateProducts($storeData) {

    $requiredFields = array('price','name','description','type'); cheating!
                                                            I see
    foreach ($storeData['products'] as $rawProduct) {
        if ( ! validateSingleProduct($rawProduct, $requiredFields)) return false;
    }

    return true;   Single line IF, simple operations
}

function validateSingleProduct($product, $requiredFields)
{
    $fields = array_keys($rawProduct);
    $missingFields = array_diff($requiredFields, $fields);

    return (count($missingFields) == 0);
}
function validateProducts($storeData) {

    $requiredFields = array('price','name','description','type');

    foreach ($storeData['products'] as $rawProduct) {
        if ( ! validateSingleProduct($rawProduct, $requiredFields)) return false;
    }

    return true;   Single line IF, simple operations         return early
}

function validateSingleProduct($product, $requiredFields)
{
    $fields = array_keys($rawProduct);
    $missingFields = array_diff($requiredFields, $fields);

    return (count($missingFields) == 0);
}
function validateProducts($storeData) {

    $requiredFields = array('price','name','description','type');

    foreach ($storeData['products'] as $rawProduct) {
        if ( ! validateSingleProduct($rawProduct, $requiredFields)) return false;
    }

    return true;   Single line IF, simple operations         return early
}

function validateSingleProduct($product, $requiredFields)
{
    $fields = array_keys($rawProduct);
    $missingFields = array_diff($requiredFields, $fields);

    return (count($missingFields) == 0);
}                        C (native) functions are
                             faster then PHP
function validateProducts($storeData) {

    $requiredFields = array('price','name','description','type');

    foreach ($storeData['products'] as $rawProduct) {
        if ( ! validateSingleProduct($rawProduct, $requiredFields)) return false;
    }

    return true;
}

function validateSingleProduct($product, $requiredFields)
{
    $fields = array_keys($rawProduct);
    $missingFields = array_diff($requiredFields, $fields);

    return (count($missingFields) == 0);
}
function validateProducts($storeData) {

    $requiredFields = array('price','name','description','type');

    foreach ($storeData['products'] as $rawProduct) {
        if ( ! validateSingleProduct($rawProduct, $requiredFields)) return false;
    }

    return true;
}

function validateSingleProduct($product, $requiredFields)
{
    $fields = array_keys($rawProduct);
    $missingFields = array_diff($requiredFields, $fields);

    return (count($missingFields) == 0);
}
function validateProductList($products)
{
    $invalidProducts = array_filter($products, 'isInvalidProduct');

    return (count($invalidProducts) === 0);
}




function isInvalidProduct($rawProduct)
{
    $requiredFields = array('price', 'name', 'description', 'type');

    $fields          = array_keys($rawProduct);
    $missingFields   = array_diff($requiredFields, $fields);

    return (count($missingFields) > 0);
}
function validateProductList($products) iteration
                                   faster
{
    $invalidProducts = array_filter($products, 'isInvalidProduct');

    return (count($invalidProducts) === 0);
}




function isInvalidProduct($rawProduct)
{
    $requiredFields = array('price', 'name', 'description', 'type');

    $fields          = array_keys($rawProduct);
    $missingFields   = array_diff($requiredFields, $fields);

    return (count($missingFields) > 0);
}
function validateProductList($products) iteration
                                   faster
{
    $invalidProducts = array_filter($products, 'isInvalidProduct');

    return (count($invalidProducts) === 0);
}


          reusable method
function isInvalidProduct($rawProduct)
{
    $requiredFields = array('price', 'name', 'description', 'type');

    $fields          = array_keys($rawProduct);
    $missingFields   = array_diff($requiredFields, $fields);

    return (count($missingFields) > 0);
}
function validateProductList($products) iteration
                                   faster
{
    $invalidProducts = array_filter($products, 'isInvalidProduct');

    return (count($invalidProducts) === 0);
}


          reusable method
function isInvalidProduct($rawProduct)
{
    $requiredFields = array('price', 'name', 'description', 'type');

    $fields          = array_keys($rawProduct);
    $missingFields   = array_diff($requiredFields, $fields);

    return (count($missingFields) > 0);
}

                          method name matches “true” result
function validateProductList($products) iteration
                                   faster
{
    $invalidProducts = array_filter($products, 'isInvalidProduct');

    return (count($invalidProducts) === 0);
}
                                    readable return: zero invalid products
          reusable method
function isInvalidProduct($rawProduct)
{
    $requiredFields = array('price', 'name', 'description', 'type');

    $fields          = array_keys($rawProduct);
    $missingFields   = array_diff($requiredFields, $fields);

    return (count($missingFields) > 0);
}

                          method name matches “true” result
List is more readable the plural

function validateProductList($products) iteration
                                   faster
{
    $invalidProducts = array_filter($products, 'isInvalidProduct');

    return (count($invalidProducts) === 0);
}
                                       readable return: zero invalid products
           reusable method
function isInvalidProduct($rawProduct)
{
    $requiredFields = array('price', 'name', 'description', 'type');

    $fields          = array_keys($rawProduct);
    $missingFields   = array_diff($requiredFields, $fields);

    return (count($missingFields) > 0);
}

                           method name matches “true” result
Key Benefits

• Cohesiveness
• Methods does only one thing
• Increases re-use
OC #2
“Do not use the ‘else’
     keyword”
public function createPost($request)
{
    $entity = new Post();

    $form = new MyForm($entity);
    $form->bind($request);

    if ($form->isValid()){

        $repository = $this->getRepository('MyBundle:Post');
        if (!$repository->exists($entity) ) {
            $repository->save($entity);
            return $this->redirect('create_ok');
        } else {
            $error = "Post Title already exists";
            return array('form' => $form, 'error' => $error);
        }

    } else {
        $error = "Invalid fields";
        return array('form' => $form, 'error' => $error);
    }

}
public function createPost($request)
{
    $entity = new Post();

    $form = new MyForm($entity);
    $form->bind($request);

    if ($form->isValid()){

        $repository = $this->getRepository('MyBundle:Post');
        if (!$repository->exists($entity) ) {
            $repository->save($entity);
            return $this->redirect('create_ok');
        } else {
            $error = "Post Title already exists";
            return array('form' => $form, 'error' => $error);
        }

    } else {
        $error = "Invalid fields";
        return array('form' => $form, 'error' => $error);
    }

}
public function createPost($request)
{
    $entity = new Post();

    $form = new MyForm($entity);
    $form->bind($request);

    if ($form->isValid()){

        $repository = $this->getRepository('MyBundle:Post');
        if (!$repository->exists($entity) ) {
            $repository->save($entity);
            return $this->redirect('create_ok');
        } else {
            $error = "Post Title already exists";
            return array('form' => $form, 'error' => $error);
        }

    } else {
        $error = "Invalid fields";
        return array('form' => $form, 'error' => $error);
    }

}
public function createPost($request)
{
    $entity = new Post();

    $form = new MyForm($entity);
    $form->bind($request);

    if ($form->isValid()){

        $repository = $this->getRepository('MyBundle:Post');
        if (!$repository->exists($entity) ) {
            $repository->save($entity);
            return $this->redirect('create_ok');
        } else {
            $error = "Post Title already exists";
            return array('form' => $form, 'error' => $error);
        }

    } else {
        $error = "Invalid fields";
        return array('form' => $form, 'error' => $error);
    }

}
public function createPost($request)
{
    $entity = new Post();

    $form = new MyForm($entity);
    $form->bind($request);

    if ($form->isValid()){

        $repository = $this->getRepository('MyBundle:Post');
        if (!$repository->exists($entity) ) {
            $repository->save($entity);
            return $this->redirect('create_ok');
        } else {
            $error = "Post Title already exists";
            return array('form' => $form, 'error' => $error);
        }

    } else {
        $error = "Invalid fields";
        return array('form' => $form, 'error' => $error);
    }

}
public function createPost($request)
{
    $entity = new Post();

    $form = new MyForm($entity);
    $form->bind($request);

    if ($form->isValid()){

        $repository = $this->getRepository('MyBundle:Post');
        if (!$repository->exists($entity) ) {
            $repository->save($entity);
            return $this->redirect('create_ok');
        } else {
            $error = "Post Title already exists";
            return array('form' => $form, 'error' => $error);
        }

    } else {
        $error = "Invalid fields";
        return array('form' => $form, 'error' => $error);
    }

}
public function createPost($request)
{
    $entity = new Post();

    $form = new MyForm($entity);
    $form->bind($request);

    if ($form->isValid()){

        $repository = $this->getRepository('MyBundle:Post');
        if (!$repository->exists($entity) ) {
            $repository->save($entity);
            return $this->redirect('create_ok');
        } else {
            $error = "Post Title already exists";
            return array('form' => $form, 'error' => $error);
        }

    } else {
        $error = "Invalid fields";
        return array('form' => $form, 'error' => $error);
    }

}
public function createPost($request)
{
    $entity = new Post();

    $form = new MyForm($entity);
    $form->bind($request);

    if ($form->isValid()){

        $repository = $this->getRepository('MyBundle:Post');
        if (!$repository->exists($entity) ) {
             $repository->save($entity);
         intermediate variable
             return $this->redirect('create_ok');
        } else {
             $error = "Post Title already exists";
             return array('form' => $form, 'error' => $error);
        }
    intermediate variable
    } else {
        $error = "Invalid fields";
        return array('form' => $form, 'error' => $error);
    }

}
public function createPost($request)
{
    $entity     = new Post();
    $repository = $this->getRepository('MyBundle:Post');

    $form = new MyForm($entity);
    $form->bind($request);

    if ( ! $form->isValid()){
        return array('form' => $form, 'error' => 'Invalid fields');
    }

    if ($repository->exists($entity)){
        return array('form' => $form, 'error' => 'Duplicate post title');
    }

    $repository->save($entity);

    return $this->redirect('create_ok');

}
public function createPost($request)
{
    $entity     = new Post();
    $repository = $this->getRepository('MyBundle:Post');

    $form = new MyForm($entity);
    $form->bind($request);

    if ( ! $form->isValid()){
        return array('form' => $form, 'error' => 'Invalid fields');
    }

    if ($repository->exists($entity)){
        return array('form' => $form, 'error' => 'Duplicate post title');
    }

    $repository->save($entity);

    return $this->redirect('create_ok');

}
public function createPost($request)
{
    $entity     = new Post();
    $repository = $this->getRepository('MyBundle:Post');

    $form = new MyForm($entity);
    $form->bind($request);
                                           removed intermediates
    if ( ! $form->isValid()){
        return array('form' => $form, 'error' => 'Invalid fields');
    }

    if ($repository->exists($entity)){
        return array('form' => $form, 'error' => 'Duplicate post title');
    }

    $repository->save($entity);

    return $this->redirect('create_ok');

}
public function createPost($request)
{
    $entity     = new Post();
    $repository = $this->getRepository('MyBundle:Post');

      $form = new MyForm($entity);
      $form->bind($request);
                                             removed intermediates
      if ( ! $form->isValid()){
          return array('form' => $form, 'error' => 'Invalid fields');
      }
    early return
      if ($repository->exists($entity)){
          return array('form' => $form, 'error' => 'Duplicate post title');
      }

      $repository->save($entity);

      return $this->redirect('create_ok');

}
Separate code
                                                              into blocks.
public function createPost($request)
{                                                             Its like using
    $entity     = new Post();
    $repository = $this->getRepository('MyBundle:Post');     Paragraphs.
      $form = new MyForm($entity);
      $form->bind($request);
                                             removed intermediates
      if ( ! $form->isValid()){
          return array('form' => $form, 'error' => 'Invalid fields');
      }
    early return
      if ($repository->exists($entity)){
          return array('form' => $form, 'error' => 'Duplicate post title');
      }

      $repository->save($entity);

      return $this->redirect('create_ok');

}
Key Benefits


• Helps avoid code duplication

• Makes code clearer (single path)
Ad
                       ap
         OC #3




                         te
                           d
   “Wrap all primitive
types and string, if it has
       behaviour”
class UIComponent
{
//...
    public function repaint($animate = true){
            //...
    }
}

//...
$component->repaint(false);
class UIComponent
{
//...
    public function repaint($animate = true){
            //...
    }
}

//...
$component->repaint(false);
class UIComponent
{
//...
    public function repaint($animate = true){
            //...
    }
}

//...
$component->repaint(false);


                  unclear operation
class UIComponent
{
    //...
    public function repaint( Animate $animate ){
            //...
    }
}

class Animate
{
    public $animate;

    public function __construct( $animate = true ) {
        $this->animate = $animate;}

}

//...
$component->repaint( new Animate(false) );
class UIComponent
{
    //...
    public function repaint( Animate $animate ){
            //...
    }
}

class Animate
                  This can now encapsulate all
{
                  animation related operations
    public $animate;

    public function __construct( $animate = true ) {
        $this->animate = $animate;}

}

//...
$component->repaint( new Animate(false) );
Key Benefits


• Type Hinting

• Encapsulation of operations
Ad
                       ap
                        te
                            d
        OC #4
“Only one -> per line, if
 not getter or fluent”
Source: CodeIgniter




$this->base_url = $this->CI->config->site_url().'/'.$this->CI->uri->segment(1).$this-
>CI->uri->slash_segment(2, 'both');




$this->base_uri = $this->CI->uri->segment(1).$this->CI->uri->slash_segment(2, 'leading');
Source: CodeIgniter




                         properties are harder to mock
$this->base_url = $this->CI->config->site_url().'/'.$this->CI->uri->segment(1).$this-
>CI->uri->slash_segment(2, 'both');




$this->base_uri = $this->CI->uri->segment(1).$this->CI->uri->slash_segment(2, 'leading');
Source: CodeIgniter




                         properties are harder to mock
$this->base_url = $this->CI->config->site_url().'/'.$this->CI->uri->segment(1).$this-
>CI->uri->slash_segment(2, 'both');


                                              no whitespace
$this->base_uri = $this->CI->uri->segment(1).$this->CI->uri->slash_segment(2, 'leading');
Source: CodeIgniter




                         properties are harder to mock
$this->base_url = $this->CI->config->site_url().'/'.$this->CI->uri->segment(1).$this-
>CI->uri->slash_segment(2, 'both');


                                              no whitespace
$this->base_uri = $this->CI->uri->segment(1).$this->CI->uri->slash_segment(2, 'leading');




                   - Underlying encapsulation problem
                   - Hard to debug and test
                   - Hard to read and understand
Source: CodeIgniter




                         properties are harder to mock
$this->base_url = $this->CI->config->site_url().'/'.$this->CI->uri->segment(1).$this-
>CI->uri->slash_segment(2, 'both');


                                              no whitespace
$this->base_uri = $this->CI->uri->segment(1).$this->CI->uri->slash_segment(2, 'leading');



                            move everything to uri object

       $this->getCI()->getUriBuilder()->getBaseUri(‘leading’);



                   - Underlying encapsulation problem
                   - Hard to debug and test
                   - Hard to read and understand
Source: Zend Framework App




$filterChain->addFilter(new Zend_Filter_Alpha())
            ->addFilter(new Zend_Filter_StringToLower());




                                                            Source: Symfony 2 Docs.
Source: Zend Framework App




    fluent interface
$filterChain->addFilter(new Zend_Filter_Alpha())
            ->addFilter(new Zend_Filter_StringToLower());




                                                            Source: Symfony 2 Docs.
Source: Zend Framework App




    fluent interface
$filterChain->addFilter(new Zend_Filter_Alpha())
            ->addFilter(new Zend_Filter_StringToLower());


      operator alignment




                                                            Source: Symfony 2 Docs.
Source: Zend Framework App




    fluent interface
$filterChain->addFilter(new Zend_Filter_Alpha())
            ->addFilter(new Zend_Filter_StringToLower());


      operator alignment




  $user = $this->get('security.context')->getToken()->getUser();




                                                            Source: Symfony 2 Docs.
Source: Zend Framework App




    fluent interface
$filterChain->addFilter(new Zend_Filter_Alpha())
            ->addFilter(new Zend_Filter_StringToLower());


      operator alignment




                                     only getters (no operations)

  $user = $this->get('security.context')->getToken()->getUser();




                                                            Source: Symfony 2 Docs.
Source: Zend Framework App




    fluent interface
$filterChain->addFilter(new Zend_Filter_Alpha())
            ->addFilter(new Zend_Filter_StringToLower());


      operator alignment




                                     only getters (no operations)

  $user = $this->get('security.context')->getToken()->getUser();




                                                            Source: Symfony 2 Docs.
Source: Zend Framework App




    fluent interface
$filterChain->addFilter(new Zend_Filter_Alpha())
            ->addFilter(new Zend_Filter_StringToLower());


      operator alignment




                                     only getters (no operations)

  $user = $this->get('security.context')->getToken()->getUser();


               where did my
             autocomplete go?

                                                            Source: Symfony 2 Docs.
Source: Zend Framework App




    fluent interface
$filterChain->addFilter(new Zend_Filter_Alpha())
            ->addFilter(new Zend_Filter_StringToLower());


      operator alignment




                                     only getters (no operations)

  $user = $this->get('security.context')->getToken()->getUser();


               where did my                  return null?
             autocomplete go?

                                                            Source: Symfony 2 Docs.
Key Benefits

• Readability
• Easier Mocking

• Easier to Debug
• Demeter’s Law
OC #5
“Do not Abbreviate”
if($sx >= $sy) {
    if ($sx > $strSysMatImgW) {
        $ny = $strSysMatImgW * $sy / $sx;
        $nx = $strSysMatImgW;
    }

    if ($ny > $strSysMatImgH) {
        $nx = $strSysMatImgH * $sx / $sy;
        $ny = $strSysMatImgH;
    }

} else {

    if ($sy > $strSysMatImgH) {
        $nx = $strSysMatImgH * $sx / $sy;
        $ny = $strSysMatImgH;
    }

    if($nx > $strSysMatImgW) {
        $ny = $strSysMatImgW * $sy / $sx;
        $nx = $strSysMatImgW;
    }
}
?
if($sx >= $sy) {                      ?
    if ($sx > $strSysMatImgW) {
        $ny = $strSysMatImgW * $sy / $sx;
        $nx = $strSysMatImgW;
    }
                                ?
    if ($ny > $strSysMatImgH) {
        $nx = $strSysMatImgH * $sx / $sy;
        $ny = $strSysMatImgH;
    }

} else {

         ?
    if ($sy > $strSysMatImgH) {
        $nx = $strSysMatImgH * $sx / $sy;
        $ny = $strSysMatImgH;
    }

         ?
    if($nx > $strSysMatImgW) {
        $ny = $strSysMatImgW * $sy / $sx;
        $nx = $strSysMatImgW;
    }
}
Why?
Why?


Its repeated many times,
       and i’m lazy.
Why?


Its repeated many times,
       and i’m lazy.
                  Underlying Problem!

  You need to transfer those operations into a separate class.
Why?

function processResponseHeadersAndDefineOutput($response) { ... }
Why?

function processResponseHeadersAndDefineOutput($response) { ... }




      This method name is too long to type,
                 and i’m lazy.
Why?
                          more then one
                          responsibility?

function processResponseHeadersAndDefineOutput($response) { ... }




      This method name is too long to type,
                 and i’m lazy.
function getPage($data) { ... }




function startProcess() { ... }




$tr->process(“site.login”);
get from where?
function getPage($data) { ... }




function startProcess() { ... }




$tr->process(“site.login”);
get from where?
                                  Use clearer names:
function getPage($data) { ... }   fetchPage()
                                  downloadPage()




function startProcess() { ... }




$tr->process(“site.login”);
get from where?
                                  Use clearer names:
function getPage($data) { ... }   fetchPage()
                                  downloadPage()




                                  Use a thesaurus:
function startProcess() { ... }
                                  fork, create, begin, open




$tr->process(“site.login”);
get from where?
                                  Use clearer names:
function getPage($data) { ... }   fetchPage()
                                  downloadPage()




                                  Use a thesaurus:
function startProcess() { ... }
                                  fork, create, begin, open


      Table row?

$tr->process(“site.login”);
get from where?
                                  Use clearer names:
function getPage($data) { ... }   fetchPage()
                                  downloadPage()




                                  Use a thesaurus:
function startProcess() { ... }
                                  fork, create, begin, open


      Table row?
                                  Easy understanding, complete scope:
$tr->process(“site.login”);
                                  $translatorService
Key Benefits


• Clearer communication

• Indicates underlying problems
Ad
                 ap
                     te
                     d
     OC #6
“Keep your classes
     small”
100 lines per class
15 classes per package
Increased to include
    docblocks



  100 lines per class
15 classes per package
Increased to include
    docblocks          15-20 lines per method



  100 lines per class
15 classes per package
Increased to include
    docblocks          15-20 lines per method



  100 lines per class
15 classes per package
                           read this as
                       namespace or folder
Key Benefits

• Single Responsibility
• Objective methods

• Slimmer namespaces
• Less clunky folders
Ad
                     ap
         OC #7




                      te
                          d
 “Limit the number of
instance variables in a
   class (max: 2 5)”
class MyRegistrationService
{

    protected   $userService;
    protected   $passwordService;
    protected   $logger;
    protected   $translator;
    protected   $entityManager;
    protected   $imageCropper;

    // ...
}
class MyRegistrationService
{

    protected   $userService;
    protected   $passwordService;
    protected   $logger;
    protected   $translator;
    protected   $entityManager;
    protected   $imageCropper;

    // ...
}




       Limit: 5
class MyRegistrationService
                     {

                         protected   $userService;
                         protected   $passwordService;
                         protected   $logger;
All DB interaction       protected   $translator;
   should be in          protected   $entityManager;
    userService          protected   $imageCropper;    Use and event based
                                                      system and move this
                         // ...                             to listener
                     }




                            Limit: 5
Key Benefits


• Shorter dependency list

• Easier Mocking for unit test
OC #8
“Use first class
 collections”
Doctrine:
      ArrayCollection


$collection->getIterator();

$collection->filter(...);

$collection->append(...);

$collection->map(...);
Key Benefits


• Implements collection operations

• Uses SPL interfaces
Dr
                   op
                    pe
                        d
        OC #9
“Do not use accessors
  (getter/setter)”
/**
  * THIS CLASS WAS GENERATED BY THE DOCTRINE ORM. DO NOT EDIT THIS FILE.
  */
class DoctrineTestsModelsCMSCmsUserProxy
    extends DoctrineTestsModelsCMSCmsUser
    implements DoctrineORMProxyProxy
{

    public function getId()
    {
        $this->__load();
        return parent::getId();
    }

    public function getStatus()
    {
        $this->__load();
        return parent::getStatus();
    }
/**
  * THIS CLASS WAS GENERATED BY THE DOCTRINE ORM. DO NOT EDIT THIS FILE.
  */
class DoctrineTestsModelsCMSCmsUserProxy
    extends DoctrineTestsModelsCMSCmsUser
    implements DoctrineORMProxyProxy
{

    public function getId()
    {
        $this->__load();          Example: Doctrine uses getters to
        return parent::getId();     inject lazy loading operations
    }

    public function getStatus()
    {
        $this->__load();
        return parent::getStatus();
    }
Key Benefits


• Injector operations

• Encapsulation of transformations
Cr
                   ea
                    te
                        d!
   OC #10 (bonus!)
“Document your code!”
//check to see if the section above set the $overall_pref variable to void
if ($overall_pref == 'void')




// implode the revised array of selections in group three into a string
// variable so that it can be transferred to the database at the end of the
// page
$groupthree = implode($groupthree_array, "nr");
really?

//check to see if the section above set the $overall_pref variable to void
if ($overall_pref == 'void')




// implode the revised array of selections in group three into a string
// variable so that it can be transferred to the database at the end of the
// page
$groupthree = implode($groupthree_array, "nr");
really?

//check to see if the section above set the $overall_pref variable to void
if ($overall_pref == 'void')




// implode the revised array of selections in group three into a string
// variable so that it can be transferred to the database at the end of the
// page
$groupthree = implode($groupthree_array, "nr");


         Documenting because i’m doing it wrong in an anusual way
$priority = isset($event['priority']) ? $event['priority'] : 0;

if (!isset($event['event'])) {
    throw new InvalidArgumentException(...));
}

if (!isset($event['method'])) {
    $event['method'] = 'on'.preg_replace(array(
      '/(?<=b)[a-z]/ie',
      '/[^a-z0-9]/i'
    ), array('strtoupper("0")', ''), $event['event']);
}

$definition->addMethodCall(
   'addListenerService',
   array($event['event'],
   array($listenerId,
   $event['method']),
   $priority
));




                                                                  Source: Symfony2
$priority = isset($event['priority']) ? $event['priority'] : 0;

if (!isset($event['event'])) {
    throw new InvalidArgumentException(...));
}

if (!isset($event['method'])) {
    $event['method'] = 'on'.preg_replace(array(
      '/(?<=b)[a-z]/ie',
      '/[^a-z0-9]/i'
    ), array('strtoupper("0")', ''), $event['event']);
}

$definition->addMethodCall(
   'addListenerService',
   array($event['event'],
   array($listenerId,               What does this do?
   $event['method']),
   $priority
));




                                                                  Source: Symfony2
$priority = isset($event['priority']) ? $event['priority'] : 0;
                            Add a simple comment:
if   (!isset($event['event'])) {
      throw new //Strips special chars and camel cases to onXxx
                 InvalidArgumentException(...));
}

if (!isset($event['method'])) {
    $event['method'] = 'on'.preg_replace(array(
      '/(?<=b)[a-z]/ie',
      '/[^a-z0-9]/i'
    ), array('strtoupper("0")', ''), $event['event']);
}

$definition->addMethodCall(
   'addListenerService',
   array($event['event'],
   array($listenerId,                   What does this do?
   $event['method']),
   $priority
));




                                                                  Source: Symfony2
$priority = isset($event['priority']) ? $event['priority'] : 0;
                            Add a simple comment:
if   (!isset($event['event'])) {
      throw new //Strips special chars and camel cases to onXxx
                 InvalidArgumentException(...));
}

if (!isset($event['method'])) {
    $event['method'] = 'on'.preg_replace(array(
                                                    Don’t explain bad
      '/(?<=b)[a-z]/ie',                               code, fix it!
      '/[^a-z0-9]/i'
    ), array('strtoupper("0")', ''), $event['event']);
}

$definition->addMethodCall(
   'addListenerService',
   array($event['event'],
   array($listenerId,                   What does this do?
   $event['method']),
   $priority
));




                                                                  Source: Symfony2
/**
* Checks whether an element is contained in the collection.
* This is an O(n) operation, where n is the size of the collection.
*
* @todo implement caching for better performance
* @param mixed $element The element to search for.
* @return boolean TRUE if the collection contains the element, or FALSE.
*/
function contains($element);
/**
* Checks whether an element is contained in the collection.
* This is an O(n) operation, where n is the size of the collection.
*
* @todo implement caching for better performance
* @param mixed $element The element to search for.
* @return boolean TRUE if the collection contains the element, or FALSE.
*/
function contains($element);


   mark todo items so the
    changes don’t get lost
A note on cost of
       running function
/**
* Checks whether an element is contained in the collection.
* This is an O(n) operation, where n is the size of the collection.
*
* @todo implement caching for better performance
* @param mixed $element The element to search for.
* @return boolean TRUE if the collection contains the element, or FALSE.
*/
function contains($element);


   mark todo items so the
    changes don’t get lost
Do a mind dump,
                                                       then clean it up.
      A note on cost of
       running function
/**
* Checks whether an element is contained in the collection.
* This is an O(n) operation, where n is the size of the collection.
*
* @todo implement caching for better performance
* @param mixed $element The element to search for.
* @return boolean TRUE if the collection contains the element, or FALSE.
*/
function contains($element);


   mark todo items so the
    changes don’t get lost
Do a mind dump,
                                                       then clean it up.
      A note on cost of
       running function
/**
* Checks whether an element is contained in the collection.
* This is an O(n) operation, where n is the size of the collection.
*
* @todo implement caching for better performance
* @param mixed $element The element to search for.
* @return boolean TRUE if the collection contains the element, or FALSE.
*/
function contains($element);
                                                  Generate API docs
                                                    ex: docBlox
   mark todo items so the
    changes don’t get lost
Key Benefits

• Automatic API documentation
• Transmission of “line of thought”
• Avoids confusion
Recap
•   #1 - Only one indentation level per method.

•   #2 - Do not use the ‘else’ keyword.

•   #3 - Wrap primitive types and string, if it has behavior.

•   #4 - Only one -> per line, if not getter or fluent.

•   #5 - Do not Abbreviate.

•   #6 - Keep your classes small

•   #7 - Limit the number of instance variables in a class (max: 5)

•   #8 - Use first class collections

•   #9 - Use accessors (getter/setter)

•   #10 - Document your code!
@rdohms                   http://doh.ms
rafael @doh.ms           http://slides.doh.ms




             Questions?
         https://joind.in/6749



 Got bad code?   https://!xthatcode.com
The ThoughtWorks Anthology
                    http://goo.gl/OcSNx

                    The Art of Readable Code
                    http://goo.gl/unrij


DISCLAIMER: This talk re-uses some of the examples used by Guilherme Blanco in his
original Object Calisthenic talk. These principles were studied and applied by us while we
worked together in previous jobs. The result taught us all a lesson we really want to spread
to other developers.

Weitere ähnliche Inhalte

Was ist angesagt?

購物車程式架構簡介
購物車程式架構簡介購物車程式架構簡介
購物車程式架構簡介Jace Ju
 
PHPSpec - the only Design Tool you need - 4Developers
PHPSpec - the only Design Tool you need - 4DevelopersPHPSpec - the only Design Tool you need - 4Developers
PHPSpec - the only Design Tool you need - 4DevelopersKacper Gunia
 
Drupal - dbtng 25th Anniversary Edition
Drupal - dbtng 25th Anniversary EditionDrupal - dbtng 25th Anniversary Edition
Drupal - dbtng 25th Anniversary Editionddiers
 
Jquery presentation
Jquery presentationJquery presentation
Jquery presentationguest5d87aa6
 
Coding for Scale and Sanity
Coding for Scale and SanityCoding for Scale and Sanity
Coding for Scale and SanityJimKellerES
 
Dig Deeper into WordPress - WD Meetup Cairo
Dig Deeper into WordPress - WD Meetup CairoDig Deeper into WordPress - WD Meetup Cairo
Dig Deeper into WordPress - WD Meetup CairoMohamed Mosaad
 
50 Laravel Tricks in 50 Minutes
50 Laravel Tricks in 50 Minutes50 Laravel Tricks in 50 Minutes
50 Laravel Tricks in 50 MinutesAzim Kurt
 
PHPUnit でよりよくテストを書くために
PHPUnit でよりよくテストを書くためにPHPUnit でよりよくテストを書くために
PHPUnit でよりよくテストを書くためにYuya Takeyama
 
Models and Service Layers, Hemoglobin and Hobgoblins
Models and Service Layers, Hemoglobin and HobgoblinsModels and Service Layers, Hemoglobin and Hobgoblins
Models and Service Layers, Hemoglobin and HobgoblinsRoss Tuck
 
Command Bus To Awesome Town
Command Bus To Awesome TownCommand Bus To Awesome Town
Command Bus To Awesome TownRoss Tuck
 
Forget about Index.php and build you applications around HTTP - PHPers Cracow
Forget about Index.php and build you applications around HTTP - PHPers CracowForget about Index.php and build you applications around HTTP - PHPers Cracow
Forget about Index.php and build you applications around HTTP - PHPers CracowKacper Gunia
 
Advanced php testing in action
Advanced php testing in actionAdvanced php testing in action
Advanced php testing in actionJace Ju
 
Internationalizing CakePHP Applications
Internationalizing CakePHP ApplicationsInternationalizing CakePHP Applications
Internationalizing CakePHP ApplicationsPierre MARTIN
 
November Camp - Spec BDD with PHPSpec 2
November Camp - Spec BDD with PHPSpec 2November Camp - Spec BDD with PHPSpec 2
November Camp - Spec BDD with PHPSpec 2Kacper Gunia
 
Open Source Search: An Analysis
Open Source Search: An AnalysisOpen Source Search: An Analysis
Open Source Search: An AnalysisJustin Finkelstein
 
Moving a high traffic ZF1 Enterprise Application to SF2 - Lessons learned
Moving a high traffic ZF1 Enterprise Application to SF2 - Lessons learnedMoving a high traffic ZF1 Enterprise Application to SF2 - Lessons learned
Moving a high traffic ZF1 Enterprise Application to SF2 - Lessons learnedBaldur Rensch
 
The IoC Hydra - Dutch PHP Conference 2016
The IoC Hydra - Dutch PHP Conference 2016The IoC Hydra - Dutch PHP Conference 2016
The IoC Hydra - Dutch PHP Conference 2016Kacper Gunia
 
Things I Believe Now That I'm Old
Things I Believe Now That I'm OldThings I Believe Now That I'm Old
Things I Believe Now That I'm OldRoss Tuck
 

Was ist angesagt? (19)

購物車程式架構簡介
購物車程式架構簡介購物車程式架構簡介
購物車程式架構簡介
 
PHPSpec - the only Design Tool you need - 4Developers
PHPSpec - the only Design Tool you need - 4DevelopersPHPSpec - the only Design Tool you need - 4Developers
PHPSpec - the only Design Tool you need - 4Developers
 
Mocking Demystified
Mocking DemystifiedMocking Demystified
Mocking Demystified
 
Drupal - dbtng 25th Anniversary Edition
Drupal - dbtng 25th Anniversary EditionDrupal - dbtng 25th Anniversary Edition
Drupal - dbtng 25th Anniversary Edition
 
Jquery presentation
Jquery presentationJquery presentation
Jquery presentation
 
Coding for Scale and Sanity
Coding for Scale and SanityCoding for Scale and Sanity
Coding for Scale and Sanity
 
Dig Deeper into WordPress - WD Meetup Cairo
Dig Deeper into WordPress - WD Meetup CairoDig Deeper into WordPress - WD Meetup Cairo
Dig Deeper into WordPress - WD Meetup Cairo
 
50 Laravel Tricks in 50 Minutes
50 Laravel Tricks in 50 Minutes50 Laravel Tricks in 50 Minutes
50 Laravel Tricks in 50 Minutes
 
PHPUnit でよりよくテストを書くために
PHPUnit でよりよくテストを書くためにPHPUnit でよりよくテストを書くために
PHPUnit でよりよくテストを書くために
 
Models and Service Layers, Hemoglobin and Hobgoblins
Models and Service Layers, Hemoglobin and HobgoblinsModels and Service Layers, Hemoglobin and Hobgoblins
Models and Service Layers, Hemoglobin and Hobgoblins
 
Command Bus To Awesome Town
Command Bus To Awesome TownCommand Bus To Awesome Town
Command Bus To Awesome Town
 
Forget about Index.php and build you applications around HTTP - PHPers Cracow
Forget about Index.php and build you applications around HTTP - PHPers CracowForget about Index.php and build you applications around HTTP - PHPers Cracow
Forget about Index.php and build you applications around HTTP - PHPers Cracow
 
Advanced php testing in action
Advanced php testing in actionAdvanced php testing in action
Advanced php testing in action
 
Internationalizing CakePHP Applications
Internationalizing CakePHP ApplicationsInternationalizing CakePHP Applications
Internationalizing CakePHP Applications
 
November Camp - Spec BDD with PHPSpec 2
November Camp - Spec BDD with PHPSpec 2November Camp - Spec BDD with PHPSpec 2
November Camp - Spec BDD with PHPSpec 2
 
Open Source Search: An Analysis
Open Source Search: An AnalysisOpen Source Search: An Analysis
Open Source Search: An Analysis
 
Moving a high traffic ZF1 Enterprise Application to SF2 - Lessons learned
Moving a high traffic ZF1 Enterprise Application to SF2 - Lessons learnedMoving a high traffic ZF1 Enterprise Application to SF2 - Lessons learned
Moving a high traffic ZF1 Enterprise Application to SF2 - Lessons learned
 
The IoC Hydra - Dutch PHP Conference 2016
The IoC Hydra - Dutch PHP Conference 2016The IoC Hydra - Dutch PHP Conference 2016
The IoC Hydra - Dutch PHP Conference 2016
 
Things I Believe Now That I'm Old
Things I Believe Now That I'm OldThings I Believe Now That I'm Old
Things I Believe Now That I'm Old
 

Andere mochten auch

les saisons de l annee
les saisons de l anneeles saisons de l annee
les saisons de l anneePaulo Marques
 
Les saisons de l'annee
Les saisons de l'anneeLes saisons de l'annee
Les saisons de l'anneemoukheyberrana
 
Sendwithus - Mailgun Webinar
Sendwithus - Mailgun WebinarSendwithus - Mailgun Webinar
Sendwithus - Mailgun WebinarKelly Kenney
 
seasons ppt in french
seasons ppt in frenchseasons ppt in french
seasons ppt in frenchamartya_kumar
 
Les vêtements et les saisons.
Les vêtements et les saisons.Les vêtements et les saisons.
Les vêtements et les saisons.Student
 
Les quatre saisons de l´année
Les quatre saisons de l´annéeLes quatre saisons de l´année
Les quatre saisons de l´annéepaulinopalma
 
Composer The Right Way - 010PHP
Composer The Right Way - 010PHPComposer The Right Way - 010PHP
Composer The Right Way - 010PHPRafael Dohms
 
ETAPAS DE LA VIDA, EMBARAZO Y PARTO
ETAPAS DE LA VIDA, EMBARAZO Y PARTOETAPAS DE LA VIDA, EMBARAZO Y PARTO
ETAPAS DE LA VIDA, EMBARAZO Y PARTOSanti Gil
 
Power point embarazo,
Power point embarazo,Power point embarazo,
Power point embarazo,guestf3561ca2
 
Writing code that lasts - JAB14
Writing code that lasts - JAB14Writing code that lasts - JAB14
Writing code that lasts - JAB14Rafael Dohms
 
Herramientas 2.0 para todos los públicos
Herramientas 2.0 para todos los públicosHerramientas 2.0 para todos los públicos
Herramientas 2.0 para todos los públicosmariajesusmusica
 
Writing code you won't hate tomorrow
Writing code you won't hate tomorrowWriting code you won't hate tomorrow
Writing code you won't hate tomorrowRafael Dohms
 

Andere mochten auch (19)

Mediaon
MediaonMediaon
Mediaon
 
les saisons de l annee
les saisons de l anneeles saisons de l annee
les saisons de l annee
 
Les saisons de l'annee
Les saisons de l'anneeLes saisons de l'annee
Les saisons de l'annee
 
Sendwithus - Mailgun Webinar
Sendwithus - Mailgun WebinarSendwithus - Mailgun Webinar
Sendwithus - Mailgun Webinar
 
seasons ppt in french
seasons ppt in frenchseasons ppt in french
seasons ppt in french
 
Les vêtements et les saisons.
Les vêtements et les saisons.Les vêtements et les saisons.
Les vêtements et les saisons.
 
Les quatre saisons de l´année
Les quatre saisons de l´annéeLes quatre saisons de l´année
Les quatre saisons de l´année
 
Composer The Right Way - 010PHP
Composer The Right Way - 010PHPComposer The Right Way - 010PHP
Composer The Right Way - 010PHP
 
Fases del embarazo, parto y lactancia.
Fases del embarazo, parto y lactancia.Fases del embarazo, parto y lactancia.
Fases del embarazo, parto y lactancia.
 
ETAPAS DE LA VIDA, EMBARAZO Y PARTO
ETAPAS DE LA VIDA, EMBARAZO Y PARTOETAPAS DE LA VIDA, EMBARAZO Y PARTO
ETAPAS DE LA VIDA, EMBARAZO Y PARTO
 
Etapas del embarazo
Etapas del embarazoEtapas del embarazo
Etapas del embarazo
 
Power point embarazo,
Power point embarazo,Power point embarazo,
Power point embarazo,
 
Desarrollo del embarazo mes a mes
Desarrollo del embarazo mes a mesDesarrollo del embarazo mes a mes
Desarrollo del embarazo mes a mes
 
Writing code that lasts - JAB14
Writing code that lasts - JAB14Writing code that lasts - JAB14
Writing code that lasts - JAB14
 
Prensa digital
Prensa digitalPrensa digital
Prensa digital
 
Aprendizaje musical TIC
Aprendizaje musical TICAprendizaje musical TIC
Aprendizaje musical TIC
 
Clase música20
Clase música20Clase música20
Clase música20
 
Herramientas 2.0 para todos los públicos
Herramientas 2.0 para todos los públicosHerramientas 2.0 para todos los públicos
Herramientas 2.0 para todos los públicos
 
Writing code you won't hate tomorrow
Writing code you won't hate tomorrowWriting code you won't hate tomorrow
Writing code you won't hate tomorrow
 

Ähnlich wie Your code sucks, let's fix it (CakeFest2012)

Your code sucks, let's fix it
Your code sucks, let's fix itYour code sucks, let's fix it
Your code sucks, let's fix itRafael Dohms
 
Propel sfugmd
Propel sfugmdPropel sfugmd
Propel sfugmdiKlaus
 
jQuery: Tips, tricks and hints for better development and Performance
jQuery: Tips, tricks and hints for better development and PerformancejQuery: Tips, tricks and hints for better development and Performance
jQuery: Tips, tricks and hints for better development and PerformanceJonas De Smet
 
Why Hacking WordPress Search Isn't Some Big Scary Thing
Why Hacking WordPress Search Isn't Some Big Scary ThingWhy Hacking WordPress Search Isn't Some Big Scary Thing
Why Hacking WordPress Search Isn't Some Big Scary ThingChris Reynolds
 
Dutch PHP Conference - PHPSpec 2 - The only Design Tool you need
Dutch PHP Conference - PHPSpec 2 - The only Design Tool you needDutch PHP Conference - PHPSpec 2 - The only Design Tool you need
Dutch PHP Conference - PHPSpec 2 - The only Design Tool you needKacper Gunia
 
Dependency Injection
Dependency InjectionDependency Injection
Dependency InjectionRifat Nabi
 
Unit testing with zend framework tek11
Unit testing with zend framework tek11Unit testing with zend framework tek11
Unit testing with zend framework tek11Michelangelo van Dam
 
WordPress as an application framework
WordPress as an application frameworkWordPress as an application framework
WordPress as an application frameworkDustin Filippini
 
Unit testing with zend framework PHPBenelux
Unit testing with zend framework PHPBeneluxUnit testing with zend framework PHPBenelux
Unit testing with zend framework PHPBeneluxMichelangelo van Dam
 
laravel tricks in 50minutes
laravel tricks in 50minuteslaravel tricks in 50minutes
laravel tricks in 50minutesBarang CK
 
jQuery - 10 Time-Savers You (Maybe) Don't Know
jQuery - 10 Time-Savers You (Maybe) Don't KnowjQuery - 10 Time-Savers You (Maybe) Don't Know
jQuery - 10 Time-Savers You (Maybe) Don't Knowgirish82
 
How to test complex SaaS applications - The family july 2014
How to test complex SaaS applications - The family july 2014How to test complex SaaS applications - The family july 2014
How to test complex SaaS applications - The family july 2014Guillaume POTIER
 
WordCamp Portland 2018: PHP for WordPress
WordCamp Portland 2018: PHP for WordPressWordCamp Portland 2018: PHP for WordPress
WordCamp Portland 2018: PHP for WordPressAlena Holligan
 
Object Calisthenics Adapted for PHP
Object Calisthenics Adapted for PHPObject Calisthenics Adapted for PHP
Object Calisthenics Adapted for PHPChad Gray
 
JavaScript for PHP developers
JavaScript for PHP developersJavaScript for PHP developers
JavaScript for PHP developersStoyan Stefanov
 
PHP and Rich Internet Applications
PHP and Rich Internet ApplicationsPHP and Rich Internet Applications
PHP and Rich Internet Applicationselliando dias
 
The History of PHPersistence
The History of PHPersistenceThe History of PHPersistence
The History of PHPersistenceHugo Hamon
 
Introduction à CoffeeScript pour ParisRB
Introduction à CoffeeScript pour ParisRB Introduction à CoffeeScript pour ParisRB
Introduction à CoffeeScript pour ParisRB jhchabran
 

Ähnlich wie Your code sucks, let's fix it (CakeFest2012) (20)

Your code sucks, let's fix it
Your code sucks, let's fix itYour code sucks, let's fix it
Your code sucks, let's fix it
 
Propel sfugmd
Propel sfugmdPropel sfugmd
Propel sfugmd
 
jQuery: Tips, tricks and hints for better development and Performance
jQuery: Tips, tricks and hints for better development and PerformancejQuery: Tips, tricks and hints for better development and Performance
jQuery: Tips, tricks and hints for better development and Performance
 
Why Hacking WordPress Search Isn't Some Big Scary Thing
Why Hacking WordPress Search Isn't Some Big Scary ThingWhy Hacking WordPress Search Isn't Some Big Scary Thing
Why Hacking WordPress Search Isn't Some Big Scary Thing
 
Dutch PHP Conference - PHPSpec 2 - The only Design Tool you need
Dutch PHP Conference - PHPSpec 2 - The only Design Tool you needDutch PHP Conference - PHPSpec 2 - The only Design Tool you need
Dutch PHP Conference - PHPSpec 2 - The only Design Tool you need
 
Dependency Injection
Dependency InjectionDependency Injection
Dependency Injection
 
Unit testing with zend framework tek11
Unit testing with zend framework tek11Unit testing with zend framework tek11
Unit testing with zend framework tek11
 
WordPress as an application framework
WordPress as an application frameworkWordPress as an application framework
WordPress as an application framework
 
Unit testing with zend framework PHPBenelux
Unit testing with zend framework PHPBeneluxUnit testing with zend framework PHPBenelux
Unit testing with zend framework PHPBenelux
 
laravel tricks in 50minutes
laravel tricks in 50minuteslaravel tricks in 50minutes
laravel tricks in 50minutes
 
jQuery - 10 Time-Savers You (Maybe) Don't Know
jQuery - 10 Time-Savers You (Maybe) Don't KnowjQuery - 10 Time-Savers You (Maybe) Don't Know
jQuery - 10 Time-Savers You (Maybe) Don't Know
 
How to test complex SaaS applications - The family july 2014
How to test complex SaaS applications - The family july 2014How to test complex SaaS applications - The family july 2014
How to test complex SaaS applications - The family july 2014
 
WordCamp Portland 2018: PHP for WordPress
WordCamp Portland 2018: PHP for WordPressWordCamp Portland 2018: PHP for WordPress
WordCamp Portland 2018: PHP for WordPress
 
Object Calisthenics Adapted for PHP
Object Calisthenics Adapted for PHPObject Calisthenics Adapted for PHP
Object Calisthenics Adapted for PHP
 
JavaScript for PHP developers
JavaScript for PHP developersJavaScript for PHP developers
JavaScript for PHP developers
 
PHP and Rich Internet Applications
PHP and Rich Internet ApplicationsPHP and Rich Internet Applications
PHP and Rich Internet Applications
 
The History of PHPersistence
The History of PHPersistenceThe History of PHPersistence
The History of PHPersistence
 
PHP Unit Testing
PHP Unit TestingPHP Unit Testing
PHP Unit Testing
 
Unit testing zend framework apps
Unit testing zend framework appsUnit testing zend framework apps
Unit testing zend framework apps
 
Introduction à CoffeeScript pour ParisRB
Introduction à CoffeeScript pour ParisRB Introduction à CoffeeScript pour ParisRB
Introduction à CoffeeScript pour ParisRB
 

Mehr von Rafael Dohms

The Individual Contributor Path - DPC2024
The Individual Contributor Path - DPC2024The Individual Contributor Path - DPC2024
The Individual Contributor Path - DPC2024Rafael Dohms
 
Application Metrics - IPC2023
Application Metrics - IPC2023Application Metrics - IPC2023
Application Metrics - IPC2023Rafael Dohms
 
How'd we get here? A guide to Architectural Decision Records
How'd we get here? A guide to Architectural Decision RecordsHow'd we get here? A guide to Architectural Decision Records
How'd we get here? A guide to Architectural Decision RecordsRafael Dohms
 
Architectural Decision Records - PHPConfBR
Architectural Decision Records - PHPConfBRArchitectural Decision Records - PHPConfBR
Architectural Decision Records - PHPConfBRRafael Dohms
 
Application Metrics (with Prometheus examples)
Application Metrics (with Prometheus examples)Application Metrics (with Prometheus examples)
Application Metrics (with Prometheus examples)Rafael Dohms
 
Application metrics - Confoo 2019
Application metrics - Confoo 2019Application metrics - Confoo 2019
Application metrics - Confoo 2019Rafael Dohms
 
Writing code you won’t hate tomorrow - PHPCE18
Writing code you won’t hate tomorrow - PHPCE18Writing code you won’t hate tomorrow - PHPCE18
Writing code you won’t hate tomorrow - PHPCE18Rafael Dohms
 
Application Metrics (with Prometheus examples) #PHPDD18
Application Metrics (with Prometheus examples) #PHPDD18Application Metrics (with Prometheus examples) #PHPDD18
Application Metrics (with Prometheus examples) #PHPDD18Rafael Dohms
 
Application metrics with Prometheus - DPC18
Application metrics with Prometheus - DPC18Application metrics with Prometheus - DPC18
Application metrics with Prometheus - DPC18Rafael Dohms
 
Writing Code That Lasts - #Magento2Seminar, Utrecht
Writing Code That Lasts - #Magento2Seminar, UtrechtWriting Code That Lasts - #Magento2Seminar, Utrecht
Writing Code That Lasts - #Magento2Seminar, UtrechtRafael Dohms
 
Composer the Right Way - PHPSRB16
Composer the Right Way - PHPSRB16Composer the Right Way - PHPSRB16
Composer the Right Way - PHPSRB16Rafael Dohms
 
“Writing code that lasts” … or writing code you won’t hate tomorrow. - #PHPSRB16
“Writing code that lasts” … or writing code you won’t hate tomorrow. - #PHPSRB16“Writing code that lasts” … or writing code you won’t hate tomorrow. - #PHPSRB16
“Writing code that lasts” … or writing code you won’t hate tomorrow. - #PHPSRB16Rafael Dohms
 
Composer the Right Way - MM16NL
Composer the Right Way - MM16NLComposer the Right Way - MM16NL
Composer the Right Way - MM16NLRafael Dohms
 
Composer The Right Way - PHPUGMRN
Composer The Right Way - PHPUGMRNComposer The Right Way - PHPUGMRN
Composer The Right Way - PHPUGMRNRafael Dohms
 
Composer the Right Way - PHPBNL16
Composer the Right Way - PHPBNL16Composer the Right Way - PHPBNL16
Composer the Right Way - PHPBNL16Rafael Dohms
 
“Writing code that lasts” … or writing code you won’t hate tomorrow.
“Writing code that lasts” … or writing code you won’t hate tomorrow.“Writing code that lasts” … or writing code you won’t hate tomorrow.
“Writing code that lasts” … or writing code you won’t hate tomorrow.Rafael Dohms
 
A Journey into your Lizard Brain - PHP Conference Brasil 2015
A Journey into your Lizard Brain - PHP Conference Brasil 2015A Journey into your Lizard Brain - PHP Conference Brasil 2015
A Journey into your Lizard Brain - PHP Conference Brasil 2015Rafael Dohms
 
“Writing code that lasts” … or writing code you won’t hate tomorrow.
“Writing code that lasts” … or writing code you won’t hate tomorrow.“Writing code that lasts” … or writing code you won’t hate tomorrow.
“Writing code that lasts” … or writing code you won’t hate tomorrow.Rafael Dohms
 
“Writing code that lasts” … or writing code you won’t hate tomorrow.
“Writing code that lasts” … or writing code you won’t hate tomorrow.“Writing code that lasts” … or writing code you won’t hate tomorrow.
“Writing code that lasts” … or writing code you won’t hate tomorrow.Rafael Dohms
 
“Writing code that lasts” … or writing code you won’t hate tomorrow.
“Writing code that lasts” … or writing code you won’t hate tomorrow.“Writing code that lasts” … or writing code you won’t hate tomorrow.
“Writing code that lasts” … or writing code you won’t hate tomorrow.Rafael Dohms
 

Mehr von Rafael Dohms (20)

The Individual Contributor Path - DPC2024
The Individual Contributor Path - DPC2024The Individual Contributor Path - DPC2024
The Individual Contributor Path - DPC2024
 
Application Metrics - IPC2023
Application Metrics - IPC2023Application Metrics - IPC2023
Application Metrics - IPC2023
 
How'd we get here? A guide to Architectural Decision Records
How'd we get here? A guide to Architectural Decision RecordsHow'd we get here? A guide to Architectural Decision Records
How'd we get here? A guide to Architectural Decision Records
 
Architectural Decision Records - PHPConfBR
Architectural Decision Records - PHPConfBRArchitectural Decision Records - PHPConfBR
Architectural Decision Records - PHPConfBR
 
Application Metrics (with Prometheus examples)
Application Metrics (with Prometheus examples)Application Metrics (with Prometheus examples)
Application Metrics (with Prometheus examples)
 
Application metrics - Confoo 2019
Application metrics - Confoo 2019Application metrics - Confoo 2019
Application metrics - Confoo 2019
 
Writing code you won’t hate tomorrow - PHPCE18
Writing code you won’t hate tomorrow - PHPCE18Writing code you won’t hate tomorrow - PHPCE18
Writing code you won’t hate tomorrow - PHPCE18
 
Application Metrics (with Prometheus examples) #PHPDD18
Application Metrics (with Prometheus examples) #PHPDD18Application Metrics (with Prometheus examples) #PHPDD18
Application Metrics (with Prometheus examples) #PHPDD18
 
Application metrics with Prometheus - DPC18
Application metrics with Prometheus - DPC18Application metrics with Prometheus - DPC18
Application metrics with Prometheus - DPC18
 
Writing Code That Lasts - #Magento2Seminar, Utrecht
Writing Code That Lasts - #Magento2Seminar, UtrechtWriting Code That Lasts - #Magento2Seminar, Utrecht
Writing Code That Lasts - #Magento2Seminar, Utrecht
 
Composer the Right Way - PHPSRB16
Composer the Right Way - PHPSRB16Composer the Right Way - PHPSRB16
Composer the Right Way - PHPSRB16
 
“Writing code that lasts” … or writing code you won’t hate tomorrow. - #PHPSRB16
“Writing code that lasts” … or writing code you won’t hate tomorrow. - #PHPSRB16“Writing code that lasts” … or writing code you won’t hate tomorrow. - #PHPSRB16
“Writing code that lasts” … or writing code you won’t hate tomorrow. - #PHPSRB16
 
Composer the Right Way - MM16NL
Composer the Right Way - MM16NLComposer the Right Way - MM16NL
Composer the Right Way - MM16NL
 
Composer The Right Way - PHPUGMRN
Composer The Right Way - PHPUGMRNComposer The Right Way - PHPUGMRN
Composer The Right Way - PHPUGMRN
 
Composer the Right Way - PHPBNL16
Composer the Right Way - PHPBNL16Composer the Right Way - PHPBNL16
Composer the Right Way - PHPBNL16
 
“Writing code that lasts” … or writing code you won’t hate tomorrow.
“Writing code that lasts” … or writing code you won’t hate tomorrow.“Writing code that lasts” … or writing code you won’t hate tomorrow.
“Writing code that lasts” … or writing code you won’t hate tomorrow.
 
A Journey into your Lizard Brain - PHP Conference Brasil 2015
A Journey into your Lizard Brain - PHP Conference Brasil 2015A Journey into your Lizard Brain - PHP Conference Brasil 2015
A Journey into your Lizard Brain - PHP Conference Brasil 2015
 
“Writing code that lasts” … or writing code you won’t hate tomorrow.
“Writing code that lasts” … or writing code you won’t hate tomorrow.“Writing code that lasts” … or writing code you won’t hate tomorrow.
“Writing code that lasts” … or writing code you won’t hate tomorrow.
 
“Writing code that lasts” … or writing code you won’t hate tomorrow.
“Writing code that lasts” … or writing code you won’t hate tomorrow.“Writing code that lasts” … or writing code you won’t hate tomorrow.
“Writing code that lasts” … or writing code you won’t hate tomorrow.
 
“Writing code that lasts” … or writing code you won’t hate tomorrow.
“Writing code that lasts” … or writing code you won’t hate tomorrow.“Writing code that lasts” … or writing code you won’t hate tomorrow.
“Writing code that lasts” … or writing code you won’t hate tomorrow.
 

Kürzlich hochgeladen

[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality AssuranceInflectra
 
QCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architecturesQCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architecturesBernd Ruecker
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersNicole Novielli
 
Glenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security ObservabilityGlenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security Observabilityitnewsafrica
 
Landscape Catalogue 2024 Australia-1.pdf
Landscape Catalogue 2024 Australia-1.pdfLandscape Catalogue 2024 Australia-1.pdf
Landscape Catalogue 2024 Australia-1.pdfAarwolf Industries LLC
 
Accelerating Enterprise Software Engineering with Platformless
Accelerating Enterprise Software Engineering with PlatformlessAccelerating Enterprise Software Engineering with Platformless
Accelerating Enterprise Software Engineering with PlatformlessWSO2
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Mark Goldstein
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch TuesdayIvanti
 
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotesMuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotesManik S Magar
 
Generative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptxGenerative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptxfnnc6jmgwh
 
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...panagenda
 
All These Sophisticated Attacks, Can We Really Detect Them - PDF
All These Sophisticated Attacks, Can We Really Detect Them - PDFAll These Sophisticated Attacks, Can We Really Detect Them - PDF
All These Sophisticated Attacks, Can We Really Detect Them - PDFMichael Gough
 
A Glance At The Java Performance Toolbox
A Glance At The Java Performance ToolboxA Glance At The Java Performance Toolbox
A Glance At The Java Performance ToolboxAna-Maria Mihalceanu
 
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...itnewsafrica
 
Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsRavi Sanghani
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPathCommunity
 
Tampa BSides - The No BS SOC (slides from April 6, 2024 talk)
Tampa BSides - The No BS SOC (slides from April 6, 2024 talk)Tampa BSides - The No BS SOC (slides from April 6, 2024 talk)
Tampa BSides - The No BS SOC (slides from April 6, 2024 talk)Mark Simos
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityIES VE
 
Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)Kaya Weers
 
Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024TopCSSGallery
 

Kürzlich hochgeladen (20)

[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
 
QCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architecturesQCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architectures
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software Developers
 
Glenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security ObservabilityGlenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security Observability
 
Landscape Catalogue 2024 Australia-1.pdf
Landscape Catalogue 2024 Australia-1.pdfLandscape Catalogue 2024 Australia-1.pdf
Landscape Catalogue 2024 Australia-1.pdf
 
Accelerating Enterprise Software Engineering with Platformless
Accelerating Enterprise Software Engineering with PlatformlessAccelerating Enterprise Software Engineering with Platformless
Accelerating Enterprise Software Engineering with Platformless
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch Tuesday
 
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotesMuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
 
Generative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptxGenerative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptx
 
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
 
All These Sophisticated Attacks, Can We Really Detect Them - PDF
All These Sophisticated Attacks, Can We Really Detect Them - PDFAll These Sophisticated Attacks, Can We Really Detect Them - PDF
All These Sophisticated Attacks, Can We Really Detect Them - PDF
 
A Glance At The Java Performance Toolbox
A Glance At The Java Performance ToolboxA Glance At The Java Performance Toolbox
A Glance At The Java Performance Toolbox
 
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...
 
Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and Insights
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to Hero
 
Tampa BSides - The No BS SOC (slides from April 6, 2024 talk)
Tampa BSides - The No BS SOC (slides from April 6, 2024 talk)Tampa BSides - The No BS SOC (slides from April 6, 2024 talk)
Tampa BSides - The No BS SOC (slides from April 6, 2024 talk)
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a reality
 
Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)
 
Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024
 

Your code sucks, let's fix it (CakeFest2012)

  • 1. Your code sucks, let’s !x it! Object Calisthenics and Code readability Rafael Dohms @rdohms
  • 2. Rafael Dohms photo credit: Eli White @rdohms Evangelist, Speaker and Contributor. Developer at WEBclusive. Enabler at AmsterdamPHP.
  • 3. What’s the talk about? • Why does my code suck? • How can we fix it?
  • 5. Is it Readable? Why does my code suck?
  • 6. Is it Readable? Why does my code suck? Is it Testable?
  • 7. Is it Maintainable? Is it Readable? Why does my code suck? Is it Testable?
  • 8. Is it Maintainable? Is it Readable? Why does my code suck? Is it Reusable? Is it Testable?
  • 9. <?php Does it look like this? $list=mysql_connect("******","*******","*****"); if(!$list)echo 'Cannot login.'; else{ mysql_select_db("******", $list); $best=array("0","0","0","0","0","0"); $id=mysql_num_rows(mysql_query("SELECT * FROM allnews")); $count=0; for($i=0;$i<6;$i++){ while(mysql_query("SELECT language FROM allnews WHERE id=$id-$count")!="he")$count+ +; $best[$i]=mysql_query("SELECT id FROM allnews WHERE id=$id-$count");} $id=$id-$count; $maxdate=mktime(0,0,0,date('m'),date('d')-7,date('Y')); while(mysql_query("SELECT date FROM allnews WHERE id=$id-$count")>=$maxdate){ if(mysql_query("SELECT language FROM allnews WHERE id=$id-$count")=="he"){ $small=$best[0]; while($i=0;$i<6;$i++){ if(mysql_query("SELECT score FROM allnews WHERE id= $small)"<mysql_query("SELECT score FROM allnews WHERE id=$best[i+1]")) $small=$best[i+1];} if(mysql_query("SELECT score FROM allnews WHERE id= $small")<mysql_query("SELECT score FROM allnews WHERE id=$id-$count")){ while($i=0;$i<6;$i++){ if($small==$best[i])$best[i]=mysql_query("SELECT id FROM allnews WHERE id=$id-$count");}}}} while($i=0;$i<6;$i++) echo '<a href="news-page.php?id='.$best[i].'"><div class="box '.mysql_query("SELECT type FROM allnews WHERE id=$best[i]").'">'.mysql_query("SELECT title FROM allnews WHERE id= $best[i]").'<div class="img" style="background-image:url(images/'.mysql_query("SELECT image1 FROM allnews WHERE id=$best[i]").');"></div></div></a>'; mysql_close($list); } ?>
  • 10. <?php Does it look like this? $list=mysql_connect("******","*******","*****"); if(!$list)echo 'Cannot login.'; else{ mysql_select_db("******", $list); $best=array("0","0","0","0","0","0"); $id=mysql_num_rows(mysql_query("SELECT * FROM allnews")); $count=0; for($i=0;$i<6;$i++){ while(mysql_query("SELECT language FROM allnews WHERE id=$id-$count")!="he")$count+ +; $best[$i]=mysql_query("SELECT id FROM allnews WHERE id=$id-$count");} $id=$id-$count; $maxdate=mktime(0,0,0,date('m'),date('d')-7,date('Y')); while(mysql_query("SELECT date FROM allnews WHERE id=$id-$count")>=$maxdate){ if(mysql_query("SELECT language FROM allnews WHERE id=$id-$count")=="he"){ $small=$best[0]; while($i=0;$i<6;$i++){ if(mysql_query("SELECT score FROM allnews WHERE id= $small)"<mysql_query("SELECT score FROM allnews WHERE id=$best[i+1]")) $small=$best[i+1];} if(mysql_query("SELECT score FROM allnews WHERE id= $small")<mysql_query("SELECT score FROM Rebecca WHERE id=$id-$count")){ If allnews Black was a developer while($i=0;$i<6;$i++){ if($small==$best[i])$best[i]=mysql_query("SELECT id FROM allnews WHERE id=$id-$count");}}}} while($i=0;$i<6;$i++) echo '<a href="news-page.php?id='.$best[i].'"><div class="box '.mysql_query("SELECT type FROM allnews WHERE id=$best[i]").'">'.mysql_query("SELECT title FROM allnews WHERE id= $best[i]").'<div class="img" style="background-image:url(images/'.mysql_query("SELECT image1 FROM allnews WHERE id=$best[i]").');"></div></div></a>'; mysql_close($list); } ?>
  • 11. How do we fix it?
  • 13. cal·is·then·ics - noun - /ˌkaləsˈTHeniks/ Calisthenics are a form of dynamic exercise consisting of a variety of simple, often rhythmical, movements, generally using minimal equipment or apparatus. Object Calisthenics
  • 14. cal·is·then·ics - noun - /ˌkaləsˈTHeniks/ Calisthenics are a form of dynamic exercise consisting of a variety of simple, often rhythmical, movements, generally using minimal equipment or apparatus. Object Calisthenics A variety of simple, often rhythmical, exercises to achieve better OO and code quality
  • 15. “So here’s an exercise that can help you to internalize principles of good object-oriented design and actually use them in real life.” -- Jeff Bay Object Calisthenics
  • 16. “So here’s an exercise that can help you to internalize principles of good object-oriented design and actually use them in real life.” -- Jeff Bay Object Calisthenics Important: PHP != JAVA Adaptations will be done
  • 17. Object Calisthenics + Readability Tips
  • 18. “You need to write code that minimizes the time it would Object Calisthenics take someone else to understand it—even if that someone else is you.” + -- Dustin Boswell and Trevor Foucher Readability Tips
  • 19. “You need to write code that minimizes the time it would Object Calisthenics take someone else to understand it—even if that someone else is you.” + -- Dustin Boswell and Trevor Foucher Readability Tips I’m a tip
  • 21. OC #1 “Only one indentation level per method”
  • 22. function validateProducts($products) { // Check to make sure that our valid fields are in there $requiredFields = array( 'price', 'name', 'description', 'type', ); $valid = true; foreach ($products as $rawProduct) { $fields = array_keys($rawProduct); foreach ($requiredFields as $requiredField) { if (!in_array($requiredField, $fields)) { $valid = false; } } } return $valid; }
  • 23. function validateProducts($products) { // Check to make sure that our valid fields are in there $requiredFields = array( 'price', 'name', 'description', 'type', ); $valid = true; 0 foreach ($products as $rawProduct) { 1 $fields = array_keys($rawProduct); foreach ($requiredFields as $requiredField) { 2 if (!in_array($requiredField, $fields)) { 3 $valid = false; } } } return $valid; }
  • 24. function validateProducts($products) { // Check to make sure that our valid fields are in there $requiredFields = array( 'price', 'name', 'description', 'type', ); $valid = true; 0 foreach ($products as $rawProduct) { 1 $fields = array_keys($rawProduct); foreach ($requiredFields as $requiredField) { 2 if (!in_array($requiredField, $fields)) { 3 $valid = false; } } } return $valid; }
  • 25. function validateProducts($products) { // Check to make sure that our valid fields are in there $requiredFields = array( 'price', 'name', 'description', 'type', ); $valid = true; foreach ($products as $rawProduct) { $validationResult = validateSingleProduct($rawProduct, $requiredFields); if ( ! $validationResult){ $valid = false; } } return $valid; } function validateSingleProduct($product, $requiredFields) { $valid = true; $fields = array_keys($rawProduct); foreach ($requiredFields as $requiredField) { if (!in_array($requiredField, $fields)) { $valid = false; } } return $valid; }
  • 26. function validateProducts($products) { // Check to make sure that our valid fields are in there $requiredFields = array( 'price', 'name', 'description', 'type', ); $valid = true; whitespace foreach ($products as $rawProduct) { $validationResult = validateSingleProduct($rawProduct, $requiredFields); if ( ! $validationResult){ $valid = false; } } return $valid; } function validateSingleProduct($product, $requiredFields) { $valid = true; $fields = array_keys($rawProduct); foreach ($requiredFields as $requiredField) { if (!in_array($requiredField, $fields)) { $valid = false; } } return $valid; }
  • 27. function validateProducts($products) { // Check to make sure that our valid fields are in there $requiredFields = array( 'price', 'name', 'description', 'type', ); $valid = true; whitespace foreach ($products as $rawProduct) { $validationResult = validateSingleProduct($rawProduct, $requiredFields); if ( ! $validationResult){ $valid = false; } } return $valid; } function validateSingleProduct($product, $requiredFields) { $valid = true; duplicated logic $fields = array_keys($rawProduct); foreach ($requiredFields as $requiredField) { if (!in_array($requiredField, $fields)) { $valid = false; } } return $valid; }
  • 28. function validateProducts($products) { // Check to make sure that our valid fields are in there $requiredFields = array( 'price', 'name', 'description', 'type', ); $valid = true; 0 foreach ($products as whitespace $validationResult $rawProduct) { = validateSingleProduct($rawProduct, $requiredFields); 1 if ( ! $validationResult){ } 2 $valid = false; } return $valid; } function validateSingleProduct($product, $requiredFields) { $valid = true; duplicated logic $fields = array_keys($rawProduct); 0 foreach(!in_array($requiredField, $fields)) ($requiredFields as $requiredField) { 1 if { } 2 $valid = false; } return $valid; }
  • 29. function validateProducts($products) { // Check to make sure that our valid fields are in there $requiredFields = array( 'price', 'name', 'description', 'type', ); $valid = true; 0 foreach ($products as $validationResult $rawProduct) { = validateSingleProduct($rawProduct, $requiredFields); 1 if ( ! $validationResult){ } 2 $valid = false; } return $valid; } function validateSingleProduct($product, $requiredFields) { $valid = true; $fields = array_keys($rawProduct); 0 foreach(!in_array($requiredField, $fields)) ($requiredFields as $requiredField) { 1 if { } 2 $valid = false; } return $valid; }
  • 30. function validateProducts($products) { // Check to make sure that our valid fields are in there $requiredFields = array( 'price', 'name', 'description', 'type', ); $valid = true; 0 foreach ($products as $validationResult $rawProduct) { = validateSingleProduct($rawProduct, $requiredFields); 1 if ( ! $validationResult){ } 2 $valid = false; } return $valid; } function validateSingleProduct($product, $requiredFields) { $valid = true; $fields = array_keys($rawProduct); 0 foreach(!in_array($requiredField, $fields)) ($requiredFields as $requiredField) { 1 if { } 2 $valid = false; } return $valid; }
  • 31. function validateProducts($storeData) { $requiredFields = array('price','name','description','type'); foreach ($storeData['products'] as $rawProduct) { if ( ! validateSingleProduct($rawProduct, $requiredFields)) return false; } return true; } function validateSingleProduct($product, $requiredFields) { $fields = array_keys($rawProduct); $missingFields = array_diff($requiredFields, $fields); return (count($missingFields) == 0); }
  • 32. function validateProducts($storeData) { $requiredFields = array('price','name','description','type'); cheating! I see foreach ($storeData['products'] as $rawProduct) { if ( ! validateSingleProduct($rawProduct, $requiredFields)) return false; } return true; } function validateSingleProduct($product, $requiredFields) { $fields = array_keys($rawProduct); $missingFields = array_diff($requiredFields, $fields); return (count($missingFields) == 0); }
  • 33. function validateProducts($storeData) { $requiredFields = array('price','name','description','type'); cheating! I see foreach ($storeData['products'] as $rawProduct) { if ( ! validateSingleProduct($rawProduct, $requiredFields)) return false; } return true; Single line IF, simple operations } function validateSingleProduct($product, $requiredFields) { $fields = array_keys($rawProduct); $missingFields = array_diff($requiredFields, $fields); return (count($missingFields) == 0); }
  • 34. function validateProducts($storeData) { $requiredFields = array('price','name','description','type'); foreach ($storeData['products'] as $rawProduct) { if ( ! validateSingleProduct($rawProduct, $requiredFields)) return false; } return true; Single line IF, simple operations return early } function validateSingleProduct($product, $requiredFields) { $fields = array_keys($rawProduct); $missingFields = array_diff($requiredFields, $fields); return (count($missingFields) == 0); }
  • 35. function validateProducts($storeData) { $requiredFields = array('price','name','description','type'); foreach ($storeData['products'] as $rawProduct) { if ( ! validateSingleProduct($rawProduct, $requiredFields)) return false; } return true; Single line IF, simple operations return early } function validateSingleProduct($product, $requiredFields) { $fields = array_keys($rawProduct); $missingFields = array_diff($requiredFields, $fields); return (count($missingFields) == 0); } C (native) functions are faster then PHP
  • 36. function validateProducts($storeData) { $requiredFields = array('price','name','description','type'); foreach ($storeData['products'] as $rawProduct) { if ( ! validateSingleProduct($rawProduct, $requiredFields)) return false; } return true; } function validateSingleProduct($product, $requiredFields) { $fields = array_keys($rawProduct); $missingFields = array_diff($requiredFields, $fields); return (count($missingFields) == 0); }
  • 37. function validateProducts($storeData) { $requiredFields = array('price','name','description','type'); foreach ($storeData['products'] as $rawProduct) { if ( ! validateSingleProduct($rawProduct, $requiredFields)) return false; } return true; } function validateSingleProduct($product, $requiredFields) { $fields = array_keys($rawProduct); $missingFields = array_diff($requiredFields, $fields); return (count($missingFields) == 0); }
  • 38. function validateProductList($products) { $invalidProducts = array_filter($products, 'isInvalidProduct'); return (count($invalidProducts) === 0); } function isInvalidProduct($rawProduct) { $requiredFields = array('price', 'name', 'description', 'type'); $fields = array_keys($rawProduct); $missingFields = array_diff($requiredFields, $fields); return (count($missingFields) > 0); }
  • 39. function validateProductList($products) iteration faster { $invalidProducts = array_filter($products, 'isInvalidProduct'); return (count($invalidProducts) === 0); } function isInvalidProduct($rawProduct) { $requiredFields = array('price', 'name', 'description', 'type'); $fields = array_keys($rawProduct); $missingFields = array_diff($requiredFields, $fields); return (count($missingFields) > 0); }
  • 40. function validateProductList($products) iteration faster { $invalidProducts = array_filter($products, 'isInvalidProduct'); return (count($invalidProducts) === 0); } reusable method function isInvalidProduct($rawProduct) { $requiredFields = array('price', 'name', 'description', 'type'); $fields = array_keys($rawProduct); $missingFields = array_diff($requiredFields, $fields); return (count($missingFields) > 0); }
  • 41. function validateProductList($products) iteration faster { $invalidProducts = array_filter($products, 'isInvalidProduct'); return (count($invalidProducts) === 0); } reusable method function isInvalidProduct($rawProduct) { $requiredFields = array('price', 'name', 'description', 'type'); $fields = array_keys($rawProduct); $missingFields = array_diff($requiredFields, $fields); return (count($missingFields) > 0); } method name matches “true” result
  • 42. function validateProductList($products) iteration faster { $invalidProducts = array_filter($products, 'isInvalidProduct'); return (count($invalidProducts) === 0); } readable return: zero invalid products reusable method function isInvalidProduct($rawProduct) { $requiredFields = array('price', 'name', 'description', 'type'); $fields = array_keys($rawProduct); $missingFields = array_diff($requiredFields, $fields); return (count($missingFields) > 0); } method name matches “true” result
  • 43. List is more readable the plural function validateProductList($products) iteration faster { $invalidProducts = array_filter($products, 'isInvalidProduct'); return (count($invalidProducts) === 0); } readable return: zero invalid products reusable method function isInvalidProduct($rawProduct) { $requiredFields = array('price', 'name', 'description', 'type'); $fields = array_keys($rawProduct); $missingFields = array_diff($requiredFields, $fields); return (count($missingFields) > 0); } method name matches “true” result
  • 44. Key Benefits • Cohesiveness • Methods does only one thing • Increases re-use
  • 45. OC #2 “Do not use the ‘else’ keyword”
  • 46. public function createPost($request) { $entity = new Post(); $form = new MyForm($entity); $form->bind($request); if ($form->isValid()){ $repository = $this->getRepository('MyBundle:Post'); if (!$repository->exists($entity) ) { $repository->save($entity); return $this->redirect('create_ok'); } else { $error = "Post Title already exists"; return array('form' => $form, 'error' => $error); } } else { $error = "Invalid fields"; return array('form' => $form, 'error' => $error); } }
  • 47. public function createPost($request) { $entity = new Post(); $form = new MyForm($entity); $form->bind($request); if ($form->isValid()){ $repository = $this->getRepository('MyBundle:Post'); if (!$repository->exists($entity) ) { $repository->save($entity); return $this->redirect('create_ok'); } else { $error = "Post Title already exists"; return array('form' => $form, 'error' => $error); } } else { $error = "Invalid fields"; return array('form' => $form, 'error' => $error); } }
  • 48. public function createPost($request) { $entity = new Post(); $form = new MyForm($entity); $form->bind($request); if ($form->isValid()){ $repository = $this->getRepository('MyBundle:Post'); if (!$repository->exists($entity) ) { $repository->save($entity); return $this->redirect('create_ok'); } else { $error = "Post Title already exists"; return array('form' => $form, 'error' => $error); } } else { $error = "Invalid fields"; return array('form' => $form, 'error' => $error); } }
  • 49. public function createPost($request) { $entity = new Post(); $form = new MyForm($entity); $form->bind($request); if ($form->isValid()){ $repository = $this->getRepository('MyBundle:Post'); if (!$repository->exists($entity) ) { $repository->save($entity); return $this->redirect('create_ok'); } else { $error = "Post Title already exists"; return array('form' => $form, 'error' => $error); } } else { $error = "Invalid fields"; return array('form' => $form, 'error' => $error); } }
  • 50. public function createPost($request) { $entity = new Post(); $form = new MyForm($entity); $form->bind($request); if ($form->isValid()){ $repository = $this->getRepository('MyBundle:Post'); if (!$repository->exists($entity) ) { $repository->save($entity); return $this->redirect('create_ok'); } else { $error = "Post Title already exists"; return array('form' => $form, 'error' => $error); } } else { $error = "Invalid fields"; return array('form' => $form, 'error' => $error); } }
  • 51. public function createPost($request) { $entity = new Post(); $form = new MyForm($entity); $form->bind($request); if ($form->isValid()){ $repository = $this->getRepository('MyBundle:Post'); if (!$repository->exists($entity) ) { $repository->save($entity); return $this->redirect('create_ok'); } else { $error = "Post Title already exists"; return array('form' => $form, 'error' => $error); } } else { $error = "Invalid fields"; return array('form' => $form, 'error' => $error); } }
  • 52. public function createPost($request) { $entity = new Post(); $form = new MyForm($entity); $form->bind($request); if ($form->isValid()){ $repository = $this->getRepository('MyBundle:Post'); if (!$repository->exists($entity) ) { $repository->save($entity); return $this->redirect('create_ok'); } else { $error = "Post Title already exists"; return array('form' => $form, 'error' => $error); } } else { $error = "Invalid fields"; return array('form' => $form, 'error' => $error); } }
  • 53. public function createPost($request) { $entity = new Post(); $form = new MyForm($entity); $form->bind($request); if ($form->isValid()){ $repository = $this->getRepository('MyBundle:Post'); if (!$repository->exists($entity) ) { $repository->save($entity); intermediate variable return $this->redirect('create_ok'); } else { $error = "Post Title already exists"; return array('form' => $form, 'error' => $error); } intermediate variable } else { $error = "Invalid fields"; return array('form' => $form, 'error' => $error); } }
  • 54. public function createPost($request) { $entity = new Post(); $repository = $this->getRepository('MyBundle:Post'); $form = new MyForm($entity); $form->bind($request); if ( ! $form->isValid()){ return array('form' => $form, 'error' => 'Invalid fields'); } if ($repository->exists($entity)){ return array('form' => $form, 'error' => 'Duplicate post title'); } $repository->save($entity); return $this->redirect('create_ok'); }
  • 55. public function createPost($request) { $entity = new Post(); $repository = $this->getRepository('MyBundle:Post'); $form = new MyForm($entity); $form->bind($request); if ( ! $form->isValid()){ return array('form' => $form, 'error' => 'Invalid fields'); } if ($repository->exists($entity)){ return array('form' => $form, 'error' => 'Duplicate post title'); } $repository->save($entity); return $this->redirect('create_ok'); }
  • 56. public function createPost($request) { $entity = new Post(); $repository = $this->getRepository('MyBundle:Post'); $form = new MyForm($entity); $form->bind($request); removed intermediates if ( ! $form->isValid()){ return array('form' => $form, 'error' => 'Invalid fields'); } if ($repository->exists($entity)){ return array('form' => $form, 'error' => 'Duplicate post title'); } $repository->save($entity); return $this->redirect('create_ok'); }
  • 57. public function createPost($request) { $entity = new Post(); $repository = $this->getRepository('MyBundle:Post'); $form = new MyForm($entity); $form->bind($request); removed intermediates if ( ! $form->isValid()){ return array('form' => $form, 'error' => 'Invalid fields'); } early return if ($repository->exists($entity)){ return array('form' => $form, 'error' => 'Duplicate post title'); } $repository->save($entity); return $this->redirect('create_ok'); }
  • 58. Separate code into blocks. public function createPost($request) { Its like using $entity = new Post(); $repository = $this->getRepository('MyBundle:Post'); Paragraphs. $form = new MyForm($entity); $form->bind($request); removed intermediates if ( ! $form->isValid()){ return array('form' => $form, 'error' => 'Invalid fields'); } early return if ($repository->exists($entity)){ return array('form' => $form, 'error' => 'Duplicate post title'); } $repository->save($entity); return $this->redirect('create_ok'); }
  • 59. Key Benefits • Helps avoid code duplication • Makes code clearer (single path)
  • 60. Ad ap OC #3 te d “Wrap all primitive types and string, if it has behaviour”
  • 61. class UIComponent { //... public function repaint($animate = true){ //... } } //... $component->repaint(false);
  • 62. class UIComponent { //... public function repaint($animate = true){ //... } } //... $component->repaint(false);
  • 63. class UIComponent { //... public function repaint($animate = true){ //... } } //... $component->repaint(false); unclear operation
  • 64. class UIComponent { //... public function repaint( Animate $animate ){ //... } } class Animate { public $animate; public function __construct( $animate = true ) { $this->animate = $animate;} } //... $component->repaint( new Animate(false) );
  • 65. class UIComponent { //... public function repaint( Animate $animate ){ //... } } class Animate This can now encapsulate all { animation related operations public $animate; public function __construct( $animate = true ) { $this->animate = $animate;} } //... $component->repaint( new Animate(false) );
  • 66. Key Benefits • Type Hinting • Encapsulation of operations
  • 67. Ad ap te d OC #4 “Only one -> per line, if not getter or fluent”
  • 68. Source: CodeIgniter $this->base_url = $this->CI->config->site_url().'/'.$this->CI->uri->segment(1).$this- >CI->uri->slash_segment(2, 'both'); $this->base_uri = $this->CI->uri->segment(1).$this->CI->uri->slash_segment(2, 'leading');
  • 69. Source: CodeIgniter properties are harder to mock $this->base_url = $this->CI->config->site_url().'/'.$this->CI->uri->segment(1).$this- >CI->uri->slash_segment(2, 'both'); $this->base_uri = $this->CI->uri->segment(1).$this->CI->uri->slash_segment(2, 'leading');
  • 70. Source: CodeIgniter properties are harder to mock $this->base_url = $this->CI->config->site_url().'/'.$this->CI->uri->segment(1).$this- >CI->uri->slash_segment(2, 'both'); no whitespace $this->base_uri = $this->CI->uri->segment(1).$this->CI->uri->slash_segment(2, 'leading');
  • 71. Source: CodeIgniter properties are harder to mock $this->base_url = $this->CI->config->site_url().'/'.$this->CI->uri->segment(1).$this- >CI->uri->slash_segment(2, 'both'); no whitespace $this->base_uri = $this->CI->uri->segment(1).$this->CI->uri->slash_segment(2, 'leading'); - Underlying encapsulation problem - Hard to debug and test - Hard to read and understand
  • 72. Source: CodeIgniter properties are harder to mock $this->base_url = $this->CI->config->site_url().'/'.$this->CI->uri->segment(1).$this- >CI->uri->slash_segment(2, 'both'); no whitespace $this->base_uri = $this->CI->uri->segment(1).$this->CI->uri->slash_segment(2, 'leading'); move everything to uri object $this->getCI()->getUriBuilder()->getBaseUri(‘leading’); - Underlying encapsulation problem - Hard to debug and test - Hard to read and understand
  • 73. Source: Zend Framework App $filterChain->addFilter(new Zend_Filter_Alpha()) ->addFilter(new Zend_Filter_StringToLower()); Source: Symfony 2 Docs.
  • 74. Source: Zend Framework App fluent interface $filterChain->addFilter(new Zend_Filter_Alpha()) ->addFilter(new Zend_Filter_StringToLower()); Source: Symfony 2 Docs.
  • 75. Source: Zend Framework App fluent interface $filterChain->addFilter(new Zend_Filter_Alpha()) ->addFilter(new Zend_Filter_StringToLower()); operator alignment Source: Symfony 2 Docs.
  • 76. Source: Zend Framework App fluent interface $filterChain->addFilter(new Zend_Filter_Alpha()) ->addFilter(new Zend_Filter_StringToLower()); operator alignment $user = $this->get('security.context')->getToken()->getUser(); Source: Symfony 2 Docs.
  • 77. Source: Zend Framework App fluent interface $filterChain->addFilter(new Zend_Filter_Alpha()) ->addFilter(new Zend_Filter_StringToLower()); operator alignment only getters (no operations) $user = $this->get('security.context')->getToken()->getUser(); Source: Symfony 2 Docs.
  • 78. Source: Zend Framework App fluent interface $filterChain->addFilter(new Zend_Filter_Alpha()) ->addFilter(new Zend_Filter_StringToLower()); operator alignment only getters (no operations) $user = $this->get('security.context')->getToken()->getUser(); Source: Symfony 2 Docs.
  • 79. Source: Zend Framework App fluent interface $filterChain->addFilter(new Zend_Filter_Alpha()) ->addFilter(new Zend_Filter_StringToLower()); operator alignment only getters (no operations) $user = $this->get('security.context')->getToken()->getUser(); where did my autocomplete go? Source: Symfony 2 Docs.
  • 80. Source: Zend Framework App fluent interface $filterChain->addFilter(new Zend_Filter_Alpha()) ->addFilter(new Zend_Filter_StringToLower()); operator alignment only getters (no operations) $user = $this->get('security.context')->getToken()->getUser(); where did my return null? autocomplete go? Source: Symfony 2 Docs.
  • 81. Key Benefits • Readability • Easier Mocking • Easier to Debug • Demeter’s Law
  • 82. OC #5 “Do not Abbreviate”
  • 83. if($sx >= $sy) { if ($sx > $strSysMatImgW) { $ny = $strSysMatImgW * $sy / $sx; $nx = $strSysMatImgW; } if ($ny > $strSysMatImgH) { $nx = $strSysMatImgH * $sx / $sy; $ny = $strSysMatImgH; } } else { if ($sy > $strSysMatImgH) { $nx = $strSysMatImgH * $sx / $sy; $ny = $strSysMatImgH; } if($nx > $strSysMatImgW) { $ny = $strSysMatImgW * $sy / $sx; $nx = $strSysMatImgW; } }
  • 84. ? if($sx >= $sy) { ? if ($sx > $strSysMatImgW) { $ny = $strSysMatImgW * $sy / $sx; $nx = $strSysMatImgW; } ? if ($ny > $strSysMatImgH) { $nx = $strSysMatImgH * $sx / $sy; $ny = $strSysMatImgH; } } else { ? if ($sy > $strSysMatImgH) { $nx = $strSysMatImgH * $sx / $sy; $ny = $strSysMatImgH; } ? if($nx > $strSysMatImgW) { $ny = $strSysMatImgW * $sy / $sx; $nx = $strSysMatImgW; } }
  • 85. Why?
  • 86. Why? Its repeated many times, and i’m lazy.
  • 87. Why? Its repeated many times, and i’m lazy. Underlying Problem! You need to transfer those operations into a separate class.
  • 89. Why? function processResponseHeadersAndDefineOutput($response) { ... } This method name is too long to type, and i’m lazy.
  • 90. Why? more then one responsibility? function processResponseHeadersAndDefineOutput($response) { ... } This method name is too long to type, and i’m lazy.
  • 91. function getPage($data) { ... } function startProcess() { ... } $tr->process(“site.login”);
  • 92. get from where? function getPage($data) { ... } function startProcess() { ... } $tr->process(“site.login”);
  • 93. get from where? Use clearer names: function getPage($data) { ... } fetchPage() downloadPage() function startProcess() { ... } $tr->process(“site.login”);
  • 94. get from where? Use clearer names: function getPage($data) { ... } fetchPage() downloadPage() Use a thesaurus: function startProcess() { ... } fork, create, begin, open $tr->process(“site.login”);
  • 95. get from where? Use clearer names: function getPage($data) { ... } fetchPage() downloadPage() Use a thesaurus: function startProcess() { ... } fork, create, begin, open Table row? $tr->process(“site.login”);
  • 96. get from where? Use clearer names: function getPage($data) { ... } fetchPage() downloadPage() Use a thesaurus: function startProcess() { ... } fork, create, begin, open Table row? Easy understanding, complete scope: $tr->process(“site.login”); $translatorService
  • 97. Key Benefits • Clearer communication • Indicates underlying problems
  • 98. Ad ap te d OC #6 “Keep your classes small”
  • 99. 100 lines per class 15 classes per package
  • 100. Increased to include docblocks 100 lines per class 15 classes per package
  • 101. Increased to include docblocks 15-20 lines per method 100 lines per class 15 classes per package
  • 102. Increased to include docblocks 15-20 lines per method 100 lines per class 15 classes per package read this as namespace or folder
  • 103. Key Benefits • Single Responsibility • Objective methods • Slimmer namespaces • Less clunky folders
  • 104. Ad ap OC #7 te d “Limit the number of instance variables in a class (max: 2 5)”
  • 105. class MyRegistrationService { protected $userService; protected $passwordService; protected $logger; protected $translator; protected $entityManager; protected $imageCropper; // ... }
  • 106. class MyRegistrationService { protected $userService; protected $passwordService; protected $logger; protected $translator; protected $entityManager; protected $imageCropper; // ... } Limit: 5
  • 107. class MyRegistrationService { protected $userService; protected $passwordService; protected $logger; All DB interaction protected $translator; should be in protected $entityManager; userService protected $imageCropper; Use and event based system and move this // ... to listener } Limit: 5
  • 108. Key Benefits • Shorter dependency list • Easier Mocking for unit test
  • 109. OC #8 “Use first class collections”
  • 110. Doctrine: ArrayCollection $collection->getIterator(); $collection->filter(...); $collection->append(...); $collection->map(...);
  • 111. Key Benefits • Implements collection operations • Uses SPL interfaces
  • 112. Dr op pe d OC #9 “Do not use accessors (getter/setter)”
  • 113. /** * THIS CLASS WAS GENERATED BY THE DOCTRINE ORM. DO NOT EDIT THIS FILE. */ class DoctrineTestsModelsCMSCmsUserProxy extends DoctrineTestsModelsCMSCmsUser implements DoctrineORMProxyProxy { public function getId() { $this->__load(); return parent::getId(); } public function getStatus() { $this->__load(); return parent::getStatus(); }
  • 114. /** * THIS CLASS WAS GENERATED BY THE DOCTRINE ORM. DO NOT EDIT THIS FILE. */ class DoctrineTestsModelsCMSCmsUserProxy extends DoctrineTestsModelsCMSCmsUser implements DoctrineORMProxyProxy { public function getId() { $this->__load(); Example: Doctrine uses getters to return parent::getId(); inject lazy loading operations } public function getStatus() { $this->__load(); return parent::getStatus(); }
  • 115. Key Benefits • Injector operations • Encapsulation of transformations
  • 116. Cr ea te d! OC #10 (bonus!) “Document your code!”
  • 117. //check to see if the section above set the $overall_pref variable to void if ($overall_pref == 'void') // implode the revised array of selections in group three into a string // variable so that it can be transferred to the database at the end of the // page $groupthree = implode($groupthree_array, "nr");
  • 118. really? //check to see if the section above set the $overall_pref variable to void if ($overall_pref == 'void') // implode the revised array of selections in group three into a string // variable so that it can be transferred to the database at the end of the // page $groupthree = implode($groupthree_array, "nr");
  • 119. really? //check to see if the section above set the $overall_pref variable to void if ($overall_pref == 'void') // implode the revised array of selections in group three into a string // variable so that it can be transferred to the database at the end of the // page $groupthree = implode($groupthree_array, "nr"); Documenting because i’m doing it wrong in an anusual way
  • 120. $priority = isset($event['priority']) ? $event['priority'] : 0; if (!isset($event['event'])) { throw new InvalidArgumentException(...)); } if (!isset($event['method'])) { $event['method'] = 'on'.preg_replace(array( '/(?<=b)[a-z]/ie', '/[^a-z0-9]/i' ), array('strtoupper("0")', ''), $event['event']); } $definition->addMethodCall( 'addListenerService', array($event['event'], array($listenerId, $event['method']), $priority )); Source: Symfony2
  • 121. $priority = isset($event['priority']) ? $event['priority'] : 0; if (!isset($event['event'])) { throw new InvalidArgumentException(...)); } if (!isset($event['method'])) { $event['method'] = 'on'.preg_replace(array( '/(?<=b)[a-z]/ie', '/[^a-z0-9]/i' ), array('strtoupper("0")', ''), $event['event']); } $definition->addMethodCall( 'addListenerService', array($event['event'], array($listenerId, What does this do? $event['method']), $priority )); Source: Symfony2
  • 122. $priority = isset($event['priority']) ? $event['priority'] : 0; Add a simple comment: if (!isset($event['event'])) { throw new //Strips special chars and camel cases to onXxx InvalidArgumentException(...)); } if (!isset($event['method'])) { $event['method'] = 'on'.preg_replace(array( '/(?<=b)[a-z]/ie', '/[^a-z0-9]/i' ), array('strtoupper("0")', ''), $event['event']); } $definition->addMethodCall( 'addListenerService', array($event['event'], array($listenerId, What does this do? $event['method']), $priority )); Source: Symfony2
  • 123. $priority = isset($event['priority']) ? $event['priority'] : 0; Add a simple comment: if (!isset($event['event'])) { throw new //Strips special chars and camel cases to onXxx InvalidArgumentException(...)); } if (!isset($event['method'])) { $event['method'] = 'on'.preg_replace(array( Don’t explain bad '/(?<=b)[a-z]/ie', code, fix it! '/[^a-z0-9]/i' ), array('strtoupper("0")', ''), $event['event']); } $definition->addMethodCall( 'addListenerService', array($event['event'], array($listenerId, What does this do? $event['method']), $priority )); Source: Symfony2
  • 124. /** * Checks whether an element is contained in the collection. * This is an O(n) operation, where n is the size of the collection. * * @todo implement caching for better performance * @param mixed $element The element to search for. * @return boolean TRUE if the collection contains the element, or FALSE. */ function contains($element);
  • 125. /** * Checks whether an element is contained in the collection. * This is an O(n) operation, where n is the size of the collection. * * @todo implement caching for better performance * @param mixed $element The element to search for. * @return boolean TRUE if the collection contains the element, or FALSE. */ function contains($element); mark todo items so the changes don’t get lost
  • 126. A note on cost of running function /** * Checks whether an element is contained in the collection. * This is an O(n) operation, where n is the size of the collection. * * @todo implement caching for better performance * @param mixed $element The element to search for. * @return boolean TRUE if the collection contains the element, or FALSE. */ function contains($element); mark todo items so the changes don’t get lost
  • 127. Do a mind dump, then clean it up. A note on cost of running function /** * Checks whether an element is contained in the collection. * This is an O(n) operation, where n is the size of the collection. * * @todo implement caching for better performance * @param mixed $element The element to search for. * @return boolean TRUE if the collection contains the element, or FALSE. */ function contains($element); mark todo items so the changes don’t get lost
  • 128. Do a mind dump, then clean it up. A note on cost of running function /** * Checks whether an element is contained in the collection. * This is an O(n) operation, where n is the size of the collection. * * @todo implement caching for better performance * @param mixed $element The element to search for. * @return boolean TRUE if the collection contains the element, or FALSE. */ function contains($element); Generate API docs ex: docBlox mark todo items so the changes don’t get lost
  • 129. Key Benefits • Automatic API documentation • Transmission of “line of thought” • Avoids confusion
  • 130. Recap • #1 - Only one indentation level per method. • #2 - Do not use the ‘else’ keyword. • #3 - Wrap primitive types and string, if it has behavior. • #4 - Only one -> per line, if not getter or fluent. • #5 - Do not Abbreviate. • #6 - Keep your classes small • #7 - Limit the number of instance variables in a class (max: 5) • #8 - Use first class collections • #9 - Use accessors (getter/setter) • #10 - Document your code!
  • 131. @rdohms http://doh.ms rafael @doh.ms http://slides.doh.ms Questions? https://joind.in/6749 Got bad code? https://!xthatcode.com
  • 132. The ThoughtWorks Anthology http://goo.gl/OcSNx The Art of Readable Code http://goo.gl/unrij DISCLAIMER: This talk re-uses some of the examples used by Guilherme Blanco in his original Object Calisthenic talk. These principles were studied and applied by us while we worked together in previous jobs. The result taught us all a lesson we really want to spread to other developers.