SlideShare uma empresa Scribd logo
1 de 36
Clean Code and Refactoring




Yuriy Gerasimov
email: yuri.gerasimov@gmail.com
twitter: ygerasimov
skype: yuriy_gerasimov
d.o.: http://drupal.org/user/257311
Disclaimer
●   Not rules but recepies
●   You are not the last person who will look at
    this code
●   Leave the code in better shape that you found
    it
●   Debates are welcome
Learn PHP and Drupal functions
●   Build array (5 => 5, 6 => 6, …, 10 => 10);
    –   drupal_map_assoc(range(5, 10));
●   Sort form element
    –   uasort($form, 'element_sort'); // by #weight
    –   uasort($form, 'element_sort_by_title');
●   Validation: valid_email_address(), valid_url()
●   Get all keys not prefixed with #
    for (element_children($form) as $key) {}
Names
Names
●   Variables, classes – nouns. Methods, functions –
    verbs
●   Shorter variable name for local scope ($i)
●   One name per concept ($user, $account, $person,
    $site_visitor)
●   Domain names ($student, $course, $lesson...)
●   Patterns names (singleton, visitor …)
●   Funciton name prefixes isSomething(),
    setSomething(), getSomething(), doSomething()
Constants
●   Use constants to describe what static vars
    mean
    if ($user->uid == 2)
    if ($user->uid == USER_SUPER_ADMIN_UID )
    if ($user->uid == self::USER_SUPER_ADMIN_UID)
Function names
(double underscore)
Functions
●   Functions should do one thing and be small
    and clean. Example
    menu_execute_active_handler():
    –   Checks whether site is online or not
    –   Executes menu callback
    –   Deliver callback result
●   _menu_router_build() has more than 200
    lines!
Functions
●   Group arguments to eliminate number of
    arguments
●   Pass structures that function is going to alter if
    results are complex
Functions
●   Groupped arguments, apply default values
Function
●   Helper functions underscore prefix
    (_menu_delete_item())
●   Group helper functions into classes with static
    methods. Autoloading.
Comments
●   Comments get outdated first!
●   Comments should be written when we fail to
    find good variables / function names
●   Think twice about names before writing a
    comment explaining your intentions
●   Why it is done this way and not What is this
Spaghetti code
●   Return result early (continue and break cycles)
Spaghetti code (refactored)
Use switch construction
●   (example from locale.inc)
Return conditions
●   simply return value (return ($a == $b); )
●   backup_migrate/includes/destinations.file.inc
Long conditions
●   one condition per line
●   operators in front
●   identation
Use Exceptions
Use Exceptions
●   _io_checkout_page_ajax_validate__if_email_exists()
Use Polymorphism
●   D8 plugins system
●   Views handlers
●   Take a look at function names in form.inc:
    –   form_type_checkbox_value(), theme_checkbox(),
        form_process_checkbox()
    –   form_type_select_value(), theme_select(),
        form_process_select()
Organize your code right
●   Separate files
●   Follow traditions
●   1000 lines – you do it wrong
Organize your code right
●   Sort by source and not by name
●   First hooks implementations, then helpers
Use IDE collapsed view
Do not Repeat Yourself (DRY)
●   panels/includes/plugins.inc
DRY
●   panels/includes/plugins.inc
Functional programming
●   anonymous functions (closures) php 5.3.0
●   variables can be functions
●   functions can be passed as arguments
Functional programming
Functional used
Functional used
Refactoring loves tests
●   Some tests better than
    no tests at all
●   Use DrupalUnitTestCase
    for unit testing (fast)
To read
●   Robert C. Martin. Clean Code: A Handbook of Agile
    Software Craftsmanship
●   Martin Fowler. Refactoring: Improving the Design of
    Existing Code
●   http://www.slideshare.net/rdohms/bettercode-
    phpbenelux212alternate
●   http://london2011.drupal.org/conference/sessions/code-
    stinks
●   http://chicago2011.drupal.org/sessions/aphorisms-api-
    design

Mais conteúdo relacionado

Mais procurados

