Play this article
Using boolean variables as flags exposes accidental implementation and pollute the code with Ifs.
TL;DR: Don't use boolean variables, they force you to write Ifs. Create polymorphic states instead.
Problems
Extensibility
Comparison in some languages
Solutions
- If Boolean maps to a real-world entity are safe. Otherwise, model as a State to favor Extensibility. This also follows the Open/Closed Principle.
Examples
- Flags
Exceptions
- Real-world true/false rules
Sample Code
wrong
fun processBatch(
useLogin: Boolean,
deleteEntries: Boolean,
beforeToday: Boolean
) {
...
}
Right
fun processBatch(
useLogin: LoginStrategy,
deleteEntries: DeletePolicy,
beforeToday: OffsetDateTime
) {
...
}
Conclusion
Take extra care when declaring something as a boolean. Flags are difficult to maintain and extend. Learn more about the domain. Try migrating to the state design pattern. Use polymorphism instead of ifs or when (pattern matching).
More Info
- FlagArgument by Martin Fowler
Credits
Â