Cleaner Code Example

Writing cleaner and more readable code

It is a known fact that code is read more times than it is written.

For that reason, you would want your code to be easy to read and understand, as much as you would want it to work well.

Whether if you are the sole engineer working on the project or you are a part of a big team, at one point someone from your team or even yourself in a few weeks or months would come read the code and try to understand what it is doing or why it was written the way it was.

So, how do we make sure our code is easy to understand?

There are no magic solutions, but we can start with the following suggestions:

  1. Write short functions.
    (As a rule of thumb, your function should fit in one screen.)
  2. Give your functions and variables meaningful names.
  3. Prefer code over comments.
    (Whenever you have a comment on a line of code, try to extract this code to function and let the function name explain instead of the comment. This way there’s a higher chance it will be maintained.)
  4. Minimize the number of exit points from your function.
    (Don’t have multiple return statements in your functions. Save the return value in a variable and have a single return at the end of the function. An exception to that would be to exit on a specific case on the first line of your function.)
  5. Try not to repeat yourself.
    (Whenever you have code that is similar to a code you already have in the project, extract it to a function and use the same code.)

Here is an example I ran into a short while ago in a project I worked on and decided to fix for everyone’s profit.

We started with the following code for a function that blocks the user from entering any character that is not a number by telling the browser to prevent the keyDown JavaScript event.

Note: the following code is written in TypeScript and React, but the methods in this post can be used for any programing language.

export const allowOnlyNumber = (
  e: React.KeyboardEvent,
  allowCopyPaste: boolean = false
): void => {
  const copyPasteKeys = [65, 67, 86, 88]; // 65 A, 67 C, 86 V,88 X
  if (allowCopyPaste && e.ctrlKey && copyPasteKeys.includes(e.which)) {
    return;
  }
  if (e.which === 9 || e.which === 13) {
    return;
  }
  if (
    e.shiftKey ||
    e.altKey ||
    !(
      e.which === 8 ||
      e.which === 46 ||
      (e.which >= 48 && e.which <= 57) ||
      (e.which >= 96 && e.which <= 105)
    )
  ) {
    e.preventDefault();
    e.stopPropagation();
  }
};

As you can see, this function has all of the issues described above.

If we take it and apply all of my suggestions we can end up with a code that is much cleaner, and much easier to understand to anyone that might stumble upon this code in the future.

Here is the end result:

export const allowOnlyNumber = (
  e: React.KeyboardEvent,
  allowCopyPaste: boolean = false
): void => {
  if (
    !isPasteEvent(e, allowCopyPaste) &&
    !isValidKey(e)
  ) {
    e.preventDefault();
    e.stopPropagation();
  }
};

Wait, that is all?!

Oh well, the rest of the code was extracted to the following functions:

const isPasteEvent = (
  e: React.KeyboardEvent,
  allowCopyPaste: boolean = false
): boolean => {
  const copyPasteKeys = [65, 67, 86, 88]; // 65 A, 67 C, 86 V,88 X
  return (
    allowCopyPaste &&
    (e.ctrlKey || e.metaKey) &&
    copyPasteKeys.includes(e.which)
  );
};

const isTabOrEnter = (e: React.KeyboardEvent): boolean => {
  return e.which === 9 || e.which === 13;
};

const isArrowKey = (e: React.KeyboardEvent): boolean => {
  return e.which >= 37 && e.which <= 40;
};

const isHomeOrEnd = (e: React.KeyboardEvent): boolean => {
  return e.which === 35 || e.which === 36;
};

const isShiftOrAltPressed = (e: React.KeyboardEvent): boolean => {
  return e.shiftKey || e.altKey;
};

const isBackspaceOrDelete = (e: React.KeyboardEvent): boolean => {
  return e.which === 8 || e.which === 46;
};

const isNumberKey = (e: React.KeyboardEvent): boolean => {
  return (e.which >= 48 && e.which <= 57) || (e.which >= 96 && e.which <= 105);
};

const isValidKey = (e: React.KeyboardEvent): boolean => {
  return (
    isTabOrEnter(e) ||
    isArrowKey(e) ||
    isHomeOrEnd(e) ||
    (!isShiftOrAltPressed(e) && (isBackspaceOrDelete(e) || isNumberKey(e)))
  );
};

Even though the code as a whole is a little longer, it is broken down into smaller functions that are much easier to digest. And if it bothers you that there is more code, keep in mind that almost any JavaScript project nowadays is going through a transpiler & minifier that will make sure this code is converted to something much smaller.

I hope this post helped you learn how to improve your code, and that the code you will write in the future will be much easier to read and understand.

I would love to hear your thoughts in the comments.

Thank you, and see you next time!

Leave a Reply

Your email address will not be published. Required fields are marked *