So you just joined a new company, you're excited to learn the newest technology and work on some super cool new projects and then BAM, you have to first learn and navigate the legacy system.
All of a sudden the excitement drains from your body as you're navigating helper file after helper file, unable to make heads or tails of the code base.
In this post I will go over 5 VERY common code smells and how to fix them. If you think something is missing, please check out my previous post, 5 easy wins to refactor even the ugliest code.
Generally speaking your code will be a lot easier to read if each statement has its own line. The exception to the rule is to combine the else (or else/if) with the ending of the previous if. However, if you are writing a new if statement, it’s important to put it on a new line. This will prevent any future errors, as it may not be obvious that the two if statements are not logically connected.
pssst I tweet about code stuff all the time. If you have questions about how to level up your dev skills give me a follow @mlevkov
A dead store is when you assign a value to a variable but is then re-assigned without actually using the original value. Calculating or setting a value, without actually using it is at best a waste of resources, and at worst a bug in our code. For the following examples, let's assume we have an array of music tracks and we want to calculate the total runtime of all the songs.
A little added bonus in the following example, is the use of the reduce function to get our value.
One thing to keep in mind as you are developing, is that you are coding for humans, and not for the compilers. It’s better to keep things as simple and as humanly readable as possible. It’s way too complicated to read when you invert the result of a boolean expression, just use the opposite comparison instead.
When concatenating strings you should always stick to string templates instead of the concatenation operator. This will make your life much easier as it allows for multiline strings, reduces any errors if your strings have quotes and is generally a lot easier to read. Here is how it would look like when we try to create a TypeORM connection string without string templates and with.
There you have it, 5 more easy tips that you can apply to almost any codebase.
If you want to level up your coding skills, I'm putting together a playbook that includes:
30+ common code smells & how to fix them
15+ design pattern practices & how to apply them
20+ common JS bugs & how to prevent them