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




            Rafael Dohms
photo credit: Eli White
   Rafael Dohms
        @rdohms

 Evangelist, Speaker and
      Contributor.

 Podcaster, User Group
        Leader.

Developer at WEBclusive.
What’s the talk about?


• Why does my code suck?
• How can we fix it?
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 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?
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
                            Important:

                         PHP != JAVA

                    Adaptations will be done
“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;

    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
          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($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         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
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);
         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);
    }

}
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);


                  unclear operation
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




                         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




    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;
    }
}
Why?


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

  You need to transfer those operations into a separate class.
Why?
                          more then one
                          responsibility?

function processResponseHeadersAndDefineOutput($response) { ... }




      This method name is too long to type,
                 and i’m lazy.
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”
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;
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();          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!”
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;
                            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
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/6675
Recommended Links:


                    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
 
Hacking Your Way To Better Security - Dutch PHP Conference 2016
Hacking Your Way To Better Security - Dutch PHP Conference 2016Hacking Your Way To Better Security - Dutch PHP Conference 2016
Hacking Your Way To Better Security - Dutch PHP Conference 2016Colin O'Dell
 
50 Laravel Tricks in 50 Minutes
50 Laravel Tricks in 50 Minutes50 Laravel Tricks in 50 Minutes
50 Laravel Tricks in 50 MinutesAzim Kurt
 
The History of PHPersistence
The History of PHPersistenceThe History of PHPersistence
The History of PHPersistenceHugo Hamon
 
Database Design Patterns
Database Design PatternsDatabase Design Patterns
Database Design PatternsHugo Hamon
 
Adding Dependency Injection to Legacy Applications
Adding Dependency Injection to Legacy ApplicationsAdding Dependency Injection to Legacy Applications
Adding Dependency Injection to Legacy ApplicationsSam Hennessy
 
Introduction to DI(C)
Introduction to DI(C)Introduction to DI(C)
Introduction to DI(C)Radek Benkel
 
PHPUnit でよりよくテストを書くために
PHPUnit でよりよくテストを書くためにPHPUnit でよりよくテストを書くために
PHPUnit でよりよくテストを書くためにYuya Takeyama
 
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
 
Lithium: The Framework for People Who Hate Frameworks
Lithium: The Framework for People Who Hate FrameworksLithium: The Framework for People Who Hate Frameworks
Lithium: The Framework for People Who Hate FrameworksNate Abele
 
Crafting beautiful software
Crafting beautiful softwareCrafting beautiful software
Crafting beautiful softwareJorn Oomen
 
Rich domain model with symfony 2.5 and doctrine 2.5
Rich domain model with symfony 2.5 and doctrine 2.5Rich domain model with symfony 2.5 and doctrine 2.5
Rich domain model with symfony 2.5 and doctrine 2.5Leonardo Proietti
 
Drupal - dbtng 25th Anniversary Edition
Drupal - dbtng 25th Anniversary EditionDrupal - dbtng 25th Anniversary Edition
Drupal - dbtng 25th Anniversary Editionddiers
 
Advanced php testing in action
Advanced php testing in actionAdvanced php testing in action
Advanced php testing in actionJace Ju
 
Symfony2, creare bundle e valore per il cliente
Symfony2, creare bundle e valore per il clienteSymfony2, creare bundle e valore per il cliente
Symfony2, creare bundle e valore per il clienteLeonardo Proietti
 
Symfony2 Building on Alpha / Beta technology
Symfony2 Building on Alpha / Beta technologySymfony2 Building on Alpha / Beta technology
Symfony2 Building on Alpha / Beta technologyDaniel Knell
 
The State of Lithium
The State of LithiumThe State of Lithium
The State of LithiumNate Abele
 
Design Patterns avec PHP 5.3, Symfony et Pimple
Design Patterns avec PHP 5.3, Symfony et PimpleDesign Patterns avec PHP 5.3, Symfony et Pimple
Design Patterns avec PHP 5.3, Symfony et PimpleHugo Hamon
 

