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.
Using a boolean parameter often means your function does two different things, breaking the Single Responsibility Principle (SRP). Here's a typical example:
This might look simple, but it has several problems:
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
Split the function into two separate ones, each doing one thing:
This gives you:
Clear names: createTempFile("log.txt") tells you exactly what it does
Simple 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
This idea works in many situations. Here are some cases:
Boolean flags in function parameters often show that a function tries to do too much. Making separate, focused functions creates code that is:
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!
The above is the detailed content of Clean code: why boolean flags in function parameters are a code smell. For more information, please follow other related articles on the PHP Chinese website!