Consistency in The Negative Result Values Through Expansion of null's Role

Brendan Eich brendan at mozilla.org
Thu Aug 16 14:47:30 PDT 2012


Andreas Rossberg wrote:
> On 16 August 2012 00:35, Rick Waldron<waldron.rick at gmail.com>  wrote:
>> On Wed, Aug 15, 2012 at 6:02 PM, Erik Reppen<erik.reppen at gmail.com>  wrote:
>>> This topic has probably been beaten to death years before I was even aware
>>> of es-discuss but it continues to get mentioned occasionally as a point of
>>> pain so I thought I'd see if I couldn't attempt to hatch a conversation and
>>> maybe understand the design concerns better than I likely do now.
>>>
>>>
>>> Consistent Type Return for Pass and Fail?
>>>
>>> The principle of consistent type-return has occasionally skewered me as
>>> somebody who came to non-amateur levels of understanding code primarily
>>> through JavaScript. I can see the value in maintaining consistent types for
>>> positive results but not so much for indicators that you didn't get anything
>>> useful. For instance:
>>>
>>> * [0,1].indexOf('wombat'); //returns an index on success or  -1 to
>>> indicate failure. -1 passed on to a lot of other array methods of course,
>>> indicates the last element. If you'd asked me the day I made that mistake I
>>> could have told you indexOf probably returns -1 on failure to find something
>>> but it didn't occur to me in the moment.
>> It would be far worse to have a different type of value as a return, right?
>
> Actually, no. It is far better to have something that produces failure
> as immediately and as reliably as possible when used improperly.
> Sentinel values are a prominent anti-pattern.

Spoken like a true ML'er :-P. Also, you mention failure and it's true 
that lack of try/catch in original-JS and ES1&2 meant APIs had to 
overload return values with out-of-band failure codes.

However, JS hackers do not write refutable match expressions cracking 
return value using typeof or better. *That* is the anti-pattern here.

-1 as an out-of-band (for non-negative indexes) return code is actually 
easier to test and works well with certain code patterns, compared to a 
differently typed code. JS is not alone here, tons of precedent even in 
other dynamic languages that do have try/catch and even matching.

The issue is "failure". Sometimes not finding the wanted character index 
is not failure but just a condition to test that leads to an alternative 
strategem. Then the conciseness and clarity of the test matters, and 
typeof rv != "number"is the wrong tool compared to rv < 0.

> However, I agree that there is no chance of fixing that for existing libraries.

That's another thing. Deviating from existing patterns for new APIs that 
have similar names and motivations is going to be a pain for some users. 
It's not obvious to me that we have a real "failure must be prompt" 
problem here that justifies breaking with convention.

/be


More information about the es-discuss mailing list