If you have any questions or feedback, pleasefill out this form
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
- 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
- Methods don’t need to start with
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.
- 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
-
Even for temporary variables, provide a bit more information.
- tmpNumber
- tmpFile
- tmpUsrData
-
If the loop variables i and j have meaning, choose appropriate names, e.g., row, col, index.
-
Choose specific method names.
-
If a variable has a unit, include it.
- startSec
- delayMs
-
Naming for important attributes
- plainData
- encryptedData
-
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
- Does filter mean to filter out items or keep them?
- Min and max prefixes
- Boolean values
- computeData => sounds more like executing a resource-intensive function
Consistent Formatting
- Maintain consistent formatting
- Adjust code for a similar appearance
- Related code should be grouped together as a paragraph.
- 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?
- It does not make the meaning more concise.
- Its logic is not complex enough to warrant a replacement with a variable.
- 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.
If you found this article helpful, please consider buying me a coffee ☕ It'll make my ordinary day shine ✨
☕Buy me a coffee