Clean Code: Chapter 3 Function
Clean Code: Chapter 3 FunctionClean Code: Chapter 3 Function
Clean Code: Chapter 3 FunctionKent Huang
 
Functions in python slide share
Functions in python slide shareFunctions in python slide share
Functions in python slide shareDevashish Kumar
 
Javascript variables and datatypes
Javascript variables and datatypesJavascript variables and datatypes
Javascript variables and datatypesVarun C M
 
Code Refactoring
Code RefactoringCode Refactoring
Code Refactoringkim.mens
 
Pi j1.3 operators
Pi j1.3 operatorsPi j1.3 operators
Pi j1.3 operatorsmcollison
 
Operator Overloading and Scope of Variable
Operator Overloading and Scope of VariableOperator Overloading and Scope of Variable
Operator Overloading and Scope of VariableMOHIT DADU
 
Objects and classes in Visual Basic
Objects and classes in Visual BasicObjects and classes in Visual Basic
Objects and classes in Visual BasicSangeetha Sg
 
JavaScript: Variables and Functions
JavaScript: Variables and FunctionsJavaScript: Variables and Functions
JavaScript: Variables and FunctionsJussi Pohjolainen
 
VB Function and procedure
VB Function and procedureVB Function and procedure
VB Function and procedurepragya ratan
 
Bad Code Smells
Bad Code SmellsBad Code Smells
Bad Code Smellskim.mens
 
Java best practices
Java best practicesJava best practices
Java best practicesRay Toal
 

Mais procurados (20)

Clean Code: Chapter 3 Function
Clean Code: Chapter 3 FunctionClean Code: Chapter 3 Function
Clean Code: Chapter 3 Function
 
Java script basic
Java script basicJava script basic
Java script basic
 
Functions in python slide share
Functions in python slide shareFunctions in python slide share
Functions in python slide share
 
Javascript variables and datatypes
Javascript variables and datatypesJavascript variables and datatypes
Javascript variables and datatypes
 
Code Refactoring
Code RefactoringCode Refactoring
Code Refactoring
 
Java ppt
Java pptJava ppt
Java ppt
 
SOLID Principles
SOLID PrinciplesSOLID Principles
SOLID Principles
 
Pi j1.3 operators
Pi j1.3 operatorsPi j1.3 operators
Pi j1.3 operators
 
Operator Overloading and Scope of Variable
Operator Overloading and Scope of VariableOperator Overloading and Scope of Variable
Operator Overloading and Scope of Variable
 
Objects and classes in Visual Basic
Objects and classes in Visual BasicObjects and classes in Visual Basic
Objects and classes in Visual Basic
 
Functions in Python
Functions in PythonFunctions in Python
Functions in Python
 
JavaScript: Variables and Functions
JavaScript: Variables and FunctionsJavaScript: Variables and Functions
JavaScript: Variables and Functions
 
Java programming-examples
Java programming-examplesJava programming-examples
Java programming-examples
 
Dutch PHP Conference 2013: Distilled
Dutch PHP Conference 2013: DistilledDutch PHP Conference 2013: Distilled
Dutch PHP Conference 2013: Distilled
 
VB Function and procedure
VB Function and procedureVB Function and procedure
VB Function and procedure
 
Bad Code Smells
Bad Code SmellsBad Code Smells
Bad Code Smells
 
Java best practices
Java best practicesJava best practices
Java best practices
 
Functions in python
Functions in python Functions in python
Functions in python
 
Procedure n functions
Procedure n functionsProcedure n functions
Procedure n functions
 
Code generating beans in Java
Code generating beans in JavaCode generating beans in Java
Code generating beans in Java
 

Destaque

Refactoring Tips by Martin Fowler
Refactoring Tips by Martin FowlerRefactoring Tips by Martin Fowler
Refactoring Tips by Martin FowlerIgor Crvenov
 
Code smells and refactoring
Code smells and refactoringCode smells and refactoring
Code smells and refactoringCarlos Mourullo
 
Refactoring code smell
Refactoring code smellRefactoring code smell
Refactoring code smellmartintsch
 
