Re: readability, that's something to think about, but when I write code like
this:
if ((typeof num != "number") ||
(Math.floor(num) != num) ||
isNaN(num) ||
(num < 0) ||
Math.abs(num) == Infinity) {
throw new Error("This need to be a non-negative whole number");
}
Well, it adds up. :) Even now I can replace the fifth condition with
!Number.isFinite(num).
Actually, I've always wondered if validating and throwing early because an
argument doesn't meet a constraint might be a hint to the underlying JS engine
that it could convert the argument to a stricter type after the validation for
performance. (No floating-point number can get past that throw; it'd have to
be an unsigned integer.) But I'm betting the perf gain might not be all that
great. If it were, that might justify the readability issue.
Would splitting into two functions help, if the first were arg validation only?
(I hope it wouldn't help... but if it did, I'd do it.)
Re: Assert.jsm: Too bad it's not available in release builds. Also, isn't it
generally accepted that asserts are for test and debug code only? Argument
validation isn't a debugging-only problem.
A couple other notes:
* XPConnect obviously does some type coercion, but that's a pretty big hammer,
as Brendan used to put it.
* None of these solutions does anything for workers, particularly since workers
can't load JSM's.
On Thursday, May 15, 2014 2:38:21 AM UTC-7, Mike de Boer wrote:
> I quite recently wrote Assert.jsm
> (http://dxr.mozilla.org/mozilla-central/source/testing/modules/Assert.jsm),
> which you can include like this:
> Components.utils.import("resource://testing-common/Assert.jsm");
> On 15 May 2014, at 11:17, David Rajchenbach-Teller <[email protected]>
> wrote:
> > I remember opening a bug for this ~2.5 years ago. The answer was that
> > most of these assertions are so trivial to write that putting them in a
> > module would actually make reading the code harder than simpler. I don't
> > think the situation has changed since then.
_______________________________________________
dev-platform mailing list
[email protected]
https://lists.mozilla.org/listinfo/dev-platform