JavaScript refactoring best practices.
Kelechi Kizito Ugwu
Posted on June 10, 2023
- Removing Code Duplication Code duplication is a prevalent issue that can lead to maintenance difficulties and increased bug risk. Let's consider an example where the same logic is repeated in multiple places:
In the above code, the constant PI
is duplicated in both functions. To refactor it, we can extract the duplicated logic into a separate function:
By utilizing the built-in Math.PI
constant, we eliminate code duplication and improve code clarity.
- Simplifying Conditional Logic Complex conditional statements can make code harder to read and maintain. Let's consider an example with nested if statements:
To simplify the conditional logic, we can use a switch statement:
By using a switch statement, we make the code more concise and easier to understand.
- Extracting Reusable Functions Extracting reusable functions from existing code can enhance code organization and promote code reuse. Let's consider an example where similar code is repeated within different functions:
To avoid duplication, we can extract the common calculation logic into a separate function:
By extracting the common calculation logic into the calculateArea
function, we improve code reuse and maintainability.
- Use descriptive naming By using descriptive naming, you make your code more understandable. An example is the following code:
Using decimal as a constant name brings about confusion.
By changing the naming in the code above to a more descriptive one enhances readability.
- Use camel casing Camel casing means that every naming starts with a lowercase word and every subsequent word’s first letter will be capitalized.
The above code is read as the rapist finder instead of therapist finder.
Camel casing aids easy identification of variables, function and types.
Posted on June 10, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.