Was ist angesagt? (20)

購物車程式架構簡介
購物車程式架構簡介購物車程式架構簡介
購物車程式架構簡介
 
Hacking Your Way To Better Security - Dutch PHP Conference 2016
Hacking Your Way To Better Security - Dutch PHP Conference 2016Hacking Your Way To Better Security - Dutch PHP Conference 2016
Hacking Your Way To Better Security - Dutch PHP Conference 2016
 
Mocking Demystified
Mocking DemystifiedMocking Demystified
Mocking Demystified
 
50 Laravel Tricks in 50 Minutes
50 Laravel Tricks in 50 Minutes50 Laravel Tricks in 50 Minutes
50 Laravel Tricks in 50 Minutes
 
The History of PHPersistence
The History of PHPersistenceThe History of PHPersistence
The History of PHPersistence
 
Database Design Patterns
Database Design PatternsDatabase Design Patterns
Database Design Patterns
 
Adding Dependency Injection to Legacy Applications
Adding Dependency Injection to Legacy ApplicationsAdding Dependency Injection to Legacy Applications
Adding Dependency Injection to Legacy Applications
 
Introduction to DI(C)
Introduction to DI(C)Introduction to DI(C)
Introduction to DI(C)
 
PHPUnit でよりよくテストを書くために
PHPUnit でよりよくテストを書くためにPHPUnit でよりよくテストを書くために
PHPUnit でよりよくテストを書くために
 
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
 
Lithium: The Framework for People Who Hate Frameworks
Lithium: The Framework for People Who Hate FrameworksLithium: The Framework for People Who Hate Frameworks
Lithium: The Framework for People Who Hate Frameworks
 
Crafting beautiful software
Crafting beautiful softwareCrafting beautiful software
Crafting beautiful software
 
Rich domain model with symfony 2.5 and doctrine 2.5
Rich domain model with symfony 2.5 and doctrine 2.5Rich domain model with symfony 2.5 and doctrine 2.5
Rich domain model with symfony 2.5 and doctrine 2.5
 
Drupal - dbtng 25th Anniversary Edition
Drupal - dbtng 25th Anniversary EditionDrupal - dbtng 25th Anniversary Edition
Drupal - dbtng 25th Anniversary Edition
 
Advanced php testing in action
Advanced php testing in actionAdvanced php testing in action
Advanced php testing in action
 
Symfony2, creare bundle e valore per il cliente
Symfony2, creare bundle e valore per il clienteSymfony2, creare bundle e valore per il cliente
Symfony2, creare bundle e valore per il cliente
 
Your Entity, Your Code
Your Entity, Your CodeYour Entity, Your Code
Your Entity, Your Code
 
Symfony2 Building on Alpha / Beta technology
Symfony2 Building on Alpha / Beta technologySymfony2 Building on Alpha / Beta technology
Symfony2 Building on Alpha / Beta technology
 
The State of Lithium
The State of LithiumThe State of Lithium
The State of Lithium
 
Design Patterns avec PHP 5.3, Symfony et Pimple
Design Patterns avec PHP 5.3, Symfony et PimpleDesign Patterns avec PHP 5.3, Symfony et Pimple
Design Patterns avec PHP 5.3, Symfony et Pimple
 

Andere mochten auch

オブジェクト指向できていますか?
オブジェクト指向できていますか?オブジェクト指向できていますか?
オブジェクト指向できていますか?Moriharu Ohzu
 
ソースコードの品質向上のための効果的で効率的なコードレビュー
ソースコードの品質向上のための効果的で効率的なコードレビューソースコードの品質向上のための効果的で効率的なコードレビュー
ソースコードの品質向上のための効果的で効率的なコードレビューMoriharu Ohzu
 
オブジェクト指向エクササイズのススメ
オブジェクト指向エクササイズのススメオブジェクト指向エクササイズのススメ
オブジェクト指向エクササイズのススメYoji Kanno
 
