DEV Community

Discussion on: The Importance of Clean Code in Your Startup's Success

Collapse
 
joelbonetr profile image
JoelBonetR πŸ₯‡ • Edited
The third tip is to use comments to explain your code. Comments are important for making your code readable and understandable. They should be used sparingly, however, as too many comments can make your code hard to read. Use comments to explain why you’re doing something, not what you’re doing

I feel in need to correct those words.
Comments for "explaining why you're doing something" is what you asked to provide at college.
IRL any other dev will understand why you did something and if not, there's a place for that: the wiki. Be that a project wiki, comments in your favourite issues tracker or whatever system you got.

Comments in code should appear at the top of each function/method and the reason is that your IDE will catch that and provide this information in different contexts where that function/method is used just by hovering the mouse over it's name.
You need to define what this function is doing, how many params it receives, of which type and what it returns clearly.
Quick example:

/**
 * Retrieves a user from the DB based on it's email
 * @param {string} email
 * @returns {User|null}
 */
const getUserByEmail = (email) => {
  return Users.find({ where: { email: email } });
}
Enter fullscreen mode Exit fullscreen mode

Note that the function can return either a User Object or null, this is important to know when calling this function and without this documentation in code it may be hard for others to spot that or they'll need to dig deep into that hypothetical ORM or try it by hand. Either way it's time lost.

You can also use TS in this case which will solve this types thingy automatically, still enforcing the documentation of your code in the CI or in the Linter will help for sure on those more complex logic paths and to keep a clean code with the same style.

See this example in JS:

/**
 * Clamps a `value` between a `min` and `max` inclusive
 *
 * @param {Number} value The value to clamp between `min` and `max`
 * @param {Number} min The minimum number of the range
 * @param {Number} max The maximum number of the range
 *
 * @returns {Number} The clamped value
 */
export function clamp(value, min, max) {
  return Math.min(Math.max(min, value), max);
}
Enter fullscreen mode Exit fullscreen mode

And in TS:

/**
 * Clamps a `value` between a `min` and `max` inclusive
 *
 * @param value The value to clamp between `min` and `max`
 * @param min The minimum number of the range
 * @param max The maximum number of the range
 *
 * @returns The clamped value
 */
export function clamp(value: number, min: number, max: number) {
  return Math.min(Math.max(min, value), max);
}
Enter fullscreen mode Exit fullscreen mode

So it can be extrapolated to any other language (static typed or not).

Best regards