Domanda

I like the idea of Optional in Java which we can use to say that the object may or may not be available.

I am now learning JavaScript and when trying to find an equivalent, came only across optional-js. No other major frameworks seem to be implementing that.

This caused me to wonder, is such a usage not needed in JavaScript? Is there an alternative in JavaScript for that? Is it not the JavaScript way of doing things?

È stato utile?

Soluzione

Since it took Java a decade to go from having everything necessary to cleanly support it (i.e. since Java 5) to adding it; C# still hasn't added it to the standard library though it's been able to for about as long; and the idea has been in common use in (statically typed) functional languages since, at least, the '70s, I would actually say JavaScript is more representative of the trend.

Indeed, dynamically typed languages tend to be worse about this. The concept is certainly useful in dynamically typed languages, and is easy to implement, but few have it in the "standard" libraries. One of the reasons is that some of the benefits are lost in a dynamically typed language. In a statically typed language, use of an Optional type will force me to handle the "nothing" case, not so in a dynamically typed language.

Another aspect that's a double whammy is the relative commonness of the notion of "truthy" values. On the one hand, it makes it significantly easier to silently get the wrong behavior when using something like Optional. On the other hand, certain patterns that Optional can handle nicely can be accomplished by using truthiness, e.g. the ubiquitous

var x = passedInValue || defaultValue;

Still, it's not hard to imagine how the above could go wrong. "What if passedInValue is 0 or false? Or what if I want it to be null? How do I communicate the difference between not providing a value and explicitly providing a null value?" Similar issues happen when using a function: "How do I tell the difference between a look up failing and a look up successfully returning null?" Arguably, in JavaScript, undefined could (seemingly) serve some of these roles, but it's a "solution" that's worse than the disease and also not a solution.

The situation is very much like null in most languages or NULL in SQL. Truthiness amplifies the problems of null. It may come as no surprise at this point that most statically typed functional languages lack an equivalent to null. For some reason, after decades of existence, I'm not aware of any statically typed functional language that decided to add something like null after the creation of the language.

So, indeed, the answer is it's not the "JavaScript way" of doing things, but JavaScript was never really a leader in doing things in good ways. Unfortunately, for this particular example, JavaScript is far from alone. Somehow I doubt that Optional wouldn't have been useful in Java a decade ago.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
scroll top