人工知能に何ができないか
人工知能に何ができないか人工知能に何ができないか
人工知能に何ができないかなおき きしだ
 
コンピューティングとJava~なにわTECH道
コンピューティングとJava~なにわTECH道コンピューティングとJava~なにわTECH道
コンピューティングとJava~なにわTECH道なおき きしだ
 
プログラマは何を勉強するか
プログラマは何を勉強するかプログラマは何を勉強するか
プログラマは何を勉強するかなおき きしだ
 
NetBeansのメモリ使用ログから機械学習できしだが働いてるかどうか判定する
NetBeansのメモリ使用ログから機械学習できしだが働いてるかどうか判定するNetBeansのメモリ使用ログから機械学習できしだが働いてるかどうか判定する
NetBeansのメモリ使用ログから機械学習できしだが働いてるかどうか判定するなおき きしだ
 
JavaOne2017で感じた、Javaのいまと未来 in 大阪
JavaOne2017で感じた、Javaのいまと未来 in 大阪JavaOne2017で感じた、Javaのいまと未来 in 大阪
JavaOne2017で感じた、Javaのいまと未来 in 大阪なおき きしだ
 
だれも教えてくれないJavaの世界。 あと、ぼくが会社員になったわけ。
だれも教えてくれないJavaの世界。 あと、ぼくが会社員になったわけ。だれも教えてくれないJavaの世界。 あと、ぼくが会社員になったわけ。
だれも教えてくれないJavaの世界。 あと、ぼくが会社員になったわけ。なおき きしだ
 
オブジェクト指向やめましょう
オブジェクト指向やめましょうオブジェクト指向やめましょう
オブジェクト指向やめましょうなおき きしだ
 
増え続ける情報に対応するためのFPGA基礎知識
増え続ける情報に対応するためのFPGA基礎知識増え続ける情報に対応するためのFPGA基礎知識
増え続ける情報に対応するためのFPGA基礎知識なおき きしだ
 
良質なコードを高速に書くコツ
良質なコードを高速に書くコツ良質なコードを高速に書くコツ
良質なコードを高速に書くコツShunji Konishi
 
デキるプログラマだけが知っているコードレビュー7つの秘訣
デキるプログラマだけが知っているコードレビュー7つの秘訣デキるプログラマだけが知っているコードレビュー7つの秘訣
デキるプログラマだけが知っているコードレビュー7つの秘訣Masahiro Nishimi
 
Java8 コーディングベストプラクティス and NetBeansのメモリログから...
Java8 コーディングベストプラクティス and NetBeansのメモリログから...Java8 コーディングベストプラクティス and NetBeansのメモリログから...
Java8 コーディングベストプラクティス and NetBeansのメモリログから...なおき きしだ
 

Andere mochten auch (17)

オブジェクト指向できていますか?
オブジェクト指向できていますか?オブジェクト指向できていますか?
オブジェクト指向できていますか?
 
ソースコードの品質向上のための効果的で効率的なコードレビュー
ソースコードの品質向上のための効果的で効率的なコードレビューソースコードの品質向上のための効果的で効率的なコードレビュー
ソースコードの品質向上のための効果的で効率的なコードレビュー
 
オブジェクト指向エクササイズのススメ
オブジェクト指向エクササイズのススメオブジェクト指向エクササイズのススメ
オブジェクト指向エクササイズのススメ
 
Javaプログラミング入門
Javaプログラミング入門Javaプログラミング入門
Javaプログラミング入門
 
人工知能に何ができないか
人工知能に何ができないか人工知能に何ができないか
人工知能に何ができないか
 
JavaOne2016報告
JavaOne2016報告JavaOne2016報告
JavaOne2016報告
 
コンピューティングとJava~なにわTECH道
コンピューティングとJava~なにわTECH道コンピューティングとJava~なにわTECH道
コンピューティングとJava~なにわTECH道
 
