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
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;
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);
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.
R. Alex Anderson 🚀@ralex1993Tired: Putting React useEffect calls directly in your render function.
Wired: Putting all useEffect calls in custom hooks so they can be named.
Inspired: Putting useEffect calls in the render function, but assigning their undefined output to named variables.
🙃20:03 PM - 09 Jun 2021
Thanks for reading!
Top comments (0)