iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🔍

What Does "Readable" Mean? A Metric for Code Quality

に公開
2022/04/12

What is "good code"? While there are various metrics for code quality, many would agree with the indicator that "readable code is good code." However, defining what exactly constitutes readable code is a challenging problem.

In this article, I will share my perspective on "readable code" as high-quality code. I don't intend to claim this is the only correct answer, but if you find it helpful or resonate with it, please share this article with those around you.

Note that while the sample code is shown using TypeScript, I will provide explanations as needed so that even those without TypeScript experience can follow along.

Short Summary

  • Readable code is code where the writer's intent is easily conveyed.
  • To convey the writer's intent to the reader, leave hints that allow the reader to infer that intent.
  • When there are multiple ways to write something, choose the option that provides the best hint (in other words, the one with the most information).
  • When providing hints, you should favor the rational reader.

Below, I will explain this philosophy through several concrete examples.

The Problem of let and const

In JavaScript/TypeScript, you have three options when declaring variables: using var, let, or const. var has existed since the beginning of JavaScript, while let and const were added in ES2015. There are differences between var and the other two, such as whether the scope is function-scoped or block-scoped, and whether re-declaration of the same variable is possible. Since let and const were added later and are superior, you can simply use one of these two and avoid using var.

The difference between let and const is that a variable declared with the latter (const) cannot be reassigned.

let foo = 123;
foo = 456; // This is OK

const bar = 0;
bar = 999; // This is an error

In JavaScript/TypeScript, every time you declare a variable, the choice between declaring it with let or const arises. If a variable is to be reassigned, let is the only option, so it will inevitably be used. However, variables that are actually never reassigned (and thus could be declared with const) occur quite frequently in JavaScript/TypeScript programming. Depending on the program, it wouldn't be an exaggeration to say that in most cases, over 90% of variables are not reassigned. The question is which one to use in that situation.

From the perspective of providing hints to the reader, const should be used for variables that are not reassigned. This is because a variable declared with const carries the information that "this variable will not be reassigned," whereas let carries no such information, implying "this variable might or might not be reassigned." Since const provides more information to the reader, you should naturally choose const for any variable where it can be used.

In fact, reassigning variables adds complexity to logic, as "what is in that variable varies depending on the situation." Therefore, when reading a program, one must pay special attention to variable reassignments. Variables declared with let that "might be reassigned" place a greater burden on the person reading the program compared to const. For this reason, the use of let should be kept to the necessary minimum.

Furthermore, a rational reader, based on the above discussion, would think, "Since they specifically used let instead of const, this variable must be reassigned later." If you use let for a variable that is not reassigned, you will give this reader a false understanding and cause confusion. Especially according to the mindset of this article, a program is a collection of rationality and necessity, and betraying rational interpretation is itself irrational, so the rational reader should be prioritized as much as possible.

Regarding the topic of let and const, there is a saying that "originally, const was intended to be used only for constants, and all ordinary variables were expected to be declared with let." However, there is no need to strictly follow this. While it is important to respect history, it does not outweigh the practical benefit that const increases the amount of information.

Using readonly

On a similar topic, TypeScript has features such as readonly arrays and readonly properties. For example, while number[] is a "numeric array type," readonly number[] represents a "non-writable numeric array type."

This readonly is particularly powerful when used in function arguments. For example, let's consider a sum function that returns the sum of a given numeric array.

function sum(arr: number[]): number {
    let result = 0;
    for (const num of arr) {
        result += num;
    }
    return result;
}

Since this function only reads the given array arr and does not modify it, we can use readonly as follows. This makes it impossible to modify arr inside sum (resulting in a compilation error).

function sum(arr: readonly number[]): number {
    let result = 0;
    for (const num of arr) {
        result += num;
    }
    return result;
}

In my opinion, the argument for sum should be of type readonly number[]. This is because, once again, writing readonly increases information. A reader of the program can tell just by looking at the function type (argument type) that "this function does not modify the given argument array." Conversely, with a function that doesn't say readonly, you don't know whether it will modify the given array (or object) or not, and it's even more rational to think, "Since it doesn't say readonly, it's a function that modifies it."

The pity is that readonly is long and tedious to write everywhere. In my view, the readability of the program takes priority over a little tediousness, though I don't deny it can feel like too much trouble for things like nested objects. In that respect, languages like Rust, which make immutability the default, have clever designs.

Providing Accurate Interfaces

In typed languages[1], you define the interface of a function by the types of its arguments and its return value. The more accurate this interface is, the more information it provides. Therefore, you should describe the interface as accurately as possible.

Let's look at a somewhat TypeScript-like example. Let's create a function that returns different numbers depending on the given argument string.

function getFontSize(size: string): number {
    if (size === "small") {
        return 10;
    } else if (size === "medium") {
        return 16;
    } else  {
        return 24;
    }
}

This getFontSize function returns 10 if passed "small", 16 if passed "medium", and 24 if passed any other string. Even so, this "any other string" is a bit vague. Specifically, what would that be? Should we pass something like "hogehoge" or "Pikachu"? Most likely, such use is not intended.

