DEV Community

glocore
glocore

Posted on

3 1 1 1 1

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!

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

👋 Kindness is contagious

Engage with a sea of insights in this enlightening article, highly esteemed within the encouraging DEV Community. Programmers of every skill level are invited to participate and enrich our shared knowledge.

A simple "thank you" can uplift someone's spirits. Express your appreciation in the comments section!

On DEV, sharing knowledge smooths our journey and strengthens our community bonds. Found this useful? A brief thank you to the author can mean a lot.

Okay