Apache SOLR | Drupal Camp Kyiv 2010
Apache SOLR | Drupal Camp Kyiv 2010Apache SOLR | Drupal Camp Kyiv 2010
Apache SOLR | Drupal Camp Kyiv 2010Yuriy Gerasimov
 
DrupalCafe7 CTools AJAX responder
DrupalCafe7 CTools AJAX responderDrupalCafe7 CTools AJAX responder
DrupalCafe7 CTools AJAX responderYuriy Gerasimov
 
Drupal camp donetsk c tools
Drupal camp donetsk c toolsDrupal camp donetsk c tools
Drupal camp donetsk c toolsYuriy Gerasimov
 
DrupalCamp Kyiv 2011 Services
DrupalCamp Kyiv 2011 ServicesDrupalCamp Kyiv 2011 Services
DrupalCamp Kyiv 2011 ServicesYuriy Gerasimov
 
Taming The Hairy Beast: How the systematic approach help you navigating throu...
Taming The Hairy Beast: How the systematic approach help you navigating throu...Taming The Hairy Beast: How the systematic approach help you navigating throu...
Taming The Hairy Beast: How the systematic approach help you navigating throu...ABDURAHMAN ALSUM
 
Delayed operations with Queues
Delayed operations with QueuesDelayed operations with Queues
Delayed operations with QueuesYuriy Gerasimov
 
Automated ui testing with selenium. drupal con london 2011
Automated ui testing with selenium. drupal con london 2011Automated ui testing with selenium. drupal con london 2011
Automated ui testing with selenium. drupal con london 2011Yuriy Gerasimov
 
Gastcollege > Jongeren & social media > Universiteit Twente
Gastcollege > Jongeren & social media > Universiteit TwenteGastcollege > Jongeren & social media > Universiteit Twente
Gastcollege > Jongeren & social media > Universiteit TwenteEls Dragt
 

Destaque (20)

Mehr Softwarequalität: Team Clean Coding
Mehr Softwarequalität: Team Clean CodingMehr Softwarequalität: Team Clean Coding
Mehr Softwarequalität: Team Clean Coding
 
Refactoring Tips by Martin Fowler
Refactoring Tips by Martin FowlerRefactoring Tips by Martin Fowler
Refactoring Tips by Martin Fowler
 
Code smells and refactoring
Code smells and refactoringCode smells and refactoring
Code smells and refactoring
 
Code Smell
Code SmellCode Smell
Code Smell
 
Code smells
Code smellsCode smells
Code smells
 
Refactoring code smell
Refactoring code smellRefactoring code smell
Refactoring code smell
 
Code Smells
Code SmellsCode Smells
Code Smells
 
Catalogo camp 7
Catalogo camp 7Catalogo camp 7
Catalogo camp 7
 
Apache SOLR | Drupal Camp Kyiv 2010
Apache SOLR | Drupal Camp Kyiv 2010Apache SOLR | Drupal Camp Kyiv 2010
Apache SOLR | Drupal Camp Kyiv 2010
 
DrupalCafe7 CTools AJAX responder
DrupalCafe7 CTools AJAX responderDrupalCafe7 CTools AJAX responder
DrupalCafe7 CTools AJAX responder
 
Drupal camp donetsk c tools
Drupal camp donetsk c toolsDrupal camp donetsk c tools
Drupal camp donetsk c tools
 
DrupalCamp Kyiv 2011 Services
DrupalCamp Kyiv 2011 ServicesDrupalCamp Kyiv 2011 Services
DrupalCamp Kyiv 2011 Services
 
Taming The Hairy Beast: How the systematic approach help you navigating throu...
Taming The Hairy Beast: How the systematic approach help you navigating throu...Taming The Hairy Beast: How the systematic approach help you navigating throu...
Taming The Hairy Beast: How the systematic approach help you navigating throu...
 
Comm viewing
Comm viewingComm viewing
Comm viewing
 
Delayed operations with Queues
Delayed operations with QueuesDelayed operations with Queues
Delayed operations with Queues
 
