Let's Talk About Readable Code
Table of Contents
When I first started in web development, if someone told me that making my code readable was important, I would have thought two things: 1. duh, and 2. that only applies in team settings, which didn’t apply to me at the time. But, after working in front-end development environments for nearly a decade now, I’ve learned that writing readable code is no simple thing. I’ve also learned how frustrating it can be when you or a co-worker fail to do it correctly, if at all.
So what is readable code, how do we write it, and is it necessary all the time?
Disclaimer #
First things first: these are my own opinions and you and/or your team should discuss what works best for you. These are by no means hard-and-fast rules that you yourself should follow, but rather my own observations from my years working in the field. Feel free to tell me all the ways I’m wrong in an email.
What is Readable Code? #
Simply put, readable code is code that anyone can jump into and navigate, edit, and maintain without having to decipher the developer’s original intent.
Here’s an example: Your team has hired a new developer with great JS chops, but they’ve never used the framework your team is using for a particular project. They’ve glanced over the docs for the framework and have a basic understanding of it. How quickly will they be able to get into that project and make changes that A. work well within the system you’ve already built, and B. don’t break stuff? If the code was written to be readable, they should have no problem figuring out what each bit of code is doing, make their changes where necessary, and ensure that everything works as expected afterwards.
Hopefully, they know how to make their code readable, too, which will make sure the next developer isn’t caught off-guard with new code to decipher. Let’s look at some basics on how to do it.
How To Make Code Readable #
Comments #
Comments are the quickest and possibly the most effective way to make your code more readable. And yet, they’re one of the most frequently neglected methods.
I think as developers we have a tendency to try to solve problems as quickly as possible, which often means jumping into the code before anything else. We just want to get a few lines down to get the idea started! Often, this leads to writing dozens of lines before adding a single comment, leading to us wanting to finish what we’ve started before considering whether it is the best solution or how it fits into the bigger picture. And, of course we always intend to go back to add those comments, right?
Not always. Here’s something to try: Comment out your core functionality before you even write any code. Think of it as an index and outline for the code you’re about to write. Not only will this make adding clear, concise comments throughout the code easier, but it will help you think through the problem before starting on a solution, which can help you come to better solutions. Win win!
Examples #
Let’s look at a couple of examples.
CSS
Let’s say you need to write some CSS for a little ‘About Me’ style card. You’ll have an image at the top, a title of the person’s name, and a short blurb about them. Throw some comments in… Something like this.
/* Start About Me Card */
/* Container Styles */
/* Image Styles */
/* Title Styles */
/* Bio Styles */
/* End About Me Card */
Now, we have already added some comments telling other developers what each section of the stylesheet will address, and we also have an outline for each part that we need to write styles for.
Let’s put some styles in there.
/* Start About Me Card */
/* Container Styles */
.card {
background-color: #f8f8f8;
border-radius: .5em;
padding: 12px;
}
/* Image Styles */
.card img {
border-radius: .25em;
width: 80%;
height: auto;
}
/* Title Styles */
.card h2 {
color: #121212;
font-family: sans-serif;
font-size: 2rem;
}
/* Bio Styles */
.card p {
color: #121212;
font-family: sans-serif;
font-size: 1rem;
}
/* End About Me Card */
But, let’s say there was something more specific the design team wanted to add after you got started, and you want to make sure other developers were aware of where that’s added. Let’s say there was one card that needed a special animation on it. It can be helpful to add a comment saying what the animation does and where the keyframes can be found, should they need updated.
/* Start About Me Card */
/* Container Styles */
.card {
background-color: #f8f8f8;
border-radius: .5em;
padding: 12px;
}
/* Featured cards get 'fade-in' animation */
.card.featured {
animation: fade-in 1s forwards;
}
/* Image Styles */
.card img {
border-radius: .25em;
width: 80%;
height: auto;
}
/* Title Styles */
.card h2 {
color: #121212;
font-family: sans-serif;
font-size: 2rem;
}
/* Bio Styles */
.card p {
color: #121212;
font-family: sans-serif;
font-size: 1rem;
}
/* End About Me Card */
Now, we have context on what’s being done to cards with the class featured
and what animation keyframes to look for if we want to change it.
Certainly, with most teams, CSS won’t need to be commented out in quite that level of detail, but I think it’s good to default to at least one comment per section or module of whatever you’re working on, along with an index at the top of the stylesheet, so team members can at least orient themselves within the stylesheet at a glance.
JS
JavaScript, or any scripting language, requires more detail to ensure that developers not only know what a function is for at a glance, but also what each part is doing.
Here’s a quick example of how I might comment out a function that applies an active
class when an element is clicked.
// Add 'active' class to element when clicked
// CC - 2.6.25
function addActive() {
const element = document.querySelector('.element');
// If the element exists...
if(element) {
// When the element is clicked
element.addEventListener('click', function() {
// Add the 'active' class
element.classList.add('active');
})
}
}
The purpose of each part of the function is now clearly described. Easy! Notice how I also included my initials and the date. This can be helpful for other developers to know who added something and when, which can add helpful context should something stop working later on.
But, comments aren’t the only way to make your code more readable.
Naming Conventions #
A lot of people have a lot of strong feelings about how to name CSS classes, IDs, function names, etc. But, at the end of the day, what matters is that you and your team are on the same page about how and what to name these things.
That said, it’s my opinion that names should:
- Be Descriptive - whether a function name, variable name, or a CSS class name, the name should describe the contents. For example, if the class is for a heading, consider adding ‘heading’ in the name.
- Follow a System - talk with your team about establishing a system for naming things. For example, you could say that all CSS classes should start with your company abbreviation followed by an underscore, the module name, then something more specific.
.cc_bio-card_image {
width: 100%;
height: auto;
}
- Follow Known Conventions - for example, it’s common practice for PHP variables to be in camel case, or for CSS class names to use dashes and underscores. Knowing and following these conventions can help keep code readable by not subverting expectations.
Use Simple Code #
As developers, we love a shorthand. It keeps code clean, reduces overall file size, and it just feels cool to write. But, it can often come at a cost in terms of readability.
Let’s look at a pretty common, super simple JS example. Look at the two following scripts and think about which is easier to read at a glance.
Example one:
let fontColor = isBlue ? 'blue' : 'orange';
Example two:
let fontColor = '';
if (isBlue) {
fontColor = 'blue';
} else {
fontColor = 'orange';
}
Quite a bit easier to understand the second one at a glance, right? Now think about how this effect would multiply across a whole project! Personally, I’d rather write the second and use tools to minify my code for production, but your team needs to consider and agree on the pluses and minuses of these types of trade offs.
Now, obviously good comments will help make the first example easier to understand, but having both is great, too.
Indentation & Formatting #
Similar to naming conventions, how your code is formatted can impact how readable your code is. While there are various methodologies for pretty much any language in terms of where to put indents, spaces, etc. the important thing here is to be consistent, as not doing so makes your code less predictable.
Let’s look at a couple of CSS declarations:
.class-one
{
color: #fff;text-decoration: underline;
cursor: pointer;}
.class-two, .class-three {margin-right: 1em;
padding: 5%
}
Technically, this is valid CSS, but I think we can all agree that this is A. quite ugly, and B. not quick to read. That is, in part, because it’s inconsistent.
Let’s clean it up.
.class-one {
color: #fff;
cursor: pointer;
text-decoration: underline;
}
.class-two,
.class-three {
margin-right: 1em;
padding: 5%;
}
Looks much better! And, it has the bonus of being much more predictable, and therefore readable.
Now that we’ve covered why writing readable code matters and a bit about how to write it, let’s answer the question: is it always necessary?
When Is It Necessary? #
On a Team #
Here’s the thing… As I stated from the beginning, you’ll need to discuss with your team how you want to format your code and when it’s necessary. If you decide you want to write your code one way, but your team another, that’s just asking for trouble. It’s worth setting up a meeting for this kind of stuff and all getting on the same page, if you haven’t already.
I know that I don’t always follow through with writing the best code possible, but I do try to at least meet the standards that my team has set, and will do more to improve on top of that if time allows.
But, what if you’re working on a personal project or just writing something you know only you will be working on?
Without a Team #
At that point, it’s really your choice, but I’d ask you to consider a few things:
- Would it be good practice to ensure your code is readable, even if you’re the only one reading it?
- Will you benefit in the future by making sure your code is readable?
- How can you be so sure that no one else will use or edit this code in the future?
- Will this code ever be seen by a potential employer or colleague?
For me, I find that striking a good balance on personal projects is a good approach. I don’t need things to be perfect, but I’d like my code to be pretty clean and readable, even if just for myself.
Closing #
I hope you’ve learned a bit reading this article, and that it’s either kindled a newfound appreciation for writing readable code, or provided new ideas on how you can improve your code moving forward. If you have any feedback or suggestions for me, feel free to let me know… And then go build something!