WordCamp Nashville: Clean Code for WordPress

  • 5,258 views
Uploaded on

Slides from my talk at WordCamp Nashville, including notes. Covers why clean code is important, and provides 10 tips to make your code cleaner, for WordPress and beyond

Slides from my talk at WordCamp Nashville, including notes. Covers why clean code is important, and provides 10 tips to make your code cleaner, for WordPress and beyond

More in: Technology
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Be the first to comment
No Downloads

Views

Total Views
5,258
On Slideshare
0
From Embeds
0
Number of Embeds
5

Actions

Shares
Downloads
10
Comments
0
Likes
1

Embeds 0

No embeds

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
    No notes for slide
  • It’s not just other people’s code, it’s your own code, 6 months later
    But it doesn’t have to be this way
  • Same technology that power disqus and google analytics
    My head was spinning enough already from switching between PHP, JS, and Ruby. Keeping the code clean made keeping track of all the interactions coherent.
  • I put “plugins” in the title to draw in developers
    There are many aspects of coding for WordPress that are unique to WordPress, like the 2 talks before me, about custom layout and customizing the admin area, and you have many resources in the WordPress community for help with topics like that. So that’s not what I’m here to talk about either
    I’m here to talk about coding principles that apply across languages and across development frameworks. I want to get you thinking about approaches to coding that will help you with WordPress, and beyond WordPress as well
  • Code formatting is important, but writing clean code is about much more than that - it’s about how your code is organized, and how clearly it expresses its intent. Good organization and expressiveness are the keys to writing code that is flexible, extensible, and maintainable over time.
  • Stroustrup: inventor of C++
    Booch: IBM chief scientist
    Thomas: founder of Object Technology International
    Feathers: author of Working Effectively with Legacy Code
    Jeffries: co-creator of XP development
    Cunnigham: inventor of Wikis
  • Doctors take the Hippocratic oath and a set of practices to ensure they practice medicine safely
    Accounts are expected to do double entry booking, to avoid mistakes
    Other professions have standards for what it means to practice that profession safely and responsibly. When the pressure is on is when you most want them to adhere to their best practices.
  • The software craftsmanship movement is intended to start a conversation about what it means to write code responsibly and cleanly.
    You don't have to agree with the ideas, but you do need to engage them.
    Other professions - doctors, lawyers, plumbers, etc have various degrees of government regulation. This will happen with software development if we don’t develop professional standards of our own. The $440 million stock market meltdown last summer by Knight Capital happened because they didn’t test their software properly. Everything from gas pumps to medical devices rely on software.
  • The more we rush, the more the code turns into a big ball of mud, making it harder and harder to work with. Keeping the code clean lets us go faster, because clean code is flexible code. Why is it exactly that trying to go fast ultimately makes us slower?
  • If you’re working quick and dirty, you’re not writing code that is readable
  • But we’re not really aware of how we’re spending our time. Going forward, think about the hours you spend debugging, or trying to figure out messy code. When you’re trying to decide whether you should spend a little more time writing code more cleanly, remember an ounce of prevention is worth a pound of cure
  • It’s not up to the project manager or your boss.
    What would your doctor say if you told her to skip washing her hands, because you’re in a hurry?
    What would your accountant say if you told him to save some time by no doing double-entry bookkeeping?
    Part of being a professional is being honest about how long it takes to do something well, and not accepting the option to do it wrong.
  • Develop systems in small portions at a time (incremental), through repeated cycles (iterative), and take advantage of what was learned in each cycle (for both features and implementation).
    This workflow style complements the clean code style. Work on one thing, do it well, then move on to the next thing.
  • This is an outline of what’s called an Agile workflow, and not all of them may apply to a typical WP project
  • You don’t want this kind of relationship with your clients or your code
  • This visual is a great analogy for how you should name your variables and functions
  • Imagine a script full of variable names like this - it would be very difficult to understand.
    Mental translating of obscure names to their real meaning distracts from our ability to get an overall understanding of the code
    The days when it was important to use short variable names to save memory space are long gone
    Automated minification tools can shrink javascript code for you when dealing with code being transmitted over slow connections
  • This gives us the nouns for code that “reads like well written prose”
  • Now we get to the verbs and sentences... Take a minute to read this. Even without knowing the class or the properties, it's clear what this method does.
    You should use a 21st century IDE, that auto-completes names for you and makes it easy to rename. I use PHP Storm.
    What don’t you see in this code?
  • The revelation for me in learning clean code techniques is that code can be expressive. That it really can “read like well written prose.”
    Rather than relying on comments to explain your code, the code should explain itself
    Comments become something you have to maintain, and if they become outdated and no longer describe the current behavior of the code, they become dangerous lies
    But they are sometimes necessary - for example, you may need to explain why you did something a certain way
    The point is to stop and think before you write a comment, and ask yourself if instead you can make the code more expressive
  • A common occurrence in software projects is “bit rot” - the code gets messier and buggier over time.
    But how about code that just keeps getting cleaner over time? You can get this by following the “boy scout rule.” Keep your new code clean, and while you’re working it, spend a few minutes cleaning up the code that it works with. Improve a variable name, break up a function that’s too big, eliminate a small bit of duplication, etc. (rule 6.5 would be don’t repeat yourself...)
    It’s easier to keep your garden healthy and looking nice by weeding it for 10min every day than waiting until it’s a huge overgrown mess.
  • Do one thing, do it well, do it only
    But what does it mean to do just one thing?
    For methods, this typically means changing the value of only one variable
    If you are passing more than 2 or 3 arguments into a function or method, you are probably doing more than one thing
    The more arguments you pass to a function, and the longer it is, the harder it is to test and debug when something goes wrong
    For classes, it means having a single conceptual responsibility. When projects get big, this is how you keep them manageable.
  • It accepts one argument - that’s good
    It changes only one value - that’s good
    There are no side-effects - that’s good
    If....elseif blocks are a red flag. There are 3 different cases being handled here. You could technically call this a violation, but each conditional block contains only one line of code, so breaking this down into more methods wouldn’t really help.
    But if you see the same conditions being tested over and over in different functions, that’s a sign to do some reorganizing
  • The complexity of having 44 classes in my Shashin plugin is justified by its need for flexibility
    You can support a new viewer or a new photo service simply by creating a new subclass. This is much more maintainable and extensible than a single huge file with deeply nested conditionals and unclear dependencies
    But if I knew I would never need that kind of flexibility, there would be no justification for creating these layers of abstraction – they would just be needless complexity
  • Why am I subjecting you to this awful image?
  • my attachment to the community - Philly WordCamp
    But I’m also part of other communities
    WordPress is essentially a framework, so this could read “WordPress is a tool to be used, not an architecture to be conformed to”
    This is from a blog post called “screaming architecture”
    Looking at Shashin, its files and code scream “photo management and display!”, with names like PicasaSynchronizer and PhotoDisplayer. It does not scream “WordPress plugin”
    The fact that it is a WordPress plugin is incidental to its design. In fact I used a design called the facade pattern, which removes most of the direct dependencies on WordPress. This makes it possible to re-use outside of WordPress if I wanted to.
  • I wrote about this on my blog a few weeks ago
    I’m talking about the Singleton pattern, continuing reliance on global variables, writing integration tests but calling them unit tests (and having an architecture that precludes actual unit testing), etc.
    WordPress experience is not a good preparation for work outside of WordPress
  • I added this slide this morning, after seeing Eric Brace & Peter Cooper last night at the Station Inn
    Musicians don’t play only when they’re on stage
    To get good at something you need time to refine your craft, when you’re not under pressure to perform
    Imagine if downloading wordpress gave you blisters
    [my working on bus example]