プログラマは何を勉強するか
プログラマは何を勉強するかプログラマは何を勉強するか
プログラマは何を勉強するか
 
NetBeansのメモリ使用ログから機械学習できしだが働いてるかどうか判定する
NetBeansのメモリ使用ログから機械学習できしだが働いてるかどうか判定するNetBeansのメモリ使用ログから機械学習できしだが働いてるかどうか判定する
NetBeansのメモリ使用ログから機械学習できしだが働いてるかどうか判定する
 
JavaOne2017で感じた、Javaのいまと未来 in 大阪
JavaOne2017で感じた、Javaのいまと未来 in 大阪JavaOne2017で感じた、Javaのいまと未来 in 大阪
JavaOne2017で感じた、Javaのいまと未来 in 大阪
 
だれも教えてくれないJavaの世界。 あと、ぼくが会社員になったわけ。
だれも教えてくれないJavaの世界。 あと、ぼくが会社員になったわけ。だれも教えてくれないJavaの世界。 あと、ぼくが会社員になったわけ。
だれも教えてくれないJavaの世界。 あと、ぼくが会社員になったわけ。
 
JavaOne報告2017
JavaOne報告2017JavaOne報告2017
JavaOne報告2017
 
オブジェクト指向やめましょう
オブジェクト指向やめましょうオブジェクト指向やめましょう
オブジェクト指向やめましょう
 
増え続ける情報に対応するためのFPGA基礎知識
増え続ける情報に対応するためのFPGA基礎知識増え続ける情報に対応するためのFPGA基礎知識
増え続ける情報に対応するためのFPGA基礎知識
 
良質なコードを高速に書くコツ
良質なコードを高速に書くコツ良質なコードを高速に書くコツ
良質なコードを高速に書くコツ
 
デキるプログラマだけが知っているコードレビュー7つの秘訣
デキるプログラマだけが知っているコードレビュー7つの秘訣デキるプログラマだけが知っているコードレビュー7つの秘訣
デキるプログラマだけが知っているコードレビュー7つの秘訣
 
Java8 コーディングベストプラクティス and NetBeansのメモリログから...
Java8 コーディングベストプラクティス and NetBeansのメモリログから...Java8 コーディングベストプラクティス and NetBeansのメモリログから...
Java8 コーディングベストプラクティス and NetBeansのメモリログから...
 

Ähnlich wie Your code sucks, let's fix it - DPC UnCon

You code sucks, let's fix it
You code sucks, let's fix itYou code sucks, let's fix it
You code sucks, let's fix itRafael Dohms
 
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
 
laravel tricks in 50minutes
laravel tricks in 50minuteslaravel tricks in 50minutes
laravel tricks in 50minutesBarang CK
 
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
 
Dependency Injection
Dependency InjectionDependency Injection
Dependency InjectionRifat Nabi
 
Tidy Up Your Code
Tidy Up Your CodeTidy Up Your Code
Tidy Up Your CodeAbbas Ali
 
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
 
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
 
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
 
JavaScript for PHP developers
JavaScript for PHP developersJavaScript for PHP developers
JavaScript for PHP developersStoyan Stefanov
 
Propel sfugmd
Propel sfugmdPropel sfugmd
Propel sfugmdiKlaus
 
Coding for Scale and Sanity
Coding for Scale and SanityCoding for Scale and Sanity
Coding for Scale and SanityJimKellerES
 
SPL: The Missing Link in Development
SPL: The Missing Link in DevelopmentSPL: The Missing Link in Development
SPL: The Missing Link in Developmentjsmith92
 
Introduction à CoffeeScript pour ParisRB
Introduction à CoffeeScript pour ParisRB Introduction à CoffeeScript pour ParisRB
Introduction à CoffeeScript pour ParisRB jhchabran
 
WordPress as an application framework
WordPress as an application frameworkWordPress as an application framework
WordPress as an application frameworkDustin Filippini
 

