On writing readable code
Too often, we write code that is unnecessarily difficult for the human eye to parse.
The extra time taken to decipher jumbled-looking code is a waste that builds up, and we should do something about it.
Imagine you are on death’s doorstep.
“Why now?” you ask the Grim Reaper.
“Because you spent precious days of your life reading Steve’s crappy code.” the Reaper solemnly replies.
Sorry, Reaper, but I would rather spend those extra days doing much better things. Wouldn’t you?
We should go beyond debating how many spaces(or tabs, blech) to use, whether to use camel or snake case, what naming conventions to use, et cetera, and find more ways to improve the readability of our code.
Keep the Reaper at bay and save everyone’s time with these techniques I use to improve code readability.
Make groups of code symmetrical
Instead of this:
const something = 'foo';
const somethingElse = 'bar';
const anotherThing = baz';
Try this:
const something = 'foo';
const somethingElse = 'bar';
const anotherThing = 'baz';
That’s purely a stylistic choice, as the spaces added are not syntactically-significant, but I find this makes the code a little easier to read.
And even better…
Reduce repetition of language keywords
For example, if your language features keywords for defining variable types, instead of this:
const something = 'foo';
const somethingElse = 'bar';
const anotherThing = 'baz';
Consider this:
const something = 'foo',
somethingElse = 'bar',
anotherThing = 'baz';
Look, ma! No extra bytes!
Note that comma-separation has replaced the semicolons since we have merged three statements into one. I’m not a stickler for using semicolons in JavaScript, but this is one reason I continue to use them; with commas, you can combine multiple statements into one.
Use shorter syntax
Ditch unnecessary tokens when possible. Sometimes, you don’t need those curly braces.
Instead of this:
function didRender(){
let el = this.get('element');
if(el){
el.text('Hello world');
}
}
Do this:
function didRender(){
let el = this.get('element');
if(el) el.text('Hello world');
}
Some people object to this, and I don’t know why. Maybe they want the explicit clarity of curly braces, which is legitimate. With really simple statements, I find them unnecessary.
Return early
Instead of this:
function doSomething(){
let output;
if(this.canDoThing){
if(this.hasThingToDo){
if(this.hasPermission){
let result = this.thingToDo();
if(result.ok){
output = result.message;
} else {
output = 'failed to do thing';
}
} else {
output = 'not allowed to do thing';
}
} else {
output = 'has nothing to do';
}
} else {
output = 'cannot do thing';
}
return output;
}
What about this?
function doSomething(){
if(!this.canDoThing) return 'cannot do thing';
if(!this.hasThingToDo) return 'has nothing to do';
if(!this.hasPermission) return 'not allowed to do that';
let result = this.thingToDo();
if(!result.ok) return 'failed to do thing';
return result.message;
}
Of course in real life you should either raise exceptions or pass errors to callbacks when something is preventing your function from doing what’s expected of it.
Long method chain? Add some newlines.
Instead of this:
let results = json['data'].map(r => r.attributes).select(r => r.isPublished).sort((a,b) => a.publishedAt - b.publishedAt);
Try this:
let results = json['data']
.map(r => r.attributes)
.select(r => r.isPublished)
.sort((a,b) => a.publishedAt - b.publishedAt);
Group operators with parentheses
Instead of this:
const foo = a && b < 0 || c > 0 || d + 1 === 0;
Consider this:
const foo = (a && b < 0) || c > 0 || (d + 1 === 0);
This is easier for my eyes to parse, and it makes the order of operations more clear. This goes contrary to my previous idea around removing unnecessary syntax, but this a case where added syntax makes things more clear.
Add clarity and meaning with emojis
Everyone loves emojis. Yes, everyone.
Did you realize that you can also use emojis in your code comments? Emojis can make your comments noticeable and provide some context.
// 🚨DEPRECATED
function doThings(){
... does one thing ... does a second thing
// 👆a note about how the second thing works ... does a third thing
// 🐛BUG happens here in some conditions}
Important sections of code really stand out with colorful symbols. They also can come in handy when doing text searches in your project. Searching by 🚨could match all important comments, not just comments for deprecation.
Modern operating systems, browsers, and IDEs support emojis. Take advantage!
Conclusion
As I said, these techniques are all my suggestions. I hope these tips help you in writing code that is easier for you and your peers to read. If you have a suggestion of your own, or think any of my suggestions are bad, I’d love to hear about it in the comments.