High readability

Simply put, high readability means being able to read the code and understand it. Code that is not readable will slow you down and could lead to mistakes, where you assume it does one thing but in fact it does something else.

Let's look at an example, shown in the following code:

type House struct {
a string
b int
t int
p float64
}

In this example, the code has a problem with its naming. Short variable names seem like a win; less typing means less work, right? In the short term, yes, but in the long run, they are hard to understand. You are forced to read the code to determine what the variable means and then re-read the code within that context, whereas a good name would have saved us from the first step. This does not indicate that super-long names are right either; they also add to the mental burden and waste screen real estate. A good variable is typically one word, with a commonly understood meaning or purpose.

There are two situations in which the aforementioned principles should not be followed. The first is methods. Perhaps it's because of my time using C++ and Java and the lack of a this operator in Go, but I find short method receivers to be useful, probably because of the fact that they are consistent throughout the struct, and only the short variable differentiates them from all the others.

The second situation is when we are working with test names. Tests are essentially mini stories; in this case, long names are often entirely appropriate. Comments would work too, but less effectively, as the test runner outputs the test's name when it fails and not the comments.

Let's update the preceding example with these ideas in mind and see if it's any better, as shown in the following code:

type House struct {
address string
bedrooms int
toilets int
price float64
}

For more on readability, flip back to the Optimizing for humans section in Chapter 3, Coding for User Experience.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.140.195.225