When it comes to code style I am a hardcore extremist. I’m not talking about things like spaces vs. tabs. What I’m getting at is clean, readable code. I’m into its visual appeal. Clean code is code that looks like a pretty pattern from across the room. It’s code I can understand a year from now. Clean code is good code and good code is working code. Let’s talk about what clean code is and how to write it.
I’ve been working as a course instructor for a coding school/boot camp in Chicago for the last 8 months and if there’s one thing I tell my students about (or badger them about if you ask them) it’s clean code.
What is clean code?
Clean code is well commented, indented consistently, and has visual appeal from across a room. Here are some real world examples. You tell me which is the clean code and which is the ugly code:
Out of those two images above, which do you think is the clean code and which is the ugly code? I’ll give you a second (or 20 seconds) to think about it…
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
The correct answer is exhibit A. The code I showed you is real code that is currently live in production on a very high traffic website. I blurred it not to obscure the code but to simulate what the code would look like from across the room.
Exhibit A shows code with good, consistent indentation. It’s obviously well documented and looks like code you’d be able to wrap your head around if you ever had to work with it.
Exhibit B shows code with inconsistent spacing, large blocks of ugly variable setting, and no comments whatsoever. Don’t be like the author of Exhibit B. Let’s talk about how to write good clean code.
The benefits of code cleanliness
If you take care to ensure your code is clean you’re going to enjoy benefits like:
- Being able to come back to the code in a year and understand what it does
- Ugly code breeds more ugly code. Clean code almost guarantees that the next person responsible for maintaining it will treat it well. Kind of like a car. If you drive a beater and drive like an asshole, anyone you lend the car to will treat it like crap too. But if you let someone borrow your nice, clean, Mercedes then whoever you let use the car will treat it wish respect even if they do rev the engine a couple of times to see how fast it could go
- You can auto-generate documentation using tools like JSDoc, Docco, Yard, RDoc, etc.
- Working on teams, whether that means open source collaborators or coworkers, you’ll be more productive
- The other developers will get up to speed very quickly
- You end up looking like a pro
- The application will last much longer. Every project goes through three main phases; development, maintenance, end of life. Clean code is easier to maintain which makes it so your code will stay in production for far longer before it gets replaced or rewritten
Clean code is a sign of excellent developer and there are many more benefits to clean code I haven’t talked about.
How to write clean code
This may seem subjective, and some of it is, but generally speaking I think every developer can agree on what clean code looks like when they see it. In fact I’ve had both students and colleagues say “ohhhh, now that’s clean code!” after seeing some code I wrote.
The debate is over. Spaces (A.K.A. “soft tabs”) have won. A space is a space is a space no matter what OS, IDE, or text editor you use. The debate still rages over whether 2 spaces or 4 is best but for the sake of this article let’s say that 2 spaces are the way to go. In just about every language I write I always use 2 space indents. Using 2 spaces is just enough of an indent to recognize nested blocks and it conserves line space. We don’t want our lines to go past about 72 characters.
The 72 character line length comes from studies (reference needed, I’ve only read about these studies, heard about it from designers too) showing that 72 characters is about the max length the human eye can follow without losing its place within a block of text or a paragraph if we’re talking about prose in place of code.
After 72 characters or at the end of a line I sometimes add a comment to describe what the current line does. Comments are the exception to the rule because comments don’t need to be read more than once. They’re just sort of reminders that you skim over once but after that the code speaks for itself.
This is okay:
1 2 3 4
A roughly 72 character line of code is also great for when you need to review anything side by side. That something could be another file you need to reference or maybe you’re following some docs or you have a browser window and text editor open side-by-side.
Break your lines, please
Another attribute of clean code is newlines. You know, line breaks. You know, like when you press enter to move the cursor to the next line. Would you have read this far if I wrote this entire article in one long paragraph? Of course not. Hell, I’m not even sure if you’ve made it this far anyway but I’m still writing and it’s clean writing.
When writing technical docs or anything meant for human consumption you use line breaks to separate your thoughts. Each paragraph represents a different thoughts. The same applies to writing code
Spaces between braces and brackets
I cringe when I see people connect their curly braces to their parenthesis.
Don’t do this:_
1 2 3
The right way:
1 2 3
Leave space in assignment operators
Another cringe-worthy pattern I see in code is the space-less assignment operator. Please, everyone give your code some room to breathe. Do not assign variables like
var myVariable=“some string”. Do it like this instead
var myVariable = ‘some string’;. Look at how much better that second one looks.
Code needs room to breathe. It needs space to roam free and be legible. I most often see this come up with new developers who are afraid that if they add too many spaces in their code it’ll break. Don’t worry guys, nothing is going to break because of a space added or missing in your variable assignments,
Use single quotes for strings
Other code styles
I can get into more specifics about what clean code looks like but I’m not writing an entire style guide here. This is just a little article on why clean code is good code. If you want examples of clean code check out my more recent projects on GitHub.
Enforcing code styles
When you’re working with a team you’d usually have a discussion about code style and codify it in some sort of style guide document. If you’re working on an open source project and accepting pull requests from collaborators then you’ll need a style guide document. The problem is not everyone reads it and some people are just assholes and don’t care. So how do you make sure no one commits dirty code to your repository? I can think of two great ways to achieve this.
The Editorconfig project is a standard that most popular IDEs and text editors support these days either by default or using a plugin. Editorconfig allows you to specify a lot of your code styles (mostly spacing) in a dot file called
.editorconfig. Add this to your project’s repository and insist that all collaborators install the plugin for their editor or IDE.
You can use Git’s hook feature to run a code linter when someone commits or pushes code. You’ll have to write your own scripts or find a ready-made solution for your use case but Git hooks could help you keep code clean.
The idea is that you have all collaborators enable a pre-commit hook which runs when you run
git commit, checks your code, then reports on any code style issues and forces you to fix them before you can commit your changes. Unfortunately, on open source projects you’d have to rely on every person who wants to contribute to install the hook. Right now GitHub doesn’t support server-side hooks so you can’t rely on GitHub running a hook when code gets pushed to a remote that’s hosted on GitHub.
In the end, the cleanliness of code is important to how it gets treated over time, is directly correlated with the lifetime of the codebase, and it can change how developers feel about the project. For a happy team and long lasting working code, make sure it’s clean. The extra couple of seconds you take now to line up your variable names makes a big impact down the road on how long your runs before being replaced.