Automated ui testing with selenium. drupal con london 2011
Automated ui testing with selenium. drupal con london 2011Automated ui testing with selenium. drupal con london 2011
Automated ui testing with selenium. drupal con london 2011
 
Commercial
CommercialCommercial
Commercial
 
Qasper - BIABC regional presentation
Qasper - BIABC regional presentationQasper - BIABC regional presentation
Qasper - BIABC regional presentation
 
Gastcollege > Jongeren & social media > Universiteit Twente
Gastcollege > Jongeren & social media > Universiteit TwenteGastcollege > Jongeren & social media > Universiteit Twente
Gastcollege > Jongeren & social media > Universiteit Twente
 
DrupalCafe5 VCS
DrupalCafe5 VCSDrupalCafe5 VCS
DrupalCafe5 VCS
 

Semelhante a Clean code and refactoring

Extending CMS Made Simple
Extending CMS Made SimpleExtending CMS Made Simple
Extending CMS Made Simplecmsmssjg
 
一种多屏时代的通用 web 应用架构
一种多屏时代的通用 web 应用架构一种多屏时代的通用 web 应用架构
一种多屏时代的通用 web 应用架构勇浩 赖
 
Top 10 Mistakes When Migrating From Oracle to PostgreSQL
Top 10 Mistakes When Migrating From Oracle to PostgreSQLTop 10 Mistakes When Migrating From Oracle to PostgreSQL
Top 10 Mistakes When Migrating From Oracle to PostgreSQLJim Mlodgenski
 
Oracle postgre sql-mirgration-top-10-mistakes
Oracle postgre sql-mirgration-top-10-mistakesOracle postgre sql-mirgration-top-10-mistakes
Oracle postgre sql-mirgration-top-10-mistakesJim Mlodgenski
 
Sharable of qualities of clean code
Sharable of qualities of clean codeSharable of qualities of clean code
Sharable of qualities of clean codeEman Mohamed
 
Customizing the Django Admin
Customizing the Django AdminCustomizing the Django Admin
Customizing the Django AdminLincoln Loop
 
Building High Perf Web Apps - IE8 Firestarter
Building High Perf Web Apps - IE8 FirestarterBuilding High Perf Web Apps - IE8 Firestarter
Building High Perf Web Apps - IE8 FirestarterMithun T. Dhar
 
An Intro to Scala for PHP Developers
An Intro to Scala for PHP DevelopersAn Intro to Scala for PHP Developers
An Intro to Scala for PHP DevelopersHuffPost Code
 
Standard Coding, OOP Techniques and Code Reuse
Standard Coding, OOP Techniques and Code ReuseStandard Coding, OOP Techniques and Code Reuse
Standard Coding, OOP Techniques and Code ReuseRayhan Chowdhury
 
Doctrine with Symfony - SymfonyCon 2019
Doctrine with Symfony - SymfonyCon 2019Doctrine with Symfony - SymfonyCon 2019
Doctrine with Symfony - SymfonyCon 2019julien pauli
 
Core Java Programming Language (JSE) : Chapter II - Object Oriented Programming.
Core Java Programming Language (JSE) : Chapter II - Object Oriented Programming.Core Java Programming Language (JSE) : Chapter II - Object Oriented Programming.
Core Java Programming Language (JSE) : Chapter II - Object Oriented Programming.WebStackAcademy
 
WordPress plugin #3
WordPress plugin #3WordPress plugin #3
WordPress plugin #3giwoolee
 
Angular Intermediate
Angular IntermediateAngular Intermediate
Angular IntermediateLinkMe Srl
 
Java on Google App engine
Java on Google App engineJava on Google App engine
Java on Google App engineMichael Parker
 
D7 theming what's new - London
D7 theming what's new - LondonD7 theming what's new - London
D7 theming what's new - LondonMarek Sotak
 

Semelhante a Clean code and refactoring (20)

Clean code
Clean codeClean code
Clean code
 
Extending CMS Made Simple
Extending CMS Made SimpleExtending CMS Made Simple
Extending CMS Made Simple
 
