A Guard Clause Is Maybe a Tiny Parser - The Code Whisperer

Your Barcode type effectively reimplements a small part of Maybe using the “OO way” to design Sum/Union types. Your switch statement reimplements Maybe.map() (the Valid branch) and Maybe.withDefault() (the Empty branch). I’m reminded of the joke that every program eventually contains a partial and buggy implementation of Lisp. :slight_smile: Your code contains a partial (but not buggy!) implementation of Maybe.

I think some people intend that as an insult, but I don’t. Your code sample here seems clear to me, and already moving in the direction of Maybe, so it wouldn’t be difficult at all to apply the refactoring of renaming Barcode to Maybe and then renaming ValidBarcode to Barcode. Then parse() would return Maybe<Barcode> and the switch statement would be transformed into Barcode.parse(text).map(handleValidBarcode).orElse(() -> println("Barcode is empty")).

The only complication in Java (and specifically the Vavr library) is that map() wants a function and not a consumer (void function), but there are at least two ways to handle that problem.

Meantime, I really like the clarity of the pattern matching while we wait for a signal that we need heavier FP machinery.

Very nice!

1 Like