In TypeScript, you can specify a more specific type than just "string (string)" by combining literal types and union types.

type SizeString = "small" | "medium" | "large";

function getFontSize(size: SizeString): number {
    if (size === "small") {
        return 10;
    } else if (size === "medium") {
        return 16;
    } else  {
        return 24;
    }
}

In the example above, the SizeString type is defined as "a string type that is either "small", "medium", or "large"." Therefore, the getFontSize function that takes SizeString as an argument can only receive these three types of strings. Now, it is clear that if you want 24, you should pass "large" (and you cannot pass anything else).

The function's interface has become stricter, moving from string to SizeString. Generally, a stricter interface is one with more information.

Literal types and union types are concepts rarely seen in languages other than TypeScript, but in many cases, you can achieve similar expressions in other languages using so-called enums (languages with ADTs like Rust are particularly excellent in this regard). TypeScript also has enum, but it is an older feature that should be avoided; the literal types and union types mentioned above are more suitable.

By the way, if you wanted to, you could also make the return type of getFontSize a union type like 10 | 16 | 24, but it is written as number here. This also has meaning: it serves to tell the reader that "the specific values 10, 16, and 24 themselves don't have special significance." It indicates through the function's interface that this is a function that returns some kind of numeric value and should not depend on individual numbers.

public and private

When you create a class and its fields, you have a choice of making those fields public (visible from outside the class) or private (visible only within the class). Whether you make a field public or private significantly changes the information provided to the reader.

In the following Human class, name, age, and presentCount are public fields.

class Human {
  name: string;
  age: number;
  presentCount: number;

  constructor(name: string, age: number) {
    this.name = name;
    this.age = age;
    this.presentCount = 0;
  }

  grow() {
    this.age++;
    this.presentCount++;
  }

  getPresent() {
    if (this.presentCount <= 0) {
      throw new Error("You have no present!");
    }
    this.presentCount--;
    return "present";
  }
}

This Human has logic where "you gain the right to getPresent() once for every time you grow()." This is implemented via presentCount; initially, presentCount is 0, but it accumulates each time grow() is called and can be used in getPresent().

To jump to the conclusion, presentCount should be private, shouldn't it? While the code above could be analyzed from various perspectives like design, in this article, we will consider it from the viewpoint of "readability."

In TypeScript, you have choices of making class fields public or private[2], and whether to make them readonly or not. In this case, since presentCount and other fields are public (and not readonly), there is room for them to be modified from outside the class. In fact, not using private or readonly should lead to the inference that external modification is expected.

In other words, a reader must always interpret the code with the possibility in mind that "fields might be modified from the outside." This is the same as the discussion on let and const: the possibility of external modification becomes a burden for the reader. Therefore, unless it is truly necessary, you should prevent external interference. In fact, code that leaves the possibility open when it won't be modified externally can even be said to betray the reader.

Regarding the code above, if presentCount can be modified from the outside, one can bypass the intention explained earlier (e.g., uhyo.presentCount += 100). It is difficult for a reader to grasp the writer's intent. That is, it would be hard to judge whether that is something you must not do, or something you are allowed to do (like a "bonus gift campaign"). When there are things that cannot be understood, reading the code naturally becomes difficult.

In this case, we should make presentCount private, and if we want to run a bonus gift campaign, we should think of a nice design for that specific purpose. Making presentCount private looks like this (in JavaScript/TypeScript, you can use # to represent private fields[3]).

class Human {
  name: string;
  age: number;
  #presentCount: number;

  constructor(name: string, age: number) {
    this.name = name;
    this.age = age;
    this.#presentCount = 0;
  }

  grow() {
    this.age++;
    this.#presentCount++;
  }

  getPresent() {
    if (this.#presentCount <= 0) {
      throw new Error("You have no present!");
    }
    this.#presentCount--;
    return "present";
  }
}

Conclusion

In this article, we examined several examples from the perspective of "readability" and discussed code quality. Each topic is relatively major and can be considered from various angles, but in this article, we consistently thought in terms of "the writer's intent" and "the information provided to the reader."

Through these considerations, I hope you have understood that a philosophy based on "readability" can be widely applied to various problems.

Furthermore, this article emphasizes that the reader is in a position to "think" and "infer." Just as writing code readably is the writer's responsibility, correctly reading the writer's intent is the reader's responsibility. Like a mystery game, it can be said that the more both parties reason rationally, the higher the code quality (from the perspective of this article) becomes. Therefore, while aiming to be a writer who writes readable programs, being a reader who can think rationally is also a goal to strive for.

To reiterate, the ideas described in this article are just one way of thinking about "code quality." Various perspectives and metrics should naturally coexist. However, I believe the philosophy in this article is widely applicable. If you resonate with it, please feel free to share it.

脚注
  1. I adopt the convention of calling static types "types." Languages like JavaScript are untyped languages. ↩︎

  2. There is also protected, for the record. ↩︎

  3. Due to historical reasons, there is also a way to write it like private presentCount: number; (so-called soft private), but I recommend the syntax used in the main text (so-called hard private). ↩︎

GitHubで編集を提案

Discussion