Avoid boolean parameters
Written byPhuoc Nguyen
Created
13 May, 2021
Category
Practice
Tags
JavaScript
Let's consider a situation where we have a function that writes a string to a file. It allows user to append the content to file, or override the content via the
`override`
parameter:js
const writeToFile = (content: string, file: string, override: boolean) => {
...
};
With that signature, the function will be invoked as following
js
// Append the content to file
writeToFile(content, file, true);
// Override the file
writeToFile(content, file, false);
If you are not the one who creates the function, you have to question what the boolean value represents until looking at the implementation.
It is worse if the function has a lot of boolean flags. Using boolean flags makes the core harder to read and maintain.
There are a few ways to get rid of the issue.
#Provide explicit methods
js
appendToFile(content, file);
overrideFile(content, file);
#Use an object parameter
js
writeToFile(content, file, { override });
#Use an enum
If you're using TypeScript, then you can use
`enum`
to represent the possible values of a boolean flag.js
enum SaveMode {
Append,
Override,
}
writeToFile(content, file, mode: SaveMode);
It's confident for consumers to call the method:
js
writeToFile(content, file, SaveMode.Append);
// Or
writeToFile(content, file, SaveMode.Override);
#See also
Questions? 🙋
Do you have any questions about front-end development? If so, feel free to create a new issue on GitHub using the button below. I'm happy to help with any topic you'd like to learn more about, even beyond what's covered in this post.
While I have a long list of upcoming topics, I'm always eager to prioritize your questions and ideas for future content. Let's learn and grow together! Sharing knowledge is the best way to elevate ourselves 🥷.
Recent posts ⚡
Newsletter 🔔
If you're into front-end technologies and you want to see more of the content I'm creating, then you might want to consider subscribing to my newsletter.
By subscribing, you'll be the first to know about new articles, products, and exclusive promotions.
Don't worry, I won't spam you. And if you ever change your mind, you can unsubscribe at any time.
Phước Nguyễn