Functional Programming | Programming | ScalaWhen You Do Want NoneFebruary 25, 2015
In the applications I typically develop, I only care when strings are meaningful or when they aren’t because they are
Null depending on the language). Empty strings and strings containing only whitespace are this
weird, in-between third category I really would prefer not to deal with. When I go to McDonald’s, I want to focus on the
burgers and fries. I want absolutely nothing to do with the Filet-O-Fish.
Scala’s Option gives us a neat way to avoid meaningless strings if we wish.
I have blogged about
It helps us avoid null in an elegant, typesafe way at compile-time. The collection-like semantics of
Option helps us turn
Some(meaninglessString) into None
(not to be confused with Python’s None)
so we can deal with it as if it were an organic
It’s really pretty easy.
If you know Scala, you can see exactly what happens here. Check out that call to
filter. We typically associate it
with collections where
filter removes all elements from the collection that don’t pass the condition. Option offers an
filter that returns None if the value “inside” Some doesn’t pass the condition. In the case of an empty or
whitespace-only string, trimming it keeps it or makes it empty, so the
filter test doesn’t pass and yields None. This is a really
concise way of letting us deal with only two categories of strings--meaningful or not--instead of three. One place where
this could come in handy is backend form validation of mandatory fields in web applications.
If you have the luxury of not having to distinguish between empty-ish strings and null, keep this tip in mind. Unless you’re Sir Mix-A-Lot, you actually might want None.