Ähnlich wie Your code sucks, let's fix it - DPC UnCon (20)

You code sucks, let's fix it
You code sucks, let's fix itYou code sucks, let's fix it
You code sucks, let's fix it
 
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
 
laravel tricks in 50minutes
laravel tricks in 50minuteslaravel tricks in 50minutes
laravel tricks in 50minutes
 
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
 
Dependency Injection
Dependency InjectionDependency Injection
Dependency Injection
 
Oops in php
Oops in phpOops in php
Oops in php
 
Tidy Up Your Code
Tidy Up Your CodeTidy Up Your Code
Tidy Up Your Code
 
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
 
Unit testing with zend framework tek11
Unit testing with zend framework tek11Unit testing with zend framework tek11
Unit testing with zend framework tek11
 
Unit testing with zend framework PHPBenelux
Unit testing with zend framework PHPBeneluxUnit testing with zend framework PHPBenelux
Unit testing with zend framework PHPBenelux
 
JavaScript for PHP developers
JavaScript for PHP developersJavaScript for PHP developers
JavaScript for PHP developers
 
Propel sfugmd
Propel sfugmdPropel sfugmd
Propel sfugmd
 
Coding for Scale and Sanity
Coding for Scale and SanityCoding for Scale and Sanity
Coding for Scale and Sanity
 
SPL: The Missing Link in Development
SPL: The Missing Link in DevelopmentSPL: The Missing Link in Development
SPL: The Missing Link in Development
 
Min-Maxing Software Costs
Min-Maxing Software CostsMin-Maxing Software Costs
Min-Maxing Software Costs
 
Introduction à CoffeeScript pour ParisRB
Introduction à CoffeeScript pour ParisRB Introduction à CoffeeScript pour ParisRB
Introduction à CoffeeScript pour ParisRB
 
Bacbkone js
Bacbkone jsBacbkone js
Bacbkone js
 
Unit testing zend framework apps
Unit testing zend framework appsUnit testing zend framework apps
Unit testing zend framework apps
 
Drupal7 dbtng
Drupal7  dbtngDrupal7  dbtng
Drupal7 dbtng
 
WordPress as an application framework
WordPress as an application frameworkWordPress as an application framework
WordPress as an application framework
 

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
 
Composer The Right Way - 010PHP
Composer The Right Way - 010PHPComposer The Right Way - 010PHP
Composer The Right Way - 010PHPRafael 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
 

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
 
Composer The Right Way - 010PHP
Composer The Right Way - 010PHPComposer The Right Way - 010PHP
Composer The Right Way - 010PHP
 
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.
 

Kürzlich hochgeladen

The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...
The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...
The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...Aggregage
 
Basic Building Blocks of Internet of Things.
Basic Building Blocks of Internet of Things.Basic Building Blocks of Internet of Things.
Basic Building Blocks of Internet of Things.YounusS2
 
AI You Can Trust - Ensuring Success with Data Integrity Webinar
AI You Can Trust - Ensuring Success with Data Integrity WebinarAI You Can Trust - Ensuring Success with Data Integrity Webinar
AI You Can Trust - Ensuring Success with Data Integrity WebinarPrecisely
 
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPA
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPAAnypoint Code Builder , Google Pub sub connector and MuleSoft RPA
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPAshyamraj55
 
Secure your environment with UiPath and CyberArk technologies - Session 1
Secure your environment with UiPath and CyberArk technologies - Session 1Secure your environment with UiPath and CyberArk technologies - Session 1
Secure your environment with UiPath and CyberArk technologies - Session 1DianaGray10
 
20230202 - Introduction to tis-py
20230202 - Introduction to tis-py20230202 - Introduction to tis-py
20230202 - Introduction to tis-pyJamie (Taka) Wang
 
Building AI-Driven Apps Using Semantic Kernel.pptx
Building AI-Driven Apps Using Semantic Kernel.pptxBuilding AI-Driven Apps Using Semantic Kernel.pptx
Building AI-Driven Apps Using Semantic Kernel.pptxUdaiappa Ramachandran
 
