Kalan's Blog

Software Engineer / Taiwanese / Life in Fukuoka

Current Theme light

Is shorter code better?

Although reducing code can improve readability, the key is to shorten the time spent reading the code.

Surface Structure

  1. Clear naming conventions and variable names
    • Methods don't need to use do
    • Avoid using ambiguous names, e.g., pop popItem
    • Add more information to method names
function getPage() {}
// The other person might not know the implementation of getPage? Is it a web crawler? Ajax?
function fetchPage() {}
// It might be clearer that it uses Ajax and returns JSON.
  1. Use more explicit terms
    • send => deliver dispatch announce route
    • find => search extract locate recover
    • start => launch create begin open
    • make => create setup build generate add new compose

Clarity is more important than cuteness.

  1. Even for temporary variables, provide more information.

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

  3. Choose specific method names.

  4. If a variable has units, include them.

    • startSec
    • delayMs
  5. Use descriptive names for important property variables.

    • plainData
    • encryptedData
  6. When a variable has a wider scope, it is better to choose a longer (or more informative) name. Conversely, if it only spans a few lines of code and others can immediately understand what the variable is doing, using an alias is fine.

Unambiguous Names

  1. Does filter mean filtering out or keeping?
  2. Use min and max as prefixes.
  3. Boolean values
  4. computeData => more like executing a resource-intensive function

Consistent Formatting

  1. Maintain consistent formatting.
  2. Adjust similar code appearances.
  3. Related code should be in the same paragraph.
  4. Aesthetics of comments

Why is formatting so important? Firstly, when others (or even yourself) revisit the code, it is at least easier (and more enjoyable) to understand. Secondly, you can spend less time understanding what your code is doing. So why not?

Code Quality Tools

  • eslint

  • stylelint

Eliminating Confusion with Methods?

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

Deceiving consumers with fancy but impractical packaging is human nature (mistakenly). The point is not whether you can deceive others, but whether you can deceive yourself. If you don't respect your own code, others won't either.

For example:

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

By carefully observing the above code, it is not difficult to see that they are all doing the same thing, and there are some repeated strings. Moreover, they are too long, and it takes some time to figure out what these lines of code are doing.

At this point, it needs refactoring. 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 is more concise, and readability is improved! Again, it is not that shorter code is good code; code that is easy for people to understand is good code. In addition to these benefits:

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

Order and Paragraph Differentiation:

Long, sprawling code is not something that anyone, even yourself, would want to read. When declaring variables and statement expressions, they can be split according to the different actions performed. The same principle applies to writing articles with paragraphs.

function getUserInfo(userName, age) {}

getUserInfo("kalan", 20)

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

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


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

When writing comments, there is no need to be too strict. Just write down your thoughts at the time and what the function should do. Sometimes, after a while, you will forget what the function is doing.

--

#2. Comment Section:

Comments exist for others to understand the programmer's thoughts. They also help you understand your own thoughts at the time.

  • How to write good comments and what does not need to be commented.
  • Parts that should not be commented
  • Putting yourself in the reader's shoes

Don't let comments take away the rightful place of code.

Avoid writing resistance. This usually takes some time to realize. But it's a good idea to write comments as soon as possible before the project architecture becomes complex. Otherwise, you will only write "TODO: refactor" against your conscience, and there will be no follow-up.

Conclusion

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

Keeping Comments Concise

  • Describe your code more precisely and avoid using pronouns to describe parameters.
  • If the behavior of a parameter is more complex, provide examples to make it clear to the user.

#3. Flow Control:

The most common is the if/else statement. The book provides a guideline to put positive conditional statements first and handle simple conditions first. If your function/method has a return value, make it return as soon as possible!

  • Make good use of De Morgan's laws: This law should be familiar to those in the field of science and engineering! It can simplify some complex logical judgments.

Wrestling with Complex Logic:

The book mentions an interesting way that I would like to record. When implementing a range, we may have a method called overlapWith to determine if two ranges overlap. Instead of directly comparing whether these two ranges overlap, it is easier to compare whether these two ranges do not overlap. Because we only need to compare two conditions => the end of other is before the range. The start of other is after the end.

Store Large Expressions in Variables.

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

// refactor

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

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

//

4. Variables:

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

  • Reduce unnecessary variable declarations.

What are unnecessary variables?

  1. Those that do not make the meaning more concise
  2. Those whose logic is not complex and do not need to be replaced by variables
  3. Those used only once
  • Use variables with one-time writeability

In functional programming, we want functions to be pure and immutable. The same goes for variables; try to make your variables const or immutable. This way, not only can you easily grasp the function, but it also makes it easier to identify points of failure.

Translating Ideas into Code:

First, describe the behavior in spoken language, and then convert the program's behavior into code. This helps 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.

Next

In the pursuit of excellence, we gradually ordinary

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

Buy me a coffee

作者

Kalan 頭像照片,在淡水拍攝,淺藍背景

愷開 | Kalan

Hi, I'm Kai. I'm Taiwanese and moved to Japan in 2019 for work. Currently settled in Fukuoka. In addition to being familiar with frontend development, I also have experience in IoT, app development, backend, and electronics. Recently, I started playing electric guitar! Feel free to contact me via email for consultations or collaborations or music! I hope to connect with more people through this blog.