Clean Code in PHP part 1 of 3

Loading...

Flash Player 9 (or above) is needed to view presentations.
We have detected that you do not have it on your computer. To install it, go here.

0 comments

Post a comment

    Post a comment
    Embed Video
    Edit your comment Cancel

    4 Favorites

    Clean Code in PHP part 1 of 3 - Presentation Transcript

    1. Clean Code “Don’t make a mess” Part 1 of 3 Jan Willem Eshuis
    2. Who is this stranger?
    3. Photo from Flickr: http://flickr.com/photos/97968921@N00/2617607943/
    4. A chameleon:-)
    5. What does he do?
    6. Acting in a lot of roles ‣ As a PHP, Javascript, database programmer ‣ As an architect of several (web) applications ‣ As the owner of JWE new media solutions ‣ As the husband of Kristel (www.kristeleshuis.nl)
    7. Enough about him! Let’s talk about “Clean Code”
    8. In this part ‣ Meaningful names ‣ Functions ‣ Comments
    9. Lot’s of IT projects start with a clean proper desk... Photo from Flickr: http://flickr.com/photos/22634122@N05/2421011780/sizes/l/
    10. But, in a lot of cases it’s a mess at the end Photo from Flickr: http://flickr.com/photos/alienmeatsack/2779516464/sizes/l/
    11. This is why you should use the principals of Clean Code in all your projects.
    12. What happens if your code gets a mess 100 Productivity 75 50 25 0 Time
    13. Meaningful Names ‣ A name must be relevant ‣ No need for comments ‣ The name of a function features a verb ‣ The name must be predictable
    14. What about this code class BankAccount { private $b; //balance on account } ‣ The classname is correct (it tells you what the class is and there is no need for comments) ‣ The name of the private $b is verry bad! (comments are needed to understand)
    15. This is better class BankAccount { private $balance; } or this class BankAccount { private $balanceOnAccount; }
    16. What about this code /** * This function makes a copy from file a to file b */ public function cpFl($a, $b){ copy($a,$b); } ‣ The function name is bad! If you would only see the line cpFl(‘temp.txt’ , ‘/demo/temp.txt’) in you code it’s hard to understand what cpFl is doing ‣ The parameters are bad!. You don’t get to know what they are used for
    17. I would prefer this public function copyFile($source, $destination) { copy($source, $destination); } This is what Clean Code is about
    18. Functions ‣ The name must be relevant ‣ The should be small ‣ The should do one thing! ‣ The should have one level of abstraction
    19. What about this function public function readItems() { $_aNewsItems = array(); $_aLines = file($this->m_sRSSfeed); $_sLines = implode('',$_aLines); $sLines = substr($_sLines,0,strpos($_sLines,'</items>') + 8); $sLines = str_replace('nos:tcmid','tcmid',$sLines); $_objSXML = new SimpleXMLElement( substr($_sLines,0,strpos($_sLines,'</items>') + 8) ); foreach ($_objSXML->item as $_objRow) { foreach ($_objRow as $_sKey => $_sValue) { $_aN[$_sKey] = trim( $_sValue ); } $_aNews[] = $_aN; } for ($a=0; $a < count($_aNews);$a++) { $_aLines = array(); $_aLines = file('$_aNews[$a]['url']); if (count($_aLines)>0) { $_sLines = implode('',$_aLines); $_objXML = new DOMDocument(); $_objXML->loadXML( $_sLines ); $_aItemList = $_objXML->getElementsByTagName('item'); // read al the sport items from the XML for ($i=0; $i < $_aItemList->length; $i++) { $_aNewsItem = array(); $_aNewsRel = array(); $_aNewsAv = array(); $_objItemElement $_aItemList->item($i); = $_aElementList = $_objItemElement->getElementsByTagName('*'); for ($j=0; $j < $_aElementList->length; $j++) { $_objItemField = $_aElementList->item($j); ....
    20. What about this function switch ( $_objItemField->tagName ) { case 'nos:tcmid' : $_aNewsItem['tcmid'] = utf8_decode($_objItemField->nodeValue); break; case 'title' : $_aNewsItem['title'] = utf8_decode($_objItemField->nodeValue); break; case 'description' : $_aNewsItem['description'] = ($_objItemField->nodeValue); break; case 'nos:body' : $_aNewsItem['body'] = ($_objItemField->nodeValue); break; case 'nos:image' : $_aNewsItem['image'] = utf8_decode($_objItemField->nodeValue); break; case 'nos:image_alt': $_aNewsItem['image_alt'] = utf8_decode($_objItemField->nodeValue); break; case 'nos:image_small' : $_aNewsItem['image_small'] = utf8_decode($_objItemField->nodeValue); break; case 'nos:image_small_alt' : $_aNewsItem['image_small_alt'] = utf8_decode($_objItemField->nodeValue); break; case 'nos:image_big' : $_aNewsItem['image_big'] = utf8_decode($_objItemField->nodeValue); break; case 'nos:image_big_alt' : $_aNewsItem['image_big_alt'] = utf8_decode($_objItemField->nodeValue); break; case 'nos:contains_av' : $_aNewsItem['contains'] = $_objItemField->nodeValue; break; case 'pubDate' : $_aNewsItem['readtime'] = date(\"Y-m-d H:i:s\",strtotime($_objItemField->nodeValue)); $_aNewsItem['pubdate'] = date(\"Y-m-d\",strtotime($_objItemField->nodeValue)); $_aNewsItem['pubtime'] = date(\"H:i:s\",strtotime($_objItemField->nodeValue)); break; default : break; } Sorry, there are more lines of code but this does the job.
    21. This code is like spaghetti Photo from Flickr: http://flickr.com/photos/disneymike/217473427/
    22. Explanation ‣ It has a lot of lines of code (the original functions has about 130 lines of code) ‣ It will take a programmer lot’s of time to read and understand all the lines ‣ It uses more than one level of abstraction ‣ It has a uge switch statement
    23. The “Do one thing problem” public function renderAcountBalancePage($account) { $accountBalance = $account->getAccountBalance(); if ($accountBalance>=0) { return $this->renderAcountBalancePositive(); } return $this->renderAccountBalanceNegative(); } ‣ There is no discussion this functions does 3 things.(it gets the account balance, checks if it’s bigger than 0 and returns the result of a render funtion) ‣ But the thing is. It’s all on the same abstration level, we see this as a function doing one thing.
    24. Switch statements public function getAccountBalance($account) { switch ($account->getCurrency()) { case 'eur' : return amountInEuro($this->euro); break; case 'usd' : return amountInUsd($this->euro); break; case 'yen' : return amountInYen($this->euro); break; default : return amountInEuro($this->euro); break; } }
    25. What’s wrong with this switch function? ‣ The function will grow with the use of more currencies ‣ It has to be changed every time a new currency is added ‣ The biggest problem is: There are probably more functions than use the same switch statement
    26. The solution to this problem ‣ Just bury the switch statement in the basement of a abstract factory and don’t show it to anyone ‣ The factory will use the switch statement to create the correct instances of the derivatives of BankAcount and various functions ‣ The functions will be dispatched through the BankAccount interface
    27. A good general rule for a switch statement is that they should only appear once
    28. Example code interface BankAccount { public function getAmount(); } class EuroAccount implements BankAccount { public function getAmount() { } } class DollarAccount implements BankAccount { public function getAmount() { } } class BankAccountFactory { public function createBankAccount($accountCurrency) { switch ($accountCurrency) { case 'eur': return new EuroAccount(); break; case 'usd': return new EuroAccount(); break; default : return new EuroAccount(); break; } } }
    29. Comments ‣ Should be avoided ‣ Less comment is better!
    30. Example // Check if the amount of money on the account is positive // and if the account is active if ( ($this->amount>0) && ($this->active==1) ){ return renderAcountInGreen(); } else { return renderAcountInRed (); } I think the code below is better ( $this->isActiveAndPositive() ){ if return renderAcountInGreen; } else { return renderAcountInRed; }
    31. Another example /** * This function make a copy of the source * file to the destination location * * @param string $source * @param string $destination */ public function copyFile($source, $destination) { copy($source, $destination); } ‣ The description of this function has no meaning ‣ The rest of the comments also make no sense
    32. Questions? Ask them and i’ll try to answer them
    33. Jan Willem Eshuis Phone : +31 (0)6 2001 3300 E-mail : janwillem@jwe.nl Company : www.jwe.nl Weblog : www.janwillemeshuis.nl Linkedin: www.linkedin.com/in/janwillem Twitter : www.twitter.com/jweshuis

    + Jan Willem EshuisJan Willem Eshuis, 8 months ago

    custom

    715 views, 4 favs, 2 embeds more stats

    This is the first part of a couple of presenations more

    More info about this document

    © All Rights Reserved

    Go to text version

    • Total Views 715
      • 692 on SlideShare
      • 23 from embeds
    • Comments 0
    • Favorites 4
    • Downloads 0
    Most viewed embeds
    • 22 views on http://www.janwillemeshuis.nl
    • 1 views on http://www.slideshare.net

    more

    All embeds
    • 22 views on http://www.janwillemeshuis.nl
    • 1 views on http://www.slideshare.net

    less

    Flagged as inappropriate Flag as inappropriate
    Flag as inappropriate

    Select your reason for flagging this presentation as inappropriate. If needed, use the feedback form to let us know more details.

    Cancel
    File a copyright complaint
    Having problems? Go to our helpdesk?

    Categories