Empowering Africa's Next Generation: The AI Leadership Blueprint
Empowering Africa's Next Generation: The AI Leadership BlueprintEmpowering Africa's Next Generation: The AI Leadership Blueprint
Empowering Africa's Next Generation: The AI Leadership BlueprintMahmoud Rabie
 
Introduction to Matsuo Laboratory (ENG).pptx
Introduction to Matsuo Laboratory (ENG).pptxIntroduction to Matsuo Laboratory (ENG).pptx
Introduction to Matsuo Laboratory (ENG).pptxMatsuo Lab
 
Videogame localization & technology_ how to enhance the power of translation.pdf
Videogame localization & technology_ how to enhance the power of translation.pdfVideogame localization & technology_ how to enhance the power of translation.pdf
Videogame localization & technology_ how to enhance the power of translation.pdfinfogdgmi
 
Using IESVE for Loads, Sizing and Heat Pump Modeling to Achieve Decarbonization
Using IESVE for Loads, Sizing and Heat Pump Modeling to Achieve DecarbonizationUsing IESVE for Loads, Sizing and Heat Pump Modeling to Achieve Decarbonization
Using IESVE for Loads, Sizing and Heat Pump Modeling to Achieve DecarbonizationIES VE
 
AI Fame Rush Review – Virtual Influencer Creation In Just Minutes
AI Fame Rush Review – Virtual Influencer Creation In Just MinutesAI Fame Rush Review – Virtual Influencer Creation In Just Minutes
AI Fame Rush Review – Virtual Influencer Creation In Just MinutesMd Hossain Ali
 
COMPUTER 10: Lesson 7 - File Storage and Online Collaboration
COMPUTER 10: Lesson 7 - File Storage and Online CollaborationCOMPUTER 10: Lesson 7 - File Storage and Online Collaboration
COMPUTER 10: Lesson 7 - File Storage and Online Collaborationbruanjhuli
 
Nanopower In Semiconductor Industry.pdf
Nanopower  In Semiconductor Industry.pdfNanopower  In Semiconductor Industry.pdf
Nanopower In Semiconductor Industry.pdfPedro Manuel
 
Cybersecurity Workshop #1.pptx
Cybersecurity Workshop #1.pptxCybersecurity Workshop #1.pptx
Cybersecurity Workshop #1.pptxGDSC PJATK
 
Computer 10: Lesson 10 - Online Crimes and Hazards
Computer 10: Lesson 10 - Online Crimes and HazardsComputer 10: Lesson 10 - Online Crimes and Hazards
Computer 10: Lesson 10 - Online Crimes and HazardsSeth Reyes
 
NIST Cybersecurity Framework (CSF) 2.0 Workshop
NIST Cybersecurity Framework (CSF) 2.0 WorkshopNIST Cybersecurity Framework (CSF) 2.0 Workshop
NIST Cybersecurity Framework (CSF) 2.0 WorkshopBachir Benyammi
 
Bird eye's view on Camunda open source ecosystem
Bird eye's view on Camunda open source ecosystemBird eye's view on Camunda open source ecosystem
Bird eye's view on Camunda open source ecosystemAsko Soukka
 
UiPath Platform: The Backend Engine Powering Your Automation - Session 1
UiPath Platform: The Backend Engine Powering Your Automation - Session 1UiPath Platform: The Backend Engine Powering Your Automation - Session 1
UiPath Platform: The Backend Engine Powering Your Automation - Session 1DianaGray10
 

Kürzlich hochgeladen (20)

The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...
The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...
The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...
 
Basic Building Blocks of Internet of Things.
Basic Building Blocks of Internet of Things.Basic Building Blocks of Internet of Things.
Basic Building Blocks of Internet of Things.
 