一种多屏时代的通用 web 应用架构
一种多屏时代的通用 web 应用架构一种多屏时代的通用 web 应用架构
一种多屏时代的通用 web 应用架构
 
Tp web
Tp webTp web
Tp web
 
Top 10 Mistakes When Migrating From Oracle to PostgreSQL
Top 10 Mistakes When Migrating From Oracle to PostgreSQLTop 10 Mistakes When Migrating From Oracle to PostgreSQL
Top 10 Mistakes When Migrating From Oracle to PostgreSQL
 
Oracle postgre sql-mirgration-top-10-mistakes
Oracle postgre sql-mirgration-top-10-mistakesOracle postgre sql-mirgration-top-10-mistakes
Oracle postgre sql-mirgration-top-10-mistakes
 
Sharable of qualities of clean code
Sharable of qualities of clean codeSharable of qualities of clean code
Sharable of qualities of clean code
 
Customizing the Django Admin
Customizing the Django AdminCustomizing the Django Admin
Customizing the Django Admin
 
Building High Perf Web Apps - IE8 Firestarter
Building High Perf Web Apps - IE8 FirestarterBuilding High Perf Web Apps - IE8 Firestarter
Building High Perf Web Apps - IE8 Firestarter
 
Rails 3 hints
Rails 3 hintsRails 3 hints
Rails 3 hints
 
An Intro to Scala for PHP Developers
An Intro to Scala for PHP DevelopersAn Intro to Scala for PHP Developers
An Intro to Scala for PHP Developers
 
Drupal 8 migrate!
Drupal 8 migrate!Drupal 8 migrate!
Drupal 8 migrate!
 
Standard Coding, OOP Techniques and Code Reuse
Standard Coding, OOP Techniques and Code ReuseStandard Coding, OOP Techniques and Code Reuse
Standard Coding, OOP Techniques and Code Reuse
 
Doctrine with Symfony - SymfonyCon 2019
Doctrine with Symfony - SymfonyCon 2019Doctrine with Symfony - SymfonyCon 2019
Doctrine with Symfony - SymfonyCon 2019
 
Core Java Programming Language (JSE) : Chapter II - Object Oriented Programming.
Core Java Programming Language (JSE) : Chapter II - Object Oriented Programming.Core Java Programming Language (JSE) : Chapter II - Object Oriented Programming.
Core Java Programming Language (JSE) : Chapter II - Object Oriented Programming.
 
WordPress plugin #3
WordPress plugin #3WordPress plugin #3
WordPress plugin #3
 
Angular Intermediate
Angular IntermediateAngular Intermediate
Angular Intermediate
 
Java on Google App engine
Java on Google App engineJava on Google App engine
Java on Google App engine
 
D7 theming what's new - London
D7 theming what's new - LondonD7 theming what's new - London
D7 theming what's new - London
 
Effective PHP. Part 1
Effective PHP. Part 1Effective PHP. Part 1
Effective PHP. Part 1
 

Mais de Yuriy Gerasimov

Progressing to Team Lead
Progressing to Team LeadProgressing to Team Lead
Progressing to Team LeadYuriy Gerasimov
 
What kind testing DUG Vancouver
What kind testing DUG VancouverWhat kind testing DUG Vancouver
What kind testing DUG VancouverYuriy Gerasimov
 
Editor Experience in Drupal 8
Editor Experience in Drupal 8Editor Experience in Drupal 8
Editor Experience in Drupal 8Yuriy Gerasimov
 
Load Testing with JMeter
Load Testing with JMeterLoad Testing with JMeter
Load Testing with JMeterYuriy Gerasimov
 
Ci. Drupal Camp Berlin 2014
Ci. Drupal Camp Berlin 2014Ci. Drupal Camp Berlin 2014
Ci. Drupal Camp Berlin 2014Yuriy Gerasimov
 
Inline elements. DrupalCamp Berlin 2014
Inline elements. DrupalCamp Berlin 2014Inline elements. DrupalCamp Berlin 2014
Inline elements. DrupalCamp Berlin 2014Yuriy Gerasimov
 