Transcript

  • 1. Source: http://abstrusegoose.com/432 Clean Code for WordPress Michael Toppa @mtoppa April 20, 2013 WordCamp Nashville It’s not just other people’s code, it’s your own code, 6 months later But it doesn’t have to be this way www.toppa.com
  • 2. Mike Toppa 19 years of experience in web development, project management, and team management ✤ Author of 7 plugins at wordpress.org, dating back to 2006 ✤ Given 5 WordCamp presentations ✤ Currently: Rails Engineer, ElectNext ✤ Previously: ✤ Director of Development, WebDevStudios - led NBC Latino WP VIP project ✤ Director of the 17 person Web Applications team at the U Penn School of Medicine ✤ Web developer at: Georgetown University, Stanford University, E*Trade, and Ask Jeeves
  • 3. Before we begin... ✤ Debut of the ElectNext Political Profiler ✤ The technology stack that powers it: ✤ ✤ A Ruby on Rails application at electnext.com for generating them ✤ ✤ WordPress plugin for embedding and displaying profiles 3rd party javascript for injecting the profiles in real-time This application would be a nightmare without clean code Same technology that power disqus and google analytics My head was spinning enough already from switching between PHP, JS, and Ruby. Keeping the code clean made keeping track of all the interactions coherent.
  • 4. What is this talk about? ✤ Clean code for WordPress plugins ✤ Clean code for WordPress ✤ Clean code I put “plugins” in the title to draw in developers There are many aspects of coding for WordPress that are unique to WordPress, like the 2 talks before me, about custom layout and customizing the admin area, and you have many resources in the WordPress community for help with topics like that. So that’s not what I’m here to talk about either I’m here to talk about coding principles that apply across languages and across development frameworks. I want to get you thinking about approaches to coding that will help you with WordPress, and beyond WordPress as well
  • 5. What is clean code? Code formatting is important, but writing clean code is about much more than that - it’s about how your code is organized, and how clearly it expresses its intent. Good organization and expressiveness are the keys to writing code that is flexible, extensible, and maintainable over time.
  • 6. Clean code... ✤ “Does one thing well” - Bjarne Stroustrup ✤ “Reads like well written prose” - Grady Booch ✤ “Can be read and enhanced by a developer other than its original author” - Dave Thomas ✤ “Always looks like it was written by someone who cares” - Michael Feathers ✤ “Contains no duplication” - Ron Jeffries ✤ “Turns out to be pretty much what you expected” - Ward Cunningham Quotes from “Clean Code” by Robert Martin Stroustrup: inventor of C++ Booch: IBM chief scientist Thomas: founder of Object Technology International Feathers: author of Working Effectively with Legacy Code Jeffries: co-creator of XP development Cunnigham: inventor of Wikis
  • 7. That sounds nice, but I have a deadline I don't have time for clean code!
  • 8. Do you want your emergency room doctor to rush your surgery? Do you want your account to rush his work on your tax return? Doctors take the Hippocratic oath and a set of practices to ensure they practice medicine safely Accounts are expected to do double entry booking, to avoid mistakes Other professions have standards for what it means to practice that profession safely and responsibly. When the pressure is on is when you most want them to adhere to their best practices.
  • 9. The software craftsmanship movement The software craftsmanship movement is intended to start a conversation about what it means to write code responsibly and cleanly. You don't have to agree with the ideas, but you do need to engage them. Other professions - doctors, lawyers, plumbers, etc have various degrees of government regulation. This will happen with software development if we don’t develop professional standards of our own. The $440 million stock market meltdown last summer by Knight Capital happened because they didn’t test their software properly. Everything from gas pumps to medical devices rely on software.
  • 10. Clean code is adaptable code The more we rush, the more the code turns into a big ball of mud, making it harder and harder to work with. Keeping the code clean lets us go faster, because clean code is flexible code. Why is it exactly that trying to go fast ultimately makes us slower?
  • 11. The ratio of time spent reading code versus writing is well over 10 to 1. Therefore, making code easy to read makes it easier to write. paraphrased from Clean Code If you’re working quick and dirty, you’re not writing code that is readable
  • 12. “We like to think we spend our time power typing, but we actually spend most of our time staring into the abyss.” - Douglas Crockford principal discoverer of JSON, creator of JSLint But we’re not really aware of how we’re spending our time. Going forward, think about the hours you spend debugging, or trying to figure out messy code. When you’re trying to decide whether you should spend a little more time writing code more cleanly, remember an ounce of prevention is worth a pound of cure
  • 13. 10 ways to make your code clean
  • 14. #1 You are responsible for the quality of your code It’s not up to the project manager or your boss. What would your doctor say if you told her to skip washing her hands, because you’re in a hurry? What would your accountant say if you told him to save some time by no doing double-entry bookkeeping? Part of being a professional is being honest about how long it takes to do something well, and not accepting the option to do it wrong.
  • 15. #2 - Work in short cycles: incremental and iterative Source Develop systems in small portions at a time (incremental), through repeated cycles (iterative), and take advantage of what was learned in each cycle (for both features and implementation). This workflow style complements the clean code style. Work on one thing, do it well, then move on to the next thing.
  • 16. This is what a project with short cycles and feedback looks like Source This is an outline of what’s called an Agile workflow, and not all of them may apply to a typical WP project
  • 17. This is what a project without feedback looks like Source “I find your lack of faith disturbing” You don’t want this kind of relationship with your clients or your code
  • 18. #3 - Use meaningful names This visual is a great analogy for how you should name your variables and functions
  • 19. The name of a variable, function, or class should tell you why it exists, and what it does
  • 20. Not good $d; // elapsed time in days Imagine a script full of variable names like this - it would be very difficult to understand. Mental translating of obscure names to their real meaning distracts from our ability to get an overall understanding of the code The days when it was important to use short variable names to save memory space are long gone Automated minification tools can shrink javascript code for you when dealing with code being transmitted over slow connections
  • 21. Good $elapsed_time_in_days; $daysSinceCreation; $days_since_modification; This gives us the nouns for code that “reads like well written prose”
  • 22. #4 - Write code that expresses intent public function set_numeric_thumbnail_size($requested_size = 'xsmall') { if (array_key_exists($requested_size, $this->thumbnail_sizes_map)) { $this->numeric_thumbnail_size = $this->thumbnail_sizes_map[$requested_size]; } elseif (is_numeric($requested_size)) { $this->numeric_thumbnail_size = $requested_size; } else { throw New Exception(__('invalid thumbnail size requested', 'shashin')); } return $this->numeric_thumbnail_size; } Now we get to the verbs and sentences... Take a minute to read this. Even without knowing the class or the properties, it's clear what this method does. You should use a 21st century IDE, that auto-completes names for you and makes it easy to rename. I use PHP Storm. What don’t you see in this code?
  • 23. #5 Comments are a red flag! Code should speak for itself whenever possible The revelation for me in learning clean code techniques is that code can be expressive. That it really can “read like well written prose.” Rather than relying on comments to explain your code, the code should explain itself Comments become something you have to maintain, and if they become outdated and no longer describe the current behavior of the code, they become dangerous lies But they are sometimes necessary - for example, you may need to explain why you did something a certain way The point is to stop and think before you write a comment, and ask yourself if instead you can make the code more expressive
  • 24. #6 A common occurrence in software projects is “bit rot” - the code gets messier and buggier over time. But how about code that just keeps getting cleaner over time? You can get this by following the “boy scout rule.” Keep your new code clean, and while you’re working it, spend a few minutes cleaning up the code that it works with. Improve a variable name, break up a function that’s too big, eliminate a small bit of duplication, etc. (rule 6.5 would be don’t repeat yourself...) It’s easier to keep your garden healthy and looking nice by weeding it for 10min every day than waiting until it’s a huge overgrown mess.
  • 25. #7 Do one thing, do it well, do it only But what does it mean to do just one thing? For methods, this typically means changing the value of only one variable If you are passing more than 2 or 3 arguments into a function or method, you are probably doing more than one thing The more arguments you pass to a function, and the longer it is, the harder it is to test and debug when something goes wrong For classes, it means having a single conceptual responsibility. When projects get big, this is how you keep them manageable.
  • 26. Does this method follow the SRP? public function set_numeric_thumbnail_size($requested_size = 'xsmall') { if (array_key_exists($requested_size, $this->thumbnail_sizes_map)) { $this->numeric_thumbnail_size = $this->thumbnail_sizes_map[$requested_size]; } elseif (is_numeric($requested_size)) { $this->numeric_thumbnail_size = $requested_size; } else { throw New Exception(__('invalid thumbnail size requested', 'shashin')); } return $this->numeric_thumbnail_size; } It accepts one argument - that’s good It changes only one value - that’s good There are no side-effects - that’s good If....elseif blocks are a red flag. There are 3 different cases being handled here. You could technically call this a violation, but each conditional block contains only one line of code, so breaking this down into more methods wouldn’t really help. But if you see the same conditions being tested over and over in different functions, that’s a sign to do some reorganizing
  • 27. #8 - Don’t over-do it: avoid needless complexity The complexity of having 44 classes in my Shashin plugin is justified by its need for flexibility You can support a new viewer or a new photo service simply by creating a new subclass. This is much more maintainable and extensible than a single huge file with deeply nested conditionals and unclear dependencies But if I knew I would never need that kind of flexibility, there would be no justification for creating these layers of abstraction – they would just be needless complexity
  • 28. #9 - Independent Architecture Why am I subjecting you to this awful image?
  • 29. “Software architectures are structures that support the use cases of the system... Frameworks are tools to be used, not architectures to be conformed to” - Bob Martin http://blog.8thlight.com/uncle-bob/2011/09/30/Screaming-Architecture.html my attachment to the community - Philly WordCamp But I’m also part of other communities WordPress is essentially a framework, so this could read “WordPress is a tool to be used, not an architecture to be conformed to” This is from a blog post called “screaming architecture” Looking at Shashin, its files and code scream “photo management and display!”, with names like PicasaSynchronizer and PhotoDisplayer. It does not scream “WordPress plugin” The fact that it is a WordPress plugin is incidental to its design. In fact I used a design called the facade pattern, which removes most of the direct dependencies on WordPress. This makes it possible to re-use outside of WordPress if I wanted to.
  • 30. Community and Architecture ✤ Why does this matter? ✤ WordPress has an architecture that’s causing its best practices to diverge from the best practices of the broader software community ✤ The WordPress community is so big that it’s easy to talk only to ourselves ✤ Developers in Ruby/Rails, Java/Spring, Python/Django, etc regularly intermingle at conferences and learn from each other ✤ I don’t see a compelling reason for WordPress to continue forever on a divergent path, and doing so means lost opportunities I wrote about this on my blog a few weeks ago I’m talking about the Singleton pattern, continuing reliance on global variables, writing integration tests but calling them unit tests (and having an architecture that precludes actual unit testing), etc. WordPress experience is not a good preparation for work outside of WordPress
  • 31. #10 - Practice, practice, practice I added this slide this morning, after seeing Eric Brace & Peter Cooper last night at the Station Inn Musicians don’t play only when they’re on stage To get good at something you need time to refine your craft, when you’re not under pressure to perform Imagine if downloading wordpress gave you blisters [my working on bus example]
  • 32. Any questions? Michael Toppa @mtoppa April 20, 2013 WordCamp Nashville www.toppa.com