by phpnode · 10y ago · 0 comments
Here's a Babel plugin which adds design by contract to JavaScript, squeezing it into existing JS syntax (the result is really similar to Eiffel) - https://github.com/codemix/babel-plugin-contracts
and here's what it looks like in a reasonably complicated program - https://github.com/codemix/malloc/blob/master/src/index.js
(disclosure: I wrote this)
Because it's yet another layer on top of other layers, because it has performance implications ... A few languages such as Vala support some form of contracts, this kind of feature is more useful when part of the language itself, not some third party babel plugin that leads to codebase fragmentation as one just had yet another layer to the compilation pipeline. No offense, that's a nice thing you wrote, I'm just not going to use this kind of thing and add more complexity for very little gain. To me tests ARE the contracts.
I would only be willing to pay the cost of transpilation with something like Typescript which adds a signification value. Babel and co ? not worthwhile.
Contracts are useful during development, they're typically stripped out in production builds, so there's no performance overhead there. If you find a bug in production, turn on your contracts and you'll quickly discover the source of the error. Contracts can validate the state of the world at runtime in a way that can never be covered by unit tests, unless your tests cover all possible inputs to your program. It doesn't mean you don't need unit tests too, they are yet another layer of safety.
I use this in combination with Flow, which means I have to transpile regardless, so the overhead is very low for me. Of course I'd like them to be part of the language proper, but for that to happen there needs to be developer demand first.
Because it's an ugly and slow run-time hack around a proper type system, but without most of the benefits of a real type-system. The compiler cannot optimize with the given types ("contracts"), it can only add run-time checks.
Check what a typed ruby can do, and how the syntax looks much more natural there.
E.g. in my typed perl (cperl) I optimize array accesses to omit out-of-bound checks when the compiler knows that the index is within the bounds. This is true for "shaped" arrays (typed arrays with a constant range), if the constant upper bound of a loop is within the shape, or if the loop just iterates over an array.
If the compiler knows that the given number to an unary op is only an integer, the optimized integer method can be used instead. If both arguments to a binary numeric op are integers, the optimized integer method can be used. ...
This thing can be used alongside Flow[0] and other babel plugins which use flow syntax.