why no "old" operator in function postconditions, as in Eiffel?
davidl
davidl at 126.com
Mon Jun 18 23:33:12 PDT 2007
That feature doesn't worth a keyword at all, and old(blah) pollutes the
naming space. You have several choices already:
The following shows how your old keyword should work(NOTICE: the code
would probably be not compatible with D2.0):
int func(int n)
out(result)
{
static int[int] funcmap; // create a func mapping here for further old
keyword test
// while this kind of sanity test would bloat the AA funcmap greatly
// But I don't see any other solution without increasing runtime to
solve this
// problem in *any* other language
funcmap[n]=result;
if ((n-1) in funcmap) // test if that has been calculated
assert(funcmap[n]==funcmap[n-1]+1);
}
body
{
if (n<1) return 0;
return func(n-1)+1;
}
void main()
{
func(3);
}
> I have started exploring D; a big attraction for me is the Design By
> Contract support. So I am quite surprised and disappointed that there
> is no "old" operator as in Eiffel, to permit a function postcondition to
> mention values from function entry. E.g. a container class might have
> something like:
>
> void insertFoo(Foo f)
> out
> {
> assert(fooCount == old(fooCount) + 1);
> }
>
> or a City class in a game might have something like:
> void buildStuff(int n)
> out
> {
> assert(resourceCount == old(resourceCount) - n);
> assert(stuffCount == old(stuffCount) + n);
> }
>
> (to give a couple of simplified examples)
>
> I regard this is a crucial part of DbC (similar to the language and
> compiler automatically handling inheritance of pre/postconditions, for
> instance); without this ability, function postconditions are quite
> crippled and much less expressive. Any function that changes the state
> of "this" and depends on the starting state of "this" wants to use "old"
> in the postcondition to explain the behavior.
>
> Being a newbie, I already asked in the digitalmars.D.learn ... no one
> there knew of a way to do this directly, only with various additional
> explicit boilerplate coding by the programmer. That's not good... It
> seems like D's DbC support is pointlessly crippled by this missing "old"
> functionality, which would not be hard to add. (The compiler just
> generates code to make a local variables to evaluate and save the value
> of expressions which are mentioned in "old" expressions in the
> function's postcondition. Exactly the sort of repetitive tedium that
> the programmer shouldn't have to do.)
>
> Are there plans to add such support to D? Searching the archives for
> "old" and "Eiffel" and find virtually no mention of this, which amazes
> me. I found "old" to be extremely useful when I coded in Eiffel. Not
> having it in a language that bills itself as supporting DbC seems like
> languages which only have "assert" and claim to be supporting DbC.
--
使用 Opera 革命性的电子邮件客户程序: http://www.opera.com/mail/
More information about the Digitalmars-d
mailing list