Guards

Peter Michaux petermichaux at gmail.com
Thu May 26 21:36:12 PDT 2011


From: Waldemar <waldemar at google.com>
Date: Thu, May 26, 2011 at 4:22 PM
Subject: May 24-26 rough meeting notes
>
> Guard Syntax:
> Technical aspects ok, but some are worried about the effects of this
> change on the ECMAScript style.

What aspects of ECMAScript style were cause for concern? Fear of Java?


> Cormac's student Tim will work with
> DaveH to prototype this this summer. Not advanced to Harmony, pending
> more user experience.

How will more user experience be generated? Through a compiler to ES5?

--

The idea of guards in general seems extremely useful and could
potentially save reams and reams of parameter checks that have been
manually written in a large-ish project (>20,000 lines) over a
long-ish time period (>2yrs) I'm working on with multiple people. The
project is large enough and long enough that I forget parts of the
code. I used to think "just don't send the wrong type of argument to a
function" but now that I'm forgetting the code myself and reviewing
the code of others daily, I see the large benefit of having the code
complain with a clear message when the wrong parameter is sent.

I'm looking at the strawman for guards.

http://wiki.ecmascript.org/doku.php?id=strawman:guards

I don't quite see how they are created.

I understand this part about how they would be used

  function f(p :: String, q :: MyType) :: Boolean { ... }

but there is no specific example of how MyType is defined. Is that
related to classes at all? I'm hoping it is not related to classes and
that it is more akin to some kind of interface definition. Suppose I
wanted MyType to be only positive even integers. Perhaps MyType is a
can only be a function that takes a single argument that is a string
and returns an integer. Perhaps MyType has to be an object with two
function properties named alpha and beta.

What about maybe types? Could MyType be defined so that null is not an
allowed value? All the manually written not-null parameter checks in
Java are an unfortunate result of its type checking system.

Would there be a way to check that too many arguments have been sent
to a function?

--

One use case I could see would be using guards in development and then
having the minifier strip the guards for production. Then the guard
definitions could be stripped as well. I've written the following kind
of thing with the intention of stripping code inside the debug block
for production.

var double = function (a) {
    /* DEBUG BEGIN */
    if (typeof a !== 'number') {
        throw new Error('a must be a number');
    }
    /* DEBUG END */
    return 2*a;
};

Peter


More information about the es-discuss mailing list