Marketing of D - article topic ideas?
Adam Ruppe
destructionator at gmail.com
Fri Jun 4 07:37:57 PDT 2010
On 6/4/10, Lutger <lutger.blijdestijn at gmail.com> wrote:
> I would be interested in contract programming.
When I write my thing up, I'll have something to say about contracts
too. My HTML DOM code (on which I own the copyright! --
http://arsdnet.net/dcode/dom.d ) was originally written as just a list
of functions, like I've done for a long time.
But, then, a null pointer got into tree somehow, and it annoyed the
hell out of me. To help track it down, I added the class invariant and
piles of in/out contracts. There's almost more assert lines than
actual code! Take a look at this function:
Element appendChild(Element e)
in {
assert(e !is null);
assert(e.parentNode is null);
assert(!selfClosed);
}
out (ret) {
assert(e.parentNode is this);
assert(e is ret);
}
body {
e.parentNode = this;
children ~= e;
return e;
}
Lots of those are pretty obvious, and it is a trivial function, so it
isn't hard to eyeball it, but putting this stuff in those contracts
make it explicit as to what is expected: it takes ownership a node
without a parent and returns it.
But now, if I edit this function, or subclass it and screw something
up, it is caught very quickly, and right on location. This experience
has made me understand the people asking for non-null types, but it
has more benefit aside from that too.
For example, yesterday, I wrote this:
auto e = document.createElement("div");
auto list = document.createElement("ul");
// snip
e.appendChild(e); // BUG, should be appending the list
The compiler didn't catch this one, and I wrote this long after
forgetting about the dom implementation code. But the in contract
caught this as soon as I ran it.
There's a few little things that could be improved here, but it is
still very nice to know stuff gets caught sooner rather than later
(and I'd love if it the compiler could catch some of those asserts at
compile time if it can prove it! I'm thinking that perhaps some
extensions to value range propagation could to the trick.)
More information about the Digitalmars-d
mailing list