Software Engineering
dynamic-typing static-typing
Updated Fri, 17 Jun 2022 04:53:59 GMT

Is an Optional/Maybe type useful in dynamic languages?

Optional is useful in an obvious way in a statically typed language, but I'm wondering if it's also useful in dynamic languages. Usually there's no compiler telling you, "hey, you used this Optional<String> as a String", so you still have to discover your mistakes at runtime. I have a static typing background and from my perspective I can't see the benefit of an Optional type in a dynamic language.


That weakness is really no different than for all types in dynamic languages. You have to run it to find out what's in it. Options aren't really different in that regard.

Options are more than just a static annotation that a value may or may not be present. They have operations associated with them as well. Chains of mapped operations on options are one highly useful feature, that keeps you from having to check for failure after every step in the chain.

Even if you only immediately retrieved the value, it still would prod the programmer to check for Nothing the first time it ran and failed. Without an option, that prodding would only take place if it happened to contain null the first time you ran it. Many a null pointer dereference have stubbornly waited until the product was in the field.