4 Tips for Improving Code Readability
We only get seconds to attract a reader's attention, and readable code snippets can make the difference. Discover 4 tips for improving readability of your code snippets.
Join the DZone community and get the full member experience.
Join For Free
Most readers will never read an entire article. More specifically, most readers will never make it more than 75 words into an article, and they will make that decision in seconds. According to a 2014 Time Magazine article, 55% of readers on the internet will stop reading a website after just 15 seconds. For the average adult—who reads about 300 words a minute—that is only about 75 words. For a 1,500 word article, that is only about 4% of this article—less than this first paragraph.
Bearing that in mind, many are likely to scan an article, rather than read any sizable portion of the text, before making the decision to continue reading. In software articles, one of the most obvious parts of the article that can aid or dissuade in keeping the reader's attention is code snippets. Concise, well-formatted code snippets can go a long way in helping a reader understand the purpose of the article, while simultaneously signaling to the reader that we, the author, have taken the effort to ensure that code is readable.
In this article, we will look at four tips that can dramatically improve the readability of code and therefore hold the attention of the reader longer: (1) removing boilerplate code, (2) formatting indentation and spacing, (3) selecting appropriate names, and (4) removing unnecessary comments.
1. Removing Boilerplate Code
Boilerplate code is a code that is redundant or is implicitly understood in the context of a snippet. For example, if we want to instruct a reader to execute a line of code, the main
method is boilerplate code. Unless the article is a beginner article, any Java developer will know that to execute Java code, a main
method is required. The trouble with adding this boilerplate code is that it detracts from the purpose of the snippet. For example, if we wanted to print the string Hello, world!
, we could include the following in our article:
public class Main {
public static void main(String[] args) {
System.out.println("Hello, world!");
}
}
While a reader can discern that the snippet is trying to print a string to standard output, that functionality is obscured. Five of the six lines in the snippet are consumed with code that we already know is needed. Instead, we can remove this boilerplate code, which makes the purpose of the snippet much clearer:
xxxxxxxxxx
System.out.println("Hello, world!");
Another common form of boilerplate code is getters and setters. These methods are commonly understood by Java developers, and unless the article is a beginner article, most developers can imagine what these methods look like. Just like the main
method, getters and setters distract from the purpose of the snippet. Take the following class as an example:
xxxxxxxxxx
public class CorvetteZr1 {
private String vin;
public void turnOn() {
// ...turn the car on...
}
public String getVin() {
return this.vin;
}
public void setVin(String vin) {
this.vin = vin;
}
In this snippet, we are trying to show the reader a class named CorvetteZr1
that contains a single field named vin
of type String
, but the getters and setters take up most of the lines and clutter the snippet. To remedy this problem, we should instead add a comment that states that getters and setters are present and refrain from explicitly including them:
xxxxxxxxxx
public class CorvetteZr1 {
private String vin;
public void turnOn() {
// ...turn the car on...
}
// ...getters & setters...
}
It is much clearer from this snippet that the focus of the code is that the CorvetteZr1
class contains a String
field named vin
. In general, the removal of boilerplate code helps the reader focus on the purpose of our snippets. Each snippet has a purpose, whether as an example of a working application or as a piece of code that the reader should replicate, and we should do all that we can to focus the attention of the reader on that purpose. We can sum up this tip as:
Remove any code that detracts from the purpose of a snippet.
In some cases, such as beginner articles, the purpose of the snippet may be to show a user how to create getters and setters or how to execute Java code using a main
method. In such cases, it is important to leave this code, since it is not considered boilerplate code. Instead, this code is essential to the purpose of the snippet. In most cases, though, this code can be removed or replaced with a smaller block of code.
While we have only seen two examples of boilerplate code, there are numerous other instances of this clutter, including:
- Default constructors
- Methods that are irrelevant to the purpose of the snippet
toString
methodsequals
methodshashCode
methods
While many of these methods are essential for code to be executed, they are often systematic (and even auto-generated in some cases), and therefore, the reader can assume what the implementation looks like without explicitly showing it.
2. Formatting Indentation & Spacing
If readers skim a page, one of the first things that they will see is improperly formatted code. Usually, this code is misaligned or lacks proper spacing. Most people—especially developers—desire symmetry, and the lack of proper formatting can be jarring to the point of frustration. For example, the following snippet is valid Java code and can be executed without error:
xxxxxxxxxx
public class Article{private String title;private String author;public void publish(){/* ... */}public void retire(){/* ... */}}
While this snippet is valid, it is far from pleasing to the eye. What's more, it is also nearly impossible to read, which detracts from the purpose of the snippet. A reader will likely spend more time trying to untangle the snippet than actually learning from it.
This snippet stands in stark contrast to the same code when properly formatted:
xxxxxxxxxx
public class Article {
private String title;
private String author;
public void publish() {
// ...
}
public void retire() {
// ...
}
}
We can see how much of a difference a handful of new lines and spaces can make in understanding a snippet. Generally, properly formatted consists of:
- Proper indentation
- Proper spacing between keywords and language tokens (like braces or parentheses)
The specifics for each language differ, but authors should always understand the rules for the language of a snippet. For example, if a Java code snippet is added to an article, it should have a 4-space indentation for each new section of code (i.e., within a class or method definition) and not have a space between the name of a method and its parameter list (i.e., the snippet should not be written as public void retire () {
).
Some rules are flexible, and might even be hotly debated, but one scheme should be selected and applied consistently to all snippets of the same language in an article. If we decide to have an opening brace on the same line as the method signature for Java, rather than one on the following line, then this approach should be used for every Java snippet, not just for some of them.
We can sum this tip up as:
Understand the formatting rules for the language of a snippet and apply them consistently.
3. Selecting Appropriate Names
Any code we write should read like a book. A reader, even the most novice, should be able to read a snippet and understand, generally, what is trying to be accomplished. Even if he or she does not understand the specific syntax of the language, the reader should be able to gain a high-level understanding of what is happening. Take the following as a counterexample:
xxxxxxxxxx
public class LibraryClass {
public BookContainer co(String t) {
BookContainer b = get(t);
b.setFlags(true, false, false);
return b;
}
}
Looking at this code, it's difficult to tell what is happening without some context. On the other hand, if we replace the above snippet with the following, it becomes very obvious what the snippet is trying to accomplish, even if we do not know the context or even the definition for every method:
xxxxxxxxxx
public class Library {
public Book checkout(String title) {
Book desiredBook = getBookByTitle(title);
desiredBook.markCheckedOut();
return desiredBook;
}
}
Based solely on the names in our snippet, we can see that we are checking out a book from a library. While we used more letters and words in the second case, the benefits from the additional characters far outweigh the "screen clutter."
There is an important exception to using more descriptive wording: Well-known variable names, such as loop indices. For example, while i
is not a very descriptive variable name, it is universally known (along with j
and k
) as loop indices, and therefore, no explanation or wording is needed:
xxxxxxxxxx
for (int i = 0; i < 10; i++) {
// ...iterate with “i” as index...
}
There may be times that having a more descriptive loop index name will be useful, but these cases are usually the exception, rather than the rule
Beyond the names themselves, there are also naming conventions for each language that ensure that variables, classes, methods, and other words are named in a consistent manner. For example, the convention for Java is to name variables using camel case, where the first letter is lowercase, but the naming convention in Python is to use snake case (separate words with underscores, such as some_variable_name
). While the naming conventions may vary by language, just like indentation and spacing, they should be applied consistently for all snippets of the same language.
This tip can be summed up as:
Make code read like a book by using descriptive names and following the naming conventions of the language.
4. Removing Unnecessary Comments
The last thing we can do to focus the reader's attention to the parts of our snippets that matter is to remove unnecessary comments. In practice, that means removing almost every comment in a snippet. The only exception is usually those that we explicitly added when removing boilerplate code or placeholder comments, such as method bodies that are not pertinent to a specific snippet.
For example, it is common to see the following in an article:
xxxxxxxxxx
public class Library {
public Book checkout(String title) {
// Find the desired book by its title
// This method should throw an exception if the
// book cannot be found or if the supplied
// title is null
Book desiredBook = getBookByTitle(title);
// Mark our desired book as checked out
// This ensures that no other user can checkout
// this book. We don’t want to have two users
// check out the book at the same time.
desiredBook.markCheckedOut();
// Return the book we checked out
return desiredBook;
}
}
There are two main problems with this approach:
- The comments detract from the code itself
- Additional description of the code should be in the text of the article
In the first case, the sizeable comments clutter the three lines of actual code in our snippet. In this case, there are nine lines of comments for five lines of code, which means the snippet is more concerned with the comment than the actual code.
In the second case, the text of the article should be used to describe the snippet rather than comments in the snippet. For example, if the body of the checkout
method requires an explanation, a paragraph can be added below the snippet that describes what is being performed in the method.
Generally, this tip can be summed up as:
Do not include comments in code snippets, unless there is a very good reason to do so.
Conclusion
We do not get much time to catch the reader's attention, and we should seriously consider anything that tips the scales in our favor. In this article, we looked at four techniques that we can use when creating code snippets in our articles to improve the reliability and focus the reader's attention to the pieces that matter. Namely, removing boilerplate code, using proper indentation and spacing, selecting appropriate names, and removing unnecessary comments. While the appearance of code snippets may seem trivial, they can truly make or break whether a reader decides to finish an article or becomes one of the 55% that makes it 15 seconds.
Published at DZone with permission of Justin Albano, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments