Should you ever have a `.none` case in an enum?

Sure. Besides the reason you've already listed:

  1. As a reader of code, I feel that there's a subtle semantic distinction between Optional<T> and T with a .none case:

    • T.none: a meaningful element within the domain of T; intentionally present
    • Optional<T>.none: outside of the domain of T; not immediately clear why Optional<T> value can be missing (accidental? intentional? the result of bad data? etc.) — Optional can be pretty overloaded in its meaning

    T.none gives me confidence as a reader that it's a special and intentional value

  2. Keeping these values within the domain of your type also helps keep your code more intentional on the type. e.g., you can write extensions on T instead of Optional<T>, hold collections of T as opposed to Optional<T>, etc. Potential for less noise, depending on the specifics of how it's used

From the examples you give, I'd say that I'd prefer Subgroup have a .none case than defer to Optional for it.

26 Likes