logo
  • 現在做什麼
  • 關於我

Kalan

文章分類

  • 前端
  • 開發筆記
  • 雜談
  • 年度回顧

快速連結

  • 現在做什麼
  • 關於我
  • 聯絡我
  • 職涯思考🔗

關注我

在福岡生活的開發者,分享軟體開發與日本生活的點點滴滴。

© 2025 Kalan Made with ❤️. All rights reserved.

Readable Code

Written byKalanKalanMar 20, 2016
Home/Review
💡

If you have any questions or feedback, pleasefill out this form

Japanese原文

Table of Contents

  1. Is Shorter Code Better?
  2. Surface Structure
  3. Unambiguous Names
  4. Consistent Formatting
    1. Code Quality Tools
  5. Using Methods to Eliminate Confusion?
  6. Order and Paragraph Distinction:
    1. Conclusion
    2. Keep Comments Concise
    3. Battling Complex Logic:
    4. Encapsulating Large Expressions in Variables.
  7. 4. Variables:
    1. Turning Ideas into Code:
    2. Avoid Writing Unnecessary Code

This post is translated by ChatGPT and originally written in Mandarin, so there may be some inaccuracies or mistakes.

Is Shorter Code Better?

While reducing code can improve readability, the key focus should be on shortening the time it takes to read code.

Surface Structure

  1. Clear naming for methods and variables
    • Methods don’t need to start with do
    • Avoid ambiguous names when choosing vocabulary, e.g., pop vs. popItem
    • Add more information to method names
function getPage() {}
// The other party might not know how getPage is implemented? Scraper? Ajax?
function fetchPage() {}
// This is likely clearer as it indicates the use of Ajax and that it returns JSON.
  1. Look for more precise vocabulary
    • send => deliver, dispatch, announce, route
    • find => search, extract, locate, recover
    • start => launch, create, begin, open
    • make => create, set up, build, generate, add, new, compose

Clarity is more important than cuteness

  1. Even for temporary variables, provide a bit more information.

    • tmpNumber
    • tmpFile
    • tmpUsrData
  2. If the loop variables i and j have meaning, choose appropriate names, e.g., row, col, index.

  3. Choose specific method names.

  4. If a variable has a unit, include it.

    • startSec
    • delayMs
  5. Naming for important attributes

    • plainData
    • encryptedData
  6. If a variable has a wider scope, using a longer (or more informative) variable name is a better choice. Conversely, if it only exists for a few lines of code and others can quickly understand what it does, using an alias is acceptable.

Unambiguous Names

  1. Does filter mean to filter out items or keep them?
  2. Min and max prefixes
  3. Boolean values
  4. computeData => sounds more like executing a resource-intensive function

Consistent Formatting

  1. Maintain consistent formatting
  2. Adjust code for a similar appearance
  3. Related code should be grouped together as a paragraph.
  4. Aesthetics of comments

Why is formatting so important? First, it makes it easier (and more appealing) for others (or yourself) to read the code later. Additionally, it allows you to spend less time understanding what your code is doing, which is a win-win!

Code Quality Tools

  • eslint

  • stylelint

Using Methods to Eliminate Confusion?

If you find yourself feeling confused while doing something, it's time to wrap it in a method.

It’s human nature to deceive consumers with beautifully crafted yet misleading packaging (just kidding). The point isn’t whether you can fool others; it's about whether you can fool yourself. If you don’t respect your own code, neither will others.

For example:

assert(checkTime("12:00")) === "12:00"
assert(checkName("kalan", 20)) === { name: "kalan", age: 20 }
assert(checkPaid(20000, true)) === 20000

Looking closely at the code above, it's clear that they are doing similar things and there are some repeated strings. Moreover, it's lengthy, and we need some time to understand what these lines of code are doing.

This is when refactoring is necessary; we can wrap it in a method.

function checkValue(type, value) {
  if (type === "time") {
    assert(checkTime(value));
  }

  if (type === "name") {
    assert(checkName(value) === value);
  }

  if (type === "paid") {
    assert(checkPaid(value) === value);
  }
}

// checkValue(type,    value);
//  					[string] [depend]
checkValue("name", kalan);
checkValue("time", "12:00");
checkValue("paid", 20000);

