Clean Code Principles in Frontend Development with JavaScript: Building Quality Code

Foto del autor

By Caue Sampaio, Martin Luna and Breno Freire

April 12, 2024

This article delves into the application of Clean Code principles in JavaScript development and their role in facilitating the creation of high-quality software products. Clean code represents a strategic approach to programming that prioritizes code readability, following industry best practices, and utilization of established design patterns. So let’s get started!

Clean Code Principles

Clean Code is based on clear guidelines and best practices aimed at making code more readable, efficient, and easy to maintain. To apply these principles in frontend development with JavaScript, it is crucial to:

  1. Name variables, functions, and classes descriptively and meaningfully.
  2. Keep functions short and focused on performing a single task.
  3. Avoid code repetitions and duplications through reuse and abstraction.
  4. Follow a consistent formatting style to facilitate code readability for other developers.
  5. Comment the code only when necessary and prioritize clarity within the code itself.

Naming variables, function and classes

When thinking about clean code naming, there’s one thing which we definitely want to wipe clean: doubts! In order to achieve that, our goal is to always try to write a code that’s self-explanatory. The names must describe what that variable is, what that function does or what that class represents. Let’s give it a look:

For this small block of code you can understand the logic, but when things start growing, it gets harder and harder to maintain the code quality, since it’s almost impossible to understand what that code block does. How can we make it easier for others to understand our code? Let’s try again, writing our code as humanly readable as possible.

If it wasn’t for the console message text, you probably wouldn’t know what the first code was responsible for. The second version may look longer, but it’s definitely way more self-explanatory than the previous one. This is extremely important for code maintainability as the code base grows.

Keep your functions short

Writing a cleaner code is very closely related to specificity, from naming code elements, organizing them and, of course, their functions.  After all, it’s easier to organize, maintain and name things when we’re very clear on what they do. If you’ve ever come across the SOLID principles, this is the “S” which means “Single Responsibility Principle”, but how small should my function responsibility be? Well, for Robert “Uncle Bob” Martin, you should extract as much as you can! In the end, you’ll have a semantic tree that you can follow by name. Let’s give it a look:

It looks like our function is a really short one, but a new feature is requested and now we need to validate if the email is in the right text pattern and if the “name” or the “email” are null. Let’s check the code:

As you can see, a little change in our rules turned our addUser function into a spaghetti code block. The addUser is not responsible for creating the user anymore, it validates and creates the user. This opens up the question: should we change the function name to validateAndMaybeCreateUser? Well, maybe not. Let’s try to apply the Single Responsibility Principle and check if it helps us make that decision.

Now, any change in your user validation won’t affect addUser anymore! Each of the functions has their own purpose and can be named accordingly. It’ll be way easier to test these functions and give them maintenance.

Preventing code repetition and duplication

Self-repetition in software development can signal inefficiency and potential problems, such as the spread of business logic across the codebase. Good practices mentioned before like using clear, descriptive names for functions and variables, enhance code clarity and ease of reuse, but they’re not enough on their own. 

Patterns like the “Don’t Repeat Yourself” (DRY) principle combat repetition issues by promoting code reusability and abstraction, reducing risks tied to duplicated code. An example of this is that duplication creates multiple component instances, complicating future updates. Time pressures can exacerbate duplication, as developers may opt for shortcuts.

Strategies like the Singleton pattern, ensuring a single class instance, simplify code management and reduce redundancy. Also, composition as a design strategy promotes code reuse, modularity, and flexibility.

Formatting style

Here are three popular tools that can help maintain consistent code formatting and style in a frontend React project:

  1. ESLint

ESLint is a widely used tool for identifying and reporting patterns found in ECMAScript/JavaScript code. It can be configured to enforce specific coding styles, detect bugs, and ensure consistent code formatting. ESLint rules can be customized to match the specific requirements of your project.

  1. Prettier:

Prettier is an opinionated code formatter that enforces a consistent style by parsing your code and re-printing it with its own rules. It supports various programming languages, including JavaScript and JSX, making it a great choice for maintaining code consistency in React projects. Prettier can be easily integrated with most code editors and build tools.

  1. Editor config

EditorConfig: While not a tool like ESLint or Prettier, EditorConfig helps maintain consistent coding styles between different editors and IDEs. It allows you to define and maintain consistent coding styles across multiple editors and IDEs through a simple configuration file. EditorConfig can help ensure consistency in indentation styles, line endings, and encoding formats.

Do it for tomorrow

Sometimes, reading other people’s code is a hard experience. In the future, another programmer or even yourself will take a look at your project and will need help understanding it, or find it hard to read. It’s good to be recognized by your peers when you care about the code’s structure; they find it easy to read, and, most importantly, it works.

“Clean code always looks like it was written by someone who cares”

Michael Feathers

We need to find a balance between code readability and working functionality. You can find any comments like the following, where the code explains itself; you don’t need to add any comments.

If you need to add comments to your code, then it’s not self-explanatory, or uses bad variable names or other similar problems. Refactor your code or be consistent when naming variables or other code conventions.

A comment should explain the goal of our code.

“Don’t comment bad code—rewrite it.”

Brian W. Kernighan, The Elements of Programming Style

We should avoid using comments, but they are helpful when using third-party libraries, APIs, frameworks, etc., because we will find ourselves in situations when writing a comment will be more beneficial than leaving a complex solution or a hack without any explanation whatsoever.

Always remember that:

  • Our code should be self-explanatory.
  • Sometimes, it is necessary to add comments explaining “why” we use an approach instead of “what” or “how” the code works.

Adhering to Clean Code principles in frontend development with JavaScript is essential for building high-quality, maintainable code. By following guidelines such as naming variables, functions, and classes descriptively, keeping functions focused on a single task, preventing code repetitions through reuse and abstraction, and utilizing tools like ESLint and Prettier for maintaining consistent formatting styles, developers can enhance code readability and efficiency. Additionally, emphasizing the importance of clear comments for better code documentation and understanding among team members is crucial in creating a codebase that is not only functional but also easily maintainable and scalable in the long run.

Any questions? Reach out to us at hello@arionkoder.com!