AI You Can Trust - Ensuring Success with Data Integrity Webinar
AI You Can Trust - Ensuring Success with Data Integrity WebinarAI You Can Trust - Ensuring Success with Data Integrity Webinar
AI You Can Trust - Ensuring Success with Data Integrity Webinar
 
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPA
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPAAnypoint Code Builder , Google Pub sub connector and MuleSoft RPA
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPA
 
Secure your environment with UiPath and CyberArk technologies - Session 1
Secure your environment with UiPath and CyberArk technologies - Session 1Secure your environment with UiPath and CyberArk technologies - Session 1
Secure your environment with UiPath and CyberArk technologies - Session 1
 
20230202 - Introduction to tis-py
20230202 - Introduction to tis-py20230202 - Introduction to tis-py
20230202 - Introduction to tis-py
 
Building AI-Driven Apps Using Semantic Kernel.pptx
Building AI-Driven Apps Using Semantic Kernel.pptxBuilding AI-Driven Apps Using Semantic Kernel.pptx
Building AI-Driven Apps Using Semantic Kernel.pptx
 
Empowering Africa's Next Generation: The AI Leadership Blueprint
Empowering Africa's Next Generation: The AI Leadership BlueprintEmpowering Africa's Next Generation: The AI Leadership Blueprint
Empowering Africa's Next Generation: The AI Leadership Blueprint
 
Introduction to Matsuo Laboratory (ENG).pptx
Introduction to Matsuo Laboratory (ENG).pptxIntroduction to Matsuo Laboratory (ENG).pptx
Introduction to Matsuo Laboratory (ENG).pptx
 
Videogame localization & technology_ how to enhance the power of translation.pdf
Videogame localization & technology_ how to enhance the power of translation.pdfVideogame localization & technology_ how to enhance the power of translation.pdf
Videogame localization & technology_ how to enhance the power of translation.pdf
 
Using IESVE for Loads, Sizing and Heat Pump Modeling to Achieve Decarbonization
Using IESVE for Loads, Sizing and Heat Pump Modeling to Achieve DecarbonizationUsing IESVE for Loads, Sizing and Heat Pump Modeling to Achieve Decarbonization
Using IESVE for Loads, Sizing and Heat Pump Modeling to Achieve Decarbonization
 
AI Fame Rush Review – Virtual Influencer Creation In Just Minutes
AI Fame Rush Review – Virtual Influencer Creation In Just MinutesAI Fame Rush Review – Virtual Influencer Creation In Just Minutes
AI Fame Rush Review – Virtual Influencer Creation In Just Minutes
 
COMPUTER 10: Lesson 7 - File Storage and Online Collaboration
COMPUTER 10: Lesson 7 - File Storage and Online CollaborationCOMPUTER 10: Lesson 7 - File Storage and Online Collaboration
COMPUTER 10: Lesson 7 - File Storage and Online Collaboration
 
Nanopower In Semiconductor Industry.pdf
Nanopower  In Semiconductor Industry.pdfNanopower  In Semiconductor Industry.pdf
Nanopower In Semiconductor Industry.pdf
 
Cybersecurity Workshop #1.pptx
Cybersecurity Workshop #1.pptxCybersecurity Workshop #1.pptx
Cybersecurity Workshop #1.pptx
 
Computer 10: Lesson 10 - Online Crimes and Hazards
Computer 10: Lesson 10 - Online Crimes and HazardsComputer 10: Lesson 10 - Online Crimes and Hazards
Computer 10: Lesson 10 - Online Crimes and Hazards
 
NIST Cybersecurity Framework (CSF) 2.0 Workshop
NIST Cybersecurity Framework (CSF) 2.0 WorkshopNIST Cybersecurity Framework (CSF) 2.0 Workshop
NIST Cybersecurity Framework (CSF) 2.0 Workshop
 
Bird eye's view on Camunda open source ecosystem
Bird eye's view on Camunda open source ecosystemBird eye's view on Camunda open source ecosystem
Bird eye's view on Camunda open source ecosystem
 
