Summarizes Ways to Write Better Code

Introduction

This article mainly condenses experiences, and for detailed writing suggestions, you can refer to: Clean Code JavaScript🔗, which provides more comprehensive explanations and examples.

Method 1: Good Naming

When first learning to program, it’s common to dive into logic, syntax, or frameworks and overlook the simplest yet most important thing: “Good Naming.” After grading countless types of assignments, I’ve found this to be the most frequently occurring and the most easy (difficult) problem to solve.
Good naming truly helps improve the quality of any kind of code, aiding both yourself and others in better understanding the context of the program; it is even unrelated to programming! So anyone should be able to grasp this concept.

So what are the universal criteria for “Good Naming”?

Clear and Simple

Naming should be clear and simply describe the contents of the named item. For instance, when declaring a variable for a username, the content should be described clearly; avoid ambiguity and unnecessary elaboration:

// What does a mean? (Meaningless)
const a = 'Joe';
// Temporary data? (Ambiguous)
const usernameTemp = 'Joe';
// It’s obviously a piece of data (Redundant)
const TheUsername = 'Joe';
const usernameData = 'Joe';
const usernameValue = 'Joe';
const usernameInfo = 'Joe';
const usernameContent = 'Joe';
// Nothing is clearly described (Ambiguous + Redundant)
const apiUrl = 'www.example.com/api';
const dataStore = 'Joe';
const str = 'Joe';
// A better naming approach
const username = 'Joe'; // Username, clear
const attractionUrl = 'www.example.com/api'; // Attraction URL, clear
// Retrieving... what data?
function getData() {
// ...
}
// Retrieving user data, OK
function getUser() {
// ...
}
// Retrieving remote user data, OK
function fetchUser() {
// ...
}
const locations = ['Austin', 'New York', 'San Francisco'];
// What does l mean?
locations.forEach((l) => {
dispatch(l);
});
// The respective location, OK
locations.forEach((location) => {
dispatch(location);
});

In simple terms, if naming is merely filling in generic words without real meaning, it should be avoided! Though the above examples may seem obvious, under pressure, time constraints, or unconsciously, such naming could easily occur. It’s fine for small programs, but as the scale increases, it can become disastrous. Never have the mindset of “it’s just practice, I’ll write it first and revise it later,” as this curse will haunt you and anyone reading your code 👻.

Avoid Abbreviations

Using abbreviations makes code more difficult to understand. While it may seem concise and understandable at the moment, it should be avoided. For example, if you’re creating a health point mechanism for a game: Health Point (HP) is common and reasonable, but those unfamiliar with gaming might not know what it means, or then there’s Hit Point? High Point? Highest Point? Conflicts arise in naming. Thus, apart from common acronyms like HTML, XML, or API, refrain from using abbreviations whenever possible.

Avoid Magic Numbers

Magic numbers are digits in code that lack clear meaning. For instance:

function isPasswordValid(password) {
if (password.length < 5) {
return false;
}
if (password.length > 16) {
return false;
}
return true;
}

To make the program more understandable for queries and modifications, magic numbers should not be scattered in the code. It’s typically better to declare them as a variable and give it a good name:

function isPasswordValid(password) {
const passwordMinLength = 5;
const passwordMaxLength = 16;
if (password.length < passwordMinLength) {
return false;
}
if (password.length > passwordMaxLength) {
return false;
}
return true;
}

If there are situations of “potential future changes” or “numbers being difficult to comprehend,” they should be declared as a variable with a good name.

Avoid Using var

var is an early method for variable declaration that, simply put, converts your variable into a global variable, making the program harder to maintain; hence it should be avoided. The fact is: you will see var less and less, and should use const or let instead depending on the situation.

Use Naming Conventions

Different programming language communities have distinct naming conventions🔗. Commonly you’ll see:

  • CamelCase
  • camelCase
  • kebab-case
  • snake_case

And many other types of abbreviations… These naming conventions are all guidelines to make code more consistent. For example, JavaScript typically employs camelCase, while CSS or HTML generally use kebab-case.
Even if you’re not in a multi-developer environment, you will eventually need to read other people’s code, so it’s better to adopt the commonly used naming conventions of the language as soon as possible.

Not only should one be able to use it, but also remain consistent. If a program contains multiple writing standards, it will lead to maintenance difficulties and should be strongly avoided.

Method 2: Avoid Comments

If follow strict naming and conventions, code is usually clear enough to not require comments; excessive comments will absolutely affect the readability of the code!
For me, comments are suitable for describing higher-level concepts, such as why the code is structured in a certain way, rather than detailing the fine points of implementation. In fact, comments may not even be needed, as higher-level concepts can be described in documentation.

This part is more subjective; I believe good code is the best comment. If you feel the same, then try to avoid using comments as much as possible!

Method 3: Don’t Reinvent the Wheel

Whenever programming, we can always stand on the shoulders of others, as long as you know how to leverage them, using existing solutions is the most time and energy-efficient method and can also make your code more concise and easier to maintain. Common problems often already have optimal solutions thoughtfully crafted by others, such as manipulating data strongly suggests referring to Array manipulation methods🔗.
(I plan to write a dedicated article about this 😉)

Focusing on how to solve the problem, rather than how to implement it, can also make your code easier for others to understand.

Method 4: Use the Most Appropriate Data Type

In JavaScript, there are many data types available, such as string, number, boolean, array, object, null, undefined, etc. Each data type has its own characteristics, and using the most appropriate data type can make code more concise and readable, and also avoid unnecessary errors.

For example, using a string to store a number might lead to unnecessary errors, such as '1' + '1' resulting in '11' instead of 2. Such errors are hard to detect; or using a string to store a switch state makes the code hard to comprehend, as a string usually implies storing text rather than a yes or no result.

Selecting the correct data type can make the code neater and avoid unnecessary mistakes.

Method 5: Remove Redundant Logic

Consider a program that calculates whether the entered value is odd, rather than judging the result and returning true or false, just directly return the result:

// ❌ Redundant logic
function isOdd(number) {
if (number % 2 === 1) {
return true;
} else {
return false;
}
}
// ✅ OK
const isOdd = (num) => {
return num % 2 === 1;
};

Some redundant logic arises from creating “abstractions only you understand.” See the following example, where “selected” items are presented with a “custom status code.” Such abstractions only harm code readability and provide no substantial help 😅:

// ❌ Redundant logic
const selected = 0;
if (selected === 0) {
showVegetable();
} else if (selected === 1) {
showFruit();
} else if (selected === 2) {
showFlower();
}
// ✅ OK
const selected = 'flower';
if (selected === 'vegetable') {
showVegetable();
} else if (selected === 'fruit') {
showFruit();
} else if (selected === 'flower') {
showFlower();
}

Instead of making judgments, it would be better to use an object as a lookup table, making such writing simpler and easier to change, and readable depending on the context:

// 😎 OK
const productTable = {
vegetable: showVegetable,
fruit: showFruit,
flower: showFlower,
};
if (isSelected) {
productTable[selected]();
}
function showVegetable() {}
function showFruit() {}
function showFlower() {}

Alternatively, you could also consolidate the three showSomething functions into a single show function with parameters; however, this still depends on the context of the code, which I won’t delve into here.

References