Adding a boolean parameter to a function can be considered an anti-pattern in several cases, especially when it introduces ambiguity, decreases readability, or leads to complicated branching logic inside the function. Here are some situations where it might be considered an anti-pattern:
Control coupling: If a boolean parameter is being used to control the behavior of the function, it introduces a form of coupling known as control coupling. This means the caller is dictating the internal logic or control flow of the function. This can make the function harder to understand and maintain.
Ambiguity: When reading a function call with a boolean argument, it might not be immediately clear what the argument represents without looking at the function signature or implementation. For example,
processData(true)
isn't as clear asprocessData(ProcessMode.SAFE)
or even two distinct methods likeprocessDataSafely()
andprocessDataUnsafe()
.Code complexity: If a boolean argument leads to two largely different behaviors inside the function (like an if-else block that splits the function into two halves), it would be clearer and more maintainable to create two separate functions.
Violation of Single Responsibility Principle: If a boolean argument is used to make the function do entirely different things, then it violates the Single Responsibility Principle (SRP), which states that a function should do only one thing.
Boolean trap: A situation when a programmer doesn't remember the order or meaning of a series of boolean flags, thus producing bugs.
Scalability: If the need arises to support a third or fourth behavior, you'd have to add more boolean arguments or change the boolean to something else, which would require changing all the callers.
In many cases, alternatives like different methods, enums, or command pattern can provide a more readable and maintainable design.