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!

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post