GarrettW.wiki

My personal knowledge base

User Tools

Site Tools


ways_to_avoid_php_code_stink

taken from Your code sucks, let's fix it - By Rafael Dohms

Be aware of whether your code is:

  • Easily readable
  • Testable
  • Maintainable (by yourself and others)
  • Reusable

Object Calisthenics + Readability Tips

  1. Only one indentation level per method
    “Wait, I can't even have two nested foreach blocks?”
    Nope. Return early, and consider whether your algorithm could be simplified by using PHP's built-in functions. If not, just break it up into reusable pieces. Separation of concerns.
  2. Don't use 'else'
    This plays into #1. Helps avoid code duplication and makes it easier to understand since there's only one decision path.
  3. Wrap primitive types if you need to attach behavior
    For example, if a function takes a parameter that doesn't satisfy readability in the calling code, maybe it needs to be wrapped in something else, like an object.
  4. Only one '→' per line, unless getters or fluent
    Properties are harder to mock for testing than methods.
    With fluency, align arrows and don't do too many levels without making sure they all return proper things to avoid exceptions.
    Also consider how auto-completable your functions are.
  5. Don't abbreviate variable and function names
    And don't try to pack too much information in either, as this is a symptom of bad encapsulation or something. Use meaningful function names.
  6. Keep your classes small
    No more than 100-200 lines per class, maybe 20 lines per method
  7. Limit the number of instance variables in classes to 5
  8. Use first-class collections
  9. Do use getters/setters
    because they allow you to inject stuff like lazy loading,
  10. Document your code!
ways_to_avoid_php_code_stink.txt · Last modified: 2015/05/05 00:58 by Garrett W.