This way, the code becomes more concise and readability improves! Again, it’s not just about having shorter code; good code is about being easily understandable. Beyond that, there are additional benefits:

  • Clearly presents the testing part.
  • Easier to add other tests!

Order and Paragraph Distinction:

Long stretches of code can be daunting for anyone, including yourself. When declaring variables or expressing statements, consider splitting them based on the actions being performed. The same principle applies to writing articles, where paragraphs are important.

function getUserInfo(userName, age) {}

getUserInfo("kalan", 20)

// getUserInfo(userName, age)
// 					  [string]  [number]
getUserInfo("kalan", 20)

If there are identical function calls, align parameters for easier reading.

command = {
	{ "timeout"      ,   null,     cmd_spec_timeout},
	{ "timestamping" ,   bull,     cmd_adj_boolean},
}

When writing comments, avoid being too rigid. Simply jot down your thoughts at the time and what this function is supposed to do. Sometimes, after a while, you might forget what this function does.

--

#2. The Comment Section:

Comments exist to help others understand the programmer's thoughts and also help you remember your own initial ideas.

  • How to write good comments, and what does not need commenting.
  • Parts that should not be commented
  • Think from the reader's perspective

Don’t let comments steal the spotlight from the code itself

Avoid writing resistant comments. This usually takes time to appreciate. However, writing comments as soon as the project structure is still manageable is definitely a good practice. Otherwise, you might end up writing something that goes against your conscience:

// TODO: refactor

And then never follow up.

Conclusion

  • Reasons for choosing specific writing styles
  • Defects in the code.
  • Which parts might confuse the users

Keep Comments Concise

  • Describe your code more precisely without using pronouns for parameters.
  • If the behavior of parameters is complex, provide examples for clarity.

#3. Flow Control:

The most common is the if/else judgment. The book provides a guideline: start with affirmative conditionals and address the simpler situations first. If your function/method has a return value, return it as soon as possible!

  • Utilize De Morgan’s laws: this principle should be familiar in technical fields! It simplifies some complex logical evaluations.

Battling Complex Logic:

The book mentions an interesting approach that I want to note down. When implementing a range, we might have a method called overlapWith to determine if two ranges overlap. Instead of directly comparing if these two ranges overlap, it’s easier to check if they do not overlap. This is because you only need to compare two conditions: whether the end of the other is before the range starts or the start of the other is after the end.

Encapsulating Large Expressions in Variables.

$(".thumb_up").removeClass("highlighted");
$(".thumb_up").removeClass("highlighted");
$(".thumb_up").removeClass("highlighted");

// refactor

const $thumbUp = $(".thumb_up");
const highLight = "highlighted";

$thumbUp.removeClass(highLight);
$thumbUp.removeClass(highLight);
$thumbUp.removeClass(highLight);

4. Variables:

The longer a variable exists, the harder it is to debug.

  • Reduce unnecessary variable declarations.

What constitutes an unnecessary variable?

  1. It does not make the meaning more concise.
  2. Its logic is not complex enough to warrant a replacement with a variable.
  3. It is only used once.
  • Use one-time variables

In functional programming, we strive for functions to be pure and immutable. The same goes for variables; try to keep your variables as const or immutable. This way, not only is your function clearer, but it’s also easier to pinpoint where errors may arise.

Turning Ideas into Code:

Start by verbally describing the behavior, then translate that behavior into code. This can help programmers write more natural code.

Avoid Writing Unnecessary Code

  • Understand the requirements.
  • Rethink the requirements.
  • Regularly read the API to maintain familiarity with the standard library.
← In the pursuit of excellence, we gradually ordinary

If you found this article helpful, please consider buying me a coffee ☕ It'll make my ordinary day shine ✨

☕Buy me a coffee

Table of Contents

  1. Is Shorter Code Better?
  2. Surface Structure
  3. Unambiguous Names
  4. Consistent Formatting
    1. Code Quality Tools
  5. Using Methods to Eliminate Confusion?
  6. Order and Paragraph Distinction:
    1. Conclusion
    2. Keep Comments Concise
    3. Battling Complex Logic:
    4. Encapsulating Large Expressions in Variables.
  7. 4. Variables:
    1. Turning Ideas into Code:
    2. Avoid Writing Unnecessary Code