201610817 - edge part1
201610817 - edge part1201610817 - edge part1
201610817 - edge part1
 
UiPath Platform: The Backend Engine Powering Your Automation - Session 1
UiPath Platform: The Backend Engine Powering Your Automation - Session 1UiPath Platform: The Backend Engine Powering Your Automation - Session 1
UiPath Platform: The Backend Engine Powering Your Automation - Session 1
 

Your code sucks, let's fix it - DPC UnCon

  • 1. Your code sucks, let’s !x it! Object Calisthenics and Code readability Rafael Dohms
  • 2. photo credit: Eli White Rafael Dohms @rdohms Evangelist, Speaker and Contributor. Podcaster, User Group Leader. Developer at WEBclusive.
  • 3. What’s the talk about? • Why does my code suck? • How can we fix it?
  • 4. Is it Maintainable? Is it Readable? Why does my code suck? Is it Reusable? Is it Testable?
  • 5. <?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); } ?>
  • 6. How do we fix it?
  • 7. 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
  • 8. “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
  • 9. “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
  • 11. OC #1 “Only one indentation level per method”
  • 12. 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; }
  • 13. 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; }
  • 14. 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 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
  • 15. 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
  • 16. Key Benefits • Cohesiveness • Methods does only one thing • Increases re-use
  • 17. OC #2 “Do not use the ‘else’ keyword”
  • 18. 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); } }
  • 19. 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); } }
  • 20. 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); } }
  • 21. 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'); }
  • 22. Key Benefits • Helps avoid code duplication • Makes code clearer (single path)
  • 23. Ad ap OC #3 te d “Wrap all primitive types and string, if it has behaviour”
  • 24. class UIComponent { //... public function repaint($animate = true){ //... } } //... $component->repaint(false); unclear operation
  • 25. 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) );
  • 26. Key Benefits • Type Hinting • Encapsulation of operations
  • 27. Ad ap te d OC #4 “Only one -> per line, if not getter or fluent”
  • 28. 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
  • 29. 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.
  • 30. Key Benefits • Readability • Easier Mocking • Easier to Debug • Demeter’s Law
  • 31. OC #5 “Do not Abbreviate”
  • 32. ? 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; } }
  • 33. Why? Its repeated many times, and i’m lazy. Underlying Problem! You need to transfer those operations into a separate class.
  • 34. Why? more then one responsibility? function processResponseHeadersAndDefineOutput($response) { ... } This method name is too long to type, and i’m lazy.
  • 35. 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
  • 36. Key Benefits • Clearer communication • Indicates underlying problems
  • 37. Ad ap te d OC #6 “Keep your classes small”
  • 38. Increased to include docblocks 15-20 lines per method 100 lines per class 15 classes per package read this as namespace or folder
  • 39. Key Benefits • Single Responsibility • Objective methods • Slimmer namespaces • Less clunky folders
  • 40. Ad ap OC #7 te d “Limit the number of instance variables in a class (max: 2 5)”
  • 41. 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
  • 42. Key Benefits • Shorter dependency list • Easier Mocking for unit test
  • 43. OC #8 “Use first class collections”
  • 44. Doctrine: ArrayCollection $collection->getIterator(); $collection->filter(...); $collection->append(...); $collection->map(...);
  • 45. Key Benefits • Implements collection operations • Uses SPL interfaces
  • 46. Dr op pe d OC #9 “Do not use accessors (getter/setter)”
  • 47. /** * 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(); }
  • 48. Key Benefits • Injector operations • Encapsulation of transformations
  • 49. Cr ea te d! OC #10 (bonus!) “Document your code!”
  • 50. 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
  • 51. $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
  • 52. 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
  • 53. Key Benefits • Automatic API documentation • Transmission of “line of thought” • Avoids confusion
  • 54. 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!
  • 55. @rdohms http://doh.ms rafael @doh.ms http://slides.doh.ms Questions? https://joind.in/6675
  • 56. Recommended Links: 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.