Boolean flags in function parameters can make your code harder to read and maintain. Let's see why you should avoid them and what you can do instead.
The problem with boolean flags
Using a boolean parameter often means your function does two different things, breaking the Single Responsibility Principle (SRP). Here's a typical example:
function createFile(name, isTemp) {
if (isTemp) {
fs.create(`./temp/${name}`);
} else {
fs.create(name);
}
}
This might look simple, but it has several problems:
- Unclear function calls: Reading the code, it's hard to know what the boolean means:
createFile("log.txt", true); // What does 'true' mean here?
Two functions in one: The boolean works like a switch, making the function do different things
Testing gets harder: You need to check both ways the function can work
Hard to add features: If you need a third option later, you might add another boolean, making things worse
A better way to write it
Split the function into two separate ones, each doing one thing:
function createFile(name) {
fs.create(name);
}
function createTempFile(name) {
createFile(`./temp/${name}`);
}
This gives you:
Clear names:
createTempFile("log.txt")
tells you exactly what it doesSimple logic: Each function does just one thing
Easy testing: You only need to test one thing per function
Simple to add features: Need something new? Add a new function without changing the old ones
More examples
This idea works in many situations. Here are some cases:
Login system
// ❌ Bad
function authenticate(user, isAdmin) {
if (isAdmin) {
// Admin login logic
} else {
// Regular user login logic
}
}
// ✅ Good
function authenticateUser(user) {
// Regular user login logic
}
function authenticateAdmin(user) {
// Admin login logic
}
Email system
// ❌ Bad
function sendEmail(user, isHtmlFormat) {
if (isHtmlFormat) {
// Send HTML email
} else {
// Send plain text email
}
}
// ✅ Good
function sendPlainTextEmail(user) {
// Send plain text email
}
function sendHtmlEmail(user) {
// Send HTML email
}
To sum up
Boolean flags in function parameters often show that a function tries to do too much. Making separate, focused functions creates code that is:
- Easy to read
- Easy to test
- Easy to fix
- Easy to change
Next time you want to add a boolean parameter, think about making two functions instead.
Have you tried splitting functions like this in your code? Did it help? Let me know in the comments!
Top comments (0)