2024-04-29 - Cameron Harder-Hutton
tl;dr: Booleans are just less flexible in the future.
Here's an example. You own a payment service. You're adding a feature to accept payments that include a promotional discount. You want to tag incoming requests with a flag to identify when to call the PromotionService and validate. Your first thought might be to add something like this:
"isPromotionPayment": "true"
Don't do this! In the future there could be many more features like it. You're missing an opportunity here to make your code more robust for the future. With 'payments' it might be easy to imagine other discounts in the future - with your feature there might not be, but do you really know?
A year later, along comes a requirement for 'student discounts'.
How do you identify these requests? Do you add isStudentDiscount
to your model?
You probably shouldn't. By now, however, all of your dependencies are calling you with the previous boolean.
Updating them will take time. Maybe too much time, that it's not palatable for the business.
Just use an enum from the start.
enum DiscountType {
PROMOTION = "PROMOTION",
STUDENT_DISCOUNT = "STUDENT_DISCOUNT",
}
Now you can add enum values forever and keep your clients backwards compatible.
A year later, the company wants to allow multiple discounts on a single purchase...
You can probably see where this is going:
"discounts": ["PROMOTION", "STUDENT_DISCOUNT"]
Here are some other nice benefits:
Your internal functions remain backwards compatible. Enums and enum lists are always friendly to an additional value being added.
Your function calls become more readable, e.g.
const result = processPayment(paymentInstrument, true);
// vs
const result = processPayment(paymentInstrument, DiscountType.PROMOTION);
// or
const result = processPayment(paymentInstrument, discounts);
Your tests become easier to debug, e.g.
expected [true] received [false]
vs
expected [Status.ENABLED] received [Status.DISABLED]
I did a bit of research when I went to write this, and found this article Don't use booleans by Steven Luu. I like his points, check it out.
Have any thoughts? Send me an email!