CI and other tools for feature branch development
CI and other tools for feature branch developmentCI and other tools for feature branch development
CI and other tools for feature branch developmentYuriy Gerasimov
 
DrupalCafe Kyiv EntityAPI
DrupalCafe Kyiv EntityAPIDrupalCafe Kyiv EntityAPI
DrupalCafe Kyiv EntityAPIYuriy Gerasimov
 
Automated UI testing. Selenium. DrupalCamp Kyiv 2011
Automated UI testing. Selenium. DrupalCamp Kyiv 2011Automated UI testing. Selenium. DrupalCamp Kyiv 2011
Automated UI testing. Selenium. DrupalCamp Kyiv 2011Yuriy Gerasimov
 
Automated UI testing with Selenium
Automated UI testing with SeleniumAutomated UI testing with Selenium
Automated UI testing with SeleniumYuriy Gerasimov
 
Code Driven Development Zaporozhye DrupalForum
Code Driven Development Zaporozhye DrupalForumCode Driven Development Zaporozhye DrupalForum
Code Driven Development Zaporozhye DrupalForumYuriy Gerasimov
 
DrupalCafe4 Kiev Services
DrupalCafe4 Kiev ServicesDrupalCafe4 Kiev Services
DrupalCafe4 Kiev ServicesYuriy Gerasimov
 

Mais de Yuriy Gerasimov (17)

Progressing to Team Lead
Progressing to Team LeadProgressing to Team Lead
Progressing to Team Lead
 
What kind testing DUG Vancouver
What kind testing DUG VancouverWhat kind testing DUG Vancouver
What kind testing DUG Vancouver
 
Editor Experience in Drupal 8
Editor Experience in Drupal 8Editor Experience in Drupal 8
Editor Experience in Drupal 8
 
Load Testing with JMeter
Load Testing with JMeterLoad Testing with JMeter
Load Testing with JMeter
 
Ci. Drupal Camp Berlin 2014
Ci. Drupal Camp Berlin 2014Ci. Drupal Camp Berlin 2014
Ci. Drupal Camp Berlin 2014
 
Inline elements. DrupalCamp Berlin 2014
Inline elements. DrupalCamp Berlin 2014Inline elements. DrupalCamp Berlin 2014
Inline elements. DrupalCamp Berlin 2014
 
CI and other tools for feature branch development
CI and other tools for feature branch developmentCI and other tools for feature branch development
CI and other tools for feature branch development
 
Drupal 8 Routing
Drupal 8 RoutingDrupal 8 Routing
Drupal 8 Routing
 
BADCamp 2012 Facet API
BADCamp 2012 Facet APIBADCamp 2012 Facet API
BADCamp 2012 Facet API
 
Services Stanford 2012
Services Stanford 2012Services Stanford 2012
Services Stanford 2012
 
DrupalCafe Kyiv EntityAPI
DrupalCafe Kyiv EntityAPIDrupalCafe Kyiv EntityAPI
DrupalCafe Kyiv EntityAPI
 
DrupalCafe Kyiv CTools
DrupalCafe Kyiv CToolsDrupalCafe Kyiv CTools
DrupalCafe Kyiv CTools
 
DrupalCafe Kyiv drupal8
DrupalCafe Kyiv drupal8DrupalCafe Kyiv drupal8
DrupalCafe Kyiv drupal8
 
Automated UI testing. Selenium. DrupalCamp Kyiv 2011
Automated UI testing. Selenium. DrupalCamp Kyiv 2011Automated UI testing. Selenium. DrupalCamp Kyiv 2011
Automated UI testing. Selenium. DrupalCamp Kyiv 2011
 
Automated UI testing with Selenium
Automated UI testing with SeleniumAutomated UI testing with Selenium
Automated UI testing with Selenium
 
Code Driven Development Zaporozhye DrupalForum
Code Driven Development Zaporozhye DrupalForumCode Driven Development Zaporozhye DrupalForum
Code Driven Development Zaporozhye DrupalForum
 
