DEV Community

glocore
glocore

Posted on

Tip: Create Functions to Improve Code Readability

Functions are a great way to make a chunk of code reusable. But even if you'll only ever do something once in your program, it may be a good idea to wrap it in a function to indicate what it does. This makes it easier for the reader to understand what's going on without having to read the complete implementation.

In the example below, the complex ternaries are only going to be used to create finalBaseUrl and finalPath, but it's hard to understand what's going on without actually reading the implementation.

const finalBaseUrl =
  this.baseUrl.slice(-1) === "/"
    ? this.baseUrl.slice(0, this.baseUrl.length - 1)
    : this.baseUrl;

const finalPath = path.slice(0, 1) === "/" ? path.slice(1, path.length) : path;
Enter fullscreen mode Exit fullscreen mode

Instead, if we create functions with appropriate names to encapsulate the complex ternary logic, a reader can skip reading the implementation.

const dropTrailingSlash = (string) =>
  string.slice(-1) === "/" ? string.slice(0, string.length - 1) : string;

const dropLeadingSlash = (string) =>
  string.slice(0, 1) === "/" ? string.slice(1, string.length) : string;

const finalBaseUrl = dropTrailingSlash(this.baseUrl);
const finalPath = dropLeadingSlash(path);
Enter fullscreen mode Exit fullscreen mode

Although we end up with more lines of code, it's much easier to scan and understand what's going on. You may instead choose to write a comment explaining your code, but such comments often tend to go out of sync as your code changes.

If you work with React, you can apply the same for hooks. Rather than having a large chunk of code in a useEffect hook, you can break it down into multiple effects and assign it relevant names to indicate what they do.


Thanks for reading!

Top comments (0)