32
April 20, 2013 WordCamp Nashville Clean Code for WordPress Michael Toppa @mtoppa www.toppa.com Source: http://abstrusegoose.com/432 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

WordCamp Nashville: Clean Code for WordPress

  • Upload
    mtoppa

  • View
    5.517

  • Download
    1

Embed Size (px)

DESCRIPTION

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

Citation preview

Page 1: WordCamp Nashville: Clean Code for WordPress

April 20, 2013 WordCamp Nashville

Clean Code for WordPressMichael Toppa @mtoppa www.toppa.com

Source: http://abstrusegoose.com/432

It’s not just other people’s code, it’s your own code, 6 months laterBut it doesn’t have to be this way

Page 2: WordCamp Nashville: Clean Code for WordPress

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

Page 3: WordCamp Nashville: Clean Code for WordPress

✤ Debut of the ElectNext Political Profiler

✤ The technology stack that powers it:

✤ WordPress plugin for embedding and displaying profiles

✤ A Ruby on Rails application at electnext.com for generating them

✤ 3rd party javascript for injecting the profiles in real-time

✤ This application would be a nightmare without clean code

Before we begin...

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.

Page 4: WordCamp Nashville: Clean Code for WordPress

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

Page 5: WordCamp Nashville: Clean Code for WordPress

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.

Page 6: WordCamp Nashville: Clean Code for WordPress

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 CunninghamQuotes from “Clean Code” by Robert Martin

Stroustrup: inventor of C++Booch: IBM chief scientistThomas: founder of Object Technology InternationalFeathers: author of Working Effectively with Legacy CodeJeffries: co-creator of XP developmentCunnigham: inventor of Wikis

Page 7: WordCamp Nashville: Clean Code for WordPress

That sounds nice, but I have a deadline

I don't have time for clean code!

Page 8: WordCamp Nashville: Clean Code for WordPress

Do you want your emergency room doctorto rush your surgery?

Do you want your account to rushhis 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.

Page 9: WordCamp Nashville: Clean Code for WordPress

The software craftsmanshipmovement

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.

Page 10: WordCamp Nashville: Clean Code for WordPress

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?

Page 11: WordCamp Nashville: Clean Code for WordPress

The ratio of time spent reading code versuswriting is well over 10 to 1.

Therefore, making code easy to readmakes it easier to write.

paraphrased from Clean Code

If you’re working quick and dirty, you’re not writing code that is readable

Page 12: WordCamp Nashville: Clean Code for WordPress

“We like to think we spend our time power typing,but we actually spend most of our time

staring into the abyss.”

- Douglas Crockfordprincipal 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

Page 13: WordCamp Nashville: Clean Code for WordPress

10 ways to make your code clean

Page 14: WordCamp Nashville: Clean Code for WordPress

#1

Youare 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.

Page 15: WordCamp Nashville: Clean Code for WordPress

#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.

Page 16: WordCamp Nashville: Clean Code for WordPress

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

Page 17: WordCamp Nashville: Clean Code for WordPress

“I find your lack of faith disturbing”

This is what a project without feedback looks like

Source

You don’t want this kind of relationship with your clients or your code

Page 18: WordCamp Nashville: Clean Code for WordPress

#3 - Usemeaningfulnames

This visual is a great analogy for how you should name your variables and functions

Page 19: WordCamp Nashville: Clean Code for WordPress

The name of a variable, function,or class should tell you

why it exists,and what it does

Page 20: WordCamp Nashville: Clean Code for WordPress

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

Page 21: WordCamp Nashville: Clean Code for WordPress

Good

$elapsed_time_in_days;$daysSinceCreation;

$days_since_modification;

This gives us the nouns for code that “reads like well written prose”

Page 22: WordCamp Nashville: Clean Code for WordPress

#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?

Page 23: WordCamp Nashville: Clean Code for WordPress

#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

Page 24: WordCamp Nashville: Clean Code for WordPress

#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.

Page 25: WordCamp Nashville: Clean Code for WordPress

#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.

Page 26: WordCamp Nashville: Clean Code for WordPress

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

Page 27: WordCamp Nashville: Clean Code for WordPress

#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

Page 28: WordCamp Nashville: Clean Code for WordPress

#9 - Independent Architecture

Why am I subjecting you to this awful image?

Page 29: WordCamp Nashville: Clean Code for WordPress

“Software architectures are structures thatsupport 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 WordCampBut I’m also part of other communitiesWordPress 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.

Page 30: WordCamp Nashville: Clean Code for WordPress

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

Page 31: WordCamp Nashville: Clean Code for WordPress

#10 - Practice, practice, practice

I added this slide this morning, after seeing Eric Brace & Peter Cooper last night at the Station InnMusicians don’t play only when they’re on stageTo get good at something you need time to refine your craft, when you’re not under pressure to performImagine if downloading wordpress gave you blisters[my working on bus example]

Page 32: WordCamp Nashville: Clean Code for WordPress

April 20, 2013 WordCamp Nashville

Any questions?Michael Toppa @mtoppa www.toppa.com