DrupalCafe4 Kiev Services
DrupalCafe4 Kiev ServicesDrupalCafe4 Kiev Services
DrupalCafe4 Kiev Services
 

Clean code and refactoring

  • 1. Clean Code and Refactoring Yuriy Gerasimov email: yuri.gerasimov@gmail.com twitter: ygerasimov skype: yuriy_gerasimov d.o.: http://drupal.org/user/257311
  • 2.
  • 3. Disclaimer ● Not rules but recepies ● You are not the last person who will look at this code ● Leave the code in better shape that you found it ● Debates are welcome
  • 4. Learn PHP and Drupal functions ● Build array (5 => 5, 6 => 6, …, 10 => 10); – drupal_map_assoc(range(5, 10)); ● Sort form element – uasort($form, 'element_sort'); // by #weight – uasort($form, 'element_sort_by_title'); ● Validation: valid_email_address(), valid_url() ● Get all keys not prefixed with # for (element_children($form) as $key) {}
  • 6. Names ● Variables, classes – nouns. Methods, functions – verbs ● Shorter variable name for local scope ($i) ● One name per concept ($user, $account, $person, $site_visitor) ● Domain names ($student, $course, $lesson...) ● Patterns names (singleton, visitor …) ● Funciton name prefixes isSomething(), setSomething(), getSomething(), doSomething()
  • 7. Constants ● Use constants to describe what static vars mean if ($user->uid == 2) if ($user->uid == USER_SUPER_ADMIN_UID ) if ($user->uid == self::USER_SUPER_ADMIN_UID)
  • 9. Functions ● Functions should do one thing and be small and clean. Example menu_execute_active_handler(): – Checks whether site is online or not – Executes menu callback – Deliver callback result ● _menu_router_build() has more than 200 lines!
  • 10. Functions ● Group arguments to eliminate number of arguments ● Pass structures that function is going to alter if results are complex
  • 11. Functions ● Groupped arguments, apply default values
  • 12. Function ● Helper functions underscore prefix (_menu_delete_item()) ● Group helper functions into classes with static methods. Autoloading.
  • 13.
  • 14. Comments ● Comments get outdated first! ● Comments should be written when we fail to find good variables / function names ● Think twice about names before writing a comment explaining your intentions ● Why it is done this way and not What is this
  • 15.
  • 16. Spaghetti code ● Return result early (continue and break cycles)
  • 18. Use switch construction ● (example from locale.inc)
  • 19. Return conditions ● simply return value (return ($a == $b); ) ● backup_migrate/includes/destinations.file.inc
  • 20. Long conditions ● one condition per line ● operators in front ● identation
  • 21.
  • 23. Use Exceptions ● _io_checkout_page_ajax_validate__if_email_exists()
  • 24. Use Polymorphism ● D8 plugins system ● Views handlers ● Take a look at function names in form.inc: – form_type_checkbox_value(), theme_checkbox(), form_process_checkbox() – form_type_select_value(), theme_select(), form_process_select()
  • 25.
  • 26. Organize your code right ● Separate files ● Follow traditions ● 1000 lines – you do it wrong
  • 27. Organize your code right ● Sort by source and not by name ● First hooks implementations, then helpers
  • 29. Do not Repeat Yourself (DRY) ● panels/includes/plugins.inc
  • 30. DRY ● panels/includes/plugins.inc
  • 31. Functional programming ● anonymous functions (closures) php 5.3.0 ● variables can be functions ● functions can be passed as arguments
  • 35. Refactoring loves tests ● Some tests better than no tests at all ● Use DrupalUnitTestCase for unit testing (fast)
  • 36. To read ● Robert C. Martin. Clean Code: A Handbook of Agile Software Craftsmanship ● Martin Fowler. Refactoring: Improving the Design of Existing Code ● http://www.slideshare.net/rdohms/bettercode- phpbenelux212alternate ● http://london2011.drupal.org/conference/sessions/code- stinks ● http://chicago2011.drupal.org/sessions/aphorisms-api- design