Software development is an evolving craft, and writing clean, readable, and maintainable code is a crucial aspect of being a proficient developer. This guide draws inspiration from Robert C. Martin's Clean Code principles and focuses on adapting them for JavaScript. It's not a strict style guide but rather a set of guidelines to produce code that is not only functional but also easy to understand and maintain.
The principles outlined in this guide are not mandates; they are distilled from years of collective experience by the authors of Clean Code. While not every principle must be strictly followed, they provide a touchstone to assess the quality of JavaScript code. In an industry where our understanding is still evolving, these guidelines serve as a foundation for writing code that stands the test of time.
The field of software engineering is relatively young, just over 50 years old. As we continue to learn and evolve, these guidelines act as a compass to navigate the complexities of code. Unlike other disciplines like architecture, which has centuries of established principles, software engineering is still in its formative years. Embracing these guidelines helps shape code into a refined form, acknowledging that every piece of code starts as a draft and matures through iterative refinement.
In the quest for brevity, developers might be tempted to use cryptic variable names. However, clarity should not be sacrificed for conciseness. For instance:
Bad code Example:
const yyyymmdstr = moment().format("YYYY/MM/DD");
Good code Example:
const currentDate = moment().format("YYYY/MM/DD");
Consistency in naming conventions enhances code readability and comprehension. It simplifies understanding, as demonstrated below:
Bad code Example:
getUserInfo();
getClientData();
getCustomerRecord();
Good code Example:
getUser();
Given that developers read more code than they write, making code searchable is paramount. Meaningful variable names aid in understanding, and tools like buddy.js and ESLint can help identify unnamed constants:
Bad code Example:
setTimeout(blastOff, 86400000);
Good code Example:
const MILLISECONDS_PER_DAY = 60 * 60 * 24 * 1000; //86400000;
setTimeout(blastOff, MILLISECONDS_PER_DAY);
Clear and descriptive variable names enhance code readability and comprehension. This helps in understanding the purpose of the variables without delving into the details of their implementation.
Bad code Example:
const address = "One Infinite Loop, Cupertino 95014";
const cityZipCodeRegex = /^[^,\\]+[,\\\s]+(.+?)\s*(\d{5})?$/;
saveCityZipCode(
address.match(cityZipCodeRegex)[1],
address.match(cityZipCodeRegex)[2]
);
Good code Example:
const address = "One Infinite Loop, Cupertino 95014";
const cityZipCodeRegex = /^[^,\\]+[,\\\s]+(.+?)\s*(\d{5})?$/;
const [_, city, zipCode] = address.match(cityZipCodeRegex) || [];
saveCityZipCode(city, zipCode);
By introducing explanatory variables (`city` and `zipCode`), the code becomes more self-documenting, making it easier for others to understand the intent.
Code should be explicit and not require developers to mentally map variables to their meanings. In other words, make the code speak for itself. Consider the following:
Bad code Example:
const locations = ["Austin", "New York", "San Francisco"];
locations.forEach(l => {
doStuff();
doSomeOtherStuff();
// ...
// ...
// ...
// Wait, what is `l` for again?
dispatch(l);
});
Good code Example:
const locations = ["Austin", "New York", "San Francisco"];
locations.forEach(location => {
doStuff();
doSomeOtherStuff();
// ...
// ...
// ...
dispatch(location);
});
By using a more explicit variable name (`location`), the code eliminates the need for mental mapping, making it easier to understand at a glance.
Avoid redundant information in variable names, especially when the context is already clear from the surrounding code. This principle prevents unnecessary verbosity and redundancy:
Bad code Example:
const Car = {
carMake: "Honda",
carModel: "Accord",
carColor: "Blue"
};
function paintCar(car, color) {
car.carColor = color;
}
Good code Example:
const Car = {
make: "Honda",
model: "Accord",
color: "Blue"
};
function paintCar(car, color) {
car.color = color;
}
In the good example, the variable names are concise, providing information without repeating what is already evident from the context.
One way to improve the clarity and conciseness of your JavaScript functions is by leveraging default parameters. This approach is often preferable to short circuiting or using conditionals to assign default values. However, it's essential to be aware of the limitations of default parameters.
Bad code Example:
function createMicrobrewery(name) {
const breweryName = name || "Hipster Brew Co.";
// ...
}
Good code Example:
function createMicrobrewery(name = "Hipster Brew Co.") {
// ...
}
The good example showcases the use of default parameters, making the code more succinct and eliminating the need for a conditional assignment. The function now provides a default value for the `name` parameter without resorting to short circuiting.
It's crucial to note that default parameters replace only `undefined` values. Other "falsy" values such as `''`, `""`, `false`, `null`, `0`, and `NaN` will not be replaced by the default value. This behaviour ensures that default values are assigned only when the parameter is explicitly `undefined`.
By embracing default parameters, you not only enhance the readability of your functions but also reduce the need for additional conditional checks, resulting in cleaner and more maintainable code. This practice aligns with the broader goal of producing clean, readable, and maintainable JavaScript code, as advocated by software engineering principles like those found in Robert C. Martin's Clean Code.
By incorporating these principles into your coding practices, you contribute to creating code that is not only functional but also maintainable and easily understandable by your peers. Clean code is an ongoing effort, and adherence to these guidelines will result in a more enjoyable and collaborative development experience.
So, focus on improving the code, not just for yourself but for the entire development team.