Yonatan Karp-Rudin
Yonatan Karp-Rudin

Follow

Yonatan Karp-Rudin

Follow
Kotlin Code Smell 006 - Boolean Variables

Photo by Alimohamad Faridi on Unsplash

Kotlin Code Smell 006 - Boolean Variables

Yonatan Karp-Rudin's photo
Yonatan Karp-Rudin
·Dec 6, 2022·

1 min read

Play this article

Table of contents

  • Problems
  • Solutions
  • Examples
  • Exceptions
  • Sample Code
  • Conclusion
  • More Info
  • Credits

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

Credits

 
Share this