Recently, Daniel Westheide wrote an interesting post about the abuse of the
You can find it here.
I couldn’t agree more with Daniel.
This short story is another example that demonstrates how using
Option is not always
the best option (pun intended).
I’m developing an advertising service for a customer using Scala.
A simplified version of the
Ad data structure is the following:
1 2 3 4 5
At some point they told me we need to support, by adding the
two types of ad: standard and expanded.
They said: “If
description2 are used, it is a standard ad.
description1 are used it is an expanded one.
Users won’t include
headline2 when the ad is intended to be standard, and won’t include
when the ad is intended to be expanded.”
The optionality of the
description2 fields could put you in the wrong direction.
Indeed, you could think of changing the data structure as follows:
1 2 3 4 5 6
This may sound fine but you could reach a much cleaner and type-safe solution using a simple Algebraic Data Type (ADT). Here’s how:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
This way you don’t need to inspect the
to find out the ad type you’re dealing with.
Indeed, the ad type is encoded in the type system which is always a desiderata.
Bottom line: use
Option with caution.