Skip to Content
97 Things Every Java Programmer Should Know
book

97 Things Every Java Programmer Should Know

by Kevlin Henney, Trisha Gee
May 2020
Beginner
267 pages
7h 37m
English
O'Reilly Media, Inc.
Content preview from 97 Things Every Java Programmer Should Know

Chapter 71. Refactor Boolean Values to Enumerations

Peter Hilton

You wouldn’t use “magic numbers” in your code, so don’t use magic Booleans either! Boolean literals are worse than hardcoded numbers: a 42 in the code might look familiar, but false could be anything, and anything could be false.

When two variables are both true, you don’t know whether that’s a coincidence or whether they’re both “true” for the same reason and should change together. This makes the code harder to read, and causes bugs when you read it wrong. As with magic numbers, you should refactor to named constants.

Refactoring 42 to an ASCII_ASTERISK or EVERYTHING constant improves code readability, and so does refactoring true to a Boolean constant called AVAILABLE in a Product class, for example. However, you probably shouldn’t have any Boolean fields in your domain model: some Boolean values aren’t really Boolean.

Suppose your Product entity has a Boolean available field, to indicate whether the product is currently being sold. This isn’t really a Boolean: it’s an optional “available” value, which isn’t the same thing because “not available” really means something else, like “out of stock.”

When a type has two possible values, that’s a coincidence, and can change—by adding a “discontinued” option, for example. The existing Boolean field cannot accommodate the additional value.

Beware: using null to mean something ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

97 Things Every Programmer Should Know

97 Things Every Programmer Should Know

Kevlin Henney
Java Coding Problems

Java Coding Problems

Anghel Leonard
The Well-Grounded Java Developer, Second Edition

The Well-Grounded Java Developer, Second Edition

Benjamin Evans, Martijn Verburg, Jason Clark

Publisher Resources

ISBN: 9781491952689Errata Page