Clean Code Barcelona 2009

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.

1 comments

Comments 1 - 1 of 1 previous next Post a comment

Post a comment
Embed Video
Edit your comment Cancel

2 Favorites & 1 Group

Clean Code Barcelona 2009 - Presentation Transcript

  1. Clean Code PHP Conference Barcelona 31th october 2009 zaterdag 31 oktober 2009
  2. About me zaterdag 31 oktober 2009
  3. This is what i am zaterdag 31 oktober 2009
  4. zaterdag 31 oktober 2009
  5. Golden rules @nos ‣always use version control (SVN) ‣produce readable code ‣test your code ‣refactor your code ‣don’t use comments :-) ‣use extreme programming zaterdag 31 oktober 2009
  6. Clean Code? Why? Because of what you will see in the next presentation zaterdag 31 oktober 2009
  7. This is how most of the projects start zaterdag 31 oktober 2009
  8. This is how most of the projects end zaterdag 31 oktober 2009
  9. Looks great, tastes bad zaterdag 31 oktober 2009
  10. Cost of code 100 Productivity / Cost 75 50 25 0 Time Cost of changes Productivity zaterdag 31 oktober 2009
  11. This is why you should use the principals of clean code zaterdag 31 oktober 2009
  12. About names zaterdag 31 oktober 2009
  13. Meaningfull Names ‣Names must be relevant ‣No need for comments! ‣Name of a function always features a verb ‣Names must be predictable zaterdag 31 oktober 2009
  14. What about this code class BankAccount { private $b; //balance on account } ‣The classname is ok ‣The private $b is verry bad! zaterdag 31 oktober 2009
  15. Better class BankAccount { private $balance; } class BankAccount { private $balanceOnAccount; } zaterdag 31 oktober 2009
  16. What about this /** * This function makes a copy from file a to file b */ ‣ public function cpFl($a, $b){ copy($a,$b); } Somewhere else in your code cpFl(“/demo/file.txt”,”/demo/otherfile.txt”); zaterdag 31 oktober 2009
  17. That was bad ‣The function name is bad! ‣The parameters are bad!. You don’t get to know what they are used for! zaterdag 31 oktober 2009
  18. Solution public function copyFile($source, $destination) { copy($source, $destination); } public function copyFileContents($source, $destination) { copy($source, $destination); } zaterdag 31 oktober 2009
  19. About functions zaterdag 31 oktober 2009
  20. Functions ‣Must have a relevant name ‣Should only do 1 thing ‣Should be small ‣Should have one level of abstraction zaterdag 31 oktober 2009
  21. What about thispublic 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); zaterdag 31 oktober 2009
  22. 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 is more code but this does the job zaterdag 31 oktober 2009
  23. Why it’s a bad function ‣It has 130 lines of code ‣Programmers will need a lot of time to read and understand it ‣It uses more than one level of abstraction ‣And the huge switch statement is ugly zaterdag 31 oktober 2009
  24. Do one thing (good)! public function renderAcountBalancePage() { $accountBalance = $this->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. zaterdag 31 oktober 2009
  25. Maybe this is even better public function renderAcountBalancePage() { if ( $this->accountBalancePositive() ) { return $this->renderAcountBalancePositive(); } return $this->renderAccountBalanceNegative(); } zaterdag 31 oktober 2009
  26. About switch statements zaterdag 31 oktober 2009
  27. Example statement public function getAccountBalance($account) { switch ($account->getCurrency()) { case 'eur' : return amountInEuro($this->_euro); break; case 'usd' : return amountInUsd($this->_usd); break; case 'yen' : return amountInYen($this->_yen); break; default : return amountInEuro($this->_euro); break; } } zaterdag 31 oktober 2009
  28. What’s wrong? ‣The function will keep growing with new currencies ‣It needs to be changed everytime a currency is added ‣Biggest problem is that there are probably more functions using the same statement:-( zaterdag 31 oktober 2009
  29. A good general rule for a switch statement is that they should only appear once zaterdag 31 oktober 2009
  30. The solution for this problem zaterdag 31 oktober 2009
  31. Solution to this problem ‣Bury the statement in a basement of an abstract factory and don’t show it to anyone! ‣The factory will be used to create the correct instance of the derivates of BankAccount and his functions zaterdag 31 oktober 2009
  32. Code interface BankAccount { public function getAmount(); } class EuroAccount implements BakAccount { 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 DollarAccount(); break; default : return new EuroAccount(); break; } } } zaterdag 31 oktober 2009
  33. About comments zaterdag 31 oktober 2009
  34. No comment needed zaterdag 31 oktober 2009
  35. Comments ‣Should be avoided ‣Less comments is better ‣Don’t use comments if you an use a function of variable zaterdag 31 oktober 2009
  36. Example code // 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 (); } zaterdag 31 oktober 2009
  37. This is a lot better if ( $this->isActiveAndPositive() ){ return renderAcountInGreen; } else { return renderAcountInRed; } ‣Comments are gone zaterdag 31 oktober 2009
  38. Another bad 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); } zaterdag 31 oktober 2009
  39. Allowed comments ‣Comments with copyright statements are allowed ‣Informative comments that make sense! ‣Comments needed for api (documentation) purpose zaterdag 31 oktober 2009
  40. If you find a comment in the code try to get rid of it! zaterdag 31 oktober 2009
  41. Formatting zaterdag 31 oktober 2009
  42. It’s like a newspaper zaterdag 31 oktober 2009
  43. Like a newspaper? ‣The headlines decides whether you read it or not ‣The first paragraph is a synopsis of the complete story ‣If you read further you will find more details untill you have all the information zaterdag 31 oktober 2009
  44. Make it look like a newspaper ‣The name of the source file should be simple but explanatory ‣The topmost parts of the file should provide the high-level concepts and algorithms ‣Once we go further down the file, details will increase and at the end we will find the lowest level functions zaterdag 31 oktober 2009
  45. Vertical Openness ‣ Most of the code is read left to right and top to bottom ‣ Each line represents an expression or a clause ‣ Each group of lines represents a thought ‣ Each thought should be seperated with a blank line zaterdag 31 oktober 2009
  46. Bad example class BankAccountFactory { private $currency; public function createBankAccount($accountCurrency) { switch ($accountCurrency) { case 'eur': $this->currency = $accountCurrency; return new EuroAccount(); break; case 'usd': $this->currency = $accountCurrency; return new EuroAccount(); break; default : $this->currency = $accountCurrency; return new EuroAccount(); break; } } public function getType() { return $this->currency; } public function withDrawMoney($amount) { $this->amount = $this->amount - $amount; return $this->amount; } } zaterdag 31 oktober 2009
  47. This is better class BankAccountFactory { private $currency; public function createBankAccount($accountCurrency) { switch ($accountCurrency) { case 'eur': $this->currency = $accountCurrency; return new EuroAccount(); break; case 'usd': $this->currency = $accountCurrency; return new EuroAccount(); break; default : $this->currency = $accountCurrency; return new EuroAccount(); break; } } public function getType() { return $this->currency; } public function withDrawMoney($amount) { $this->amount = $this->amount - $amount; return $this->amount; } } zaterdag 31 oktober 2009
  48. This is how it should be class BankAccountFactory { private $currency; public function createBankAccount($accountCurrency) { switch ($accountCurrency) { case 'eur': $this->currency = $accountCurrency; return new EuroAccount(); break; case 'usd': $this->currency = $accountCurrency; return new EuroAccount(); break; default : $this->currency = $accountCurrency; return new EuroAccount(); break; } } public function getType() { return $this->currency; } public function withDrawMoney($amount) { $this->amount = $this->amount - $amount; return $this->amount; } } zaterdag 31 oktober 2009
  49. Error handling zaterdag 31 oktober 2009
  50. General rules ‣Use exceptions instead of return values for error handling ‣Don’t return “null” ‣Don’t pass “null” zaterdag 31 oktober 2009
  51. Exceptions ‣They make the code cleaner ‣They seperate the “real code” from the “error handling code” ‣Act better on errors zaterdag 31 oktober 2009
  52. Some best practices zaterdag 31 oktober 2009
  53. How we work @NOS ‣projects take no longer than 2 weeks ‣every 2 weeks there is a delivery ‣every step is tested ‣everybody in the team has the overview ‣eXtreme Programming ‣projectmanagers are real managers (they can handle more than 2 projects) zaterdag 31 oktober 2009
  54. Changes are possible ‣every step is evaluated and from that expierience next step(s) are decided ‣you only lose 2 weeks of work when you made the wrong decision ‣that makes is not a problem to take the wrong decision at least you make decisions instead of talking about them zaterdag 31 oktober 2009
  55. Questions? zaterdag 31 oktober 2009
  56. http://twitter.com/jweshuis http://www.janwillemeshuis.nl zaterdag 31 oktober 2009
  57. Titel zaterdag 31 oktober 2009

+ Jan Willem EshuisJan Willem Eshuis, 3 weeks ago

custom

322 views, 2 favs, 1 embeds more stats

The slides of the presentation i gave at phpbarcelo more

More info about this document

© All Rights Reserved

Go to text version

  • Total Views 322
    • 299 on SlideShare
    • 23 from embeds
  • Comments 1
  • Favorites 2
  • Downloads 16
Most viewed embeds
  • 23 views on http://janwillemeshuis.nl

more

All embeds
  • 23 views on http://janwillemeshuis.nl

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

Groups / Events