wordcamp us: clean code

22
December 5, 2015 Wordcamp U.S. Clean Code Michael Toppa @mtoppa toppa.com Source

Upload: mtoppa

Post on 15-Apr-2017

3.248 views

Category:

Software


0 download

TRANSCRIPT

December 5, 2015 Wordcamp U.S.

Clean CodeMichael Toppa @mtoppa toppa.com

Source

ポカヨケ

www.pokayoke.design@pokayokedesign

Clean code…

That sounds nice, but I have a deadline

I don't have time for clean 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?

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

“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

10 ways to make your code clean

#1

Youare responsible for the quality of your code

* A lot of what’s in my talk comes from Bob Martin, who wrote a book called Clean Code. He provides some good analogies.* It’s not up to the project manager or your boss - they are almost always asking you to go faster.* 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?* If we want to be treated as professionals, we need to act like professionals. And 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.

#2

Use meaningful

names

The name of a variable, function, or class should tell you why it exists, and what it does

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

Good

$elapsed_time_in_days;$daysSinceCreation;

$days_since_modification;

* Grady Booch, the former chief scientist at IBM said that code should “read like well written prose.”* So you can think of variable names as the nouns and subjects of your code sentences

#3 - 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]; }

else { throw New Exception(__('invalid thumbnail size requested', 'shashin')); }

return $this->numeric_thumbnail_size;}

* Now we get to functions, which are our verbs… 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?

#4

Comments are often lies waiting to happen.

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

#5

Source

* 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 on 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.* 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.

#6

Source

* Do one thing, do it well, do it only. But what does it mean to do just one thing?* For functions, 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* Many code review tools will warn you if a function is more than 10 lines long.* For classes, it means having a single conceptual responsibility. When projects get big, this is how you keep them manageable. Code review tools will

typically warn you if classes are more than 200 lines

#7 - Write tests!

Copyright Lucasfilm Ltd

Test driven development (TDD)

Source

* Learning TDD completely changed how I code. It forces you to think about how your new code will talk to the existing code first. This leads to better design than just diving in to solve a problem, and only afterwards trying to figure out how all the pieces fit together.

* Having repeatable tests has also saved me literally hundreds of times, when a change I introduced *here* broke something over *there* without me realizing it.

* Better to find out from a test that you broke something than from an angry customer.

#8 - Work in short cycles: incremental and iterative

Source

* Develop systems in small portions at a time (incremental), through repeated cycles (iterative), write tests to verify functionality, and take advantage of what was learned in each cycle (for both features and implementation).

* What I’m describing is an Agile workflow, which would require a whole other talk to explain in detail* But for now I’ll just say that an Agile workflow complements the clean code style.* Work on one thing, do it well, then move on to the next thing.

#9 - Independent Architecture

Why am I subjecting you to this awful image?

“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

* 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”

* I wrote a plugin for displaying photos from Picasa, Youtube, and others in WordPress. 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. I use most of the same practices in my Rails work as my WordPress work.

* What I’m actually talking about here is community, and growing our sense of community. The WordPress community is so big, it’s easy to talk only amongst ourselves. There’s a lot we can learn about maintainable design from other platforms and languages.

#10 - Practice, practice, practice

Source

* 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

* [my working on bus example]

December 5, 2015 Wordcamp U.S.

Michael Toppa @mtoppa www.toppa.com