www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - Tidier pre/post conditions

reply bearophile <bearophileHUGS lycos.com> writes:
Generally a program can produce different outputs between release and not
release mode, but I always like to minimize the probability of this.

Two examples:

---------------

import std.stdio: writeln;

void foo(int[] arr)
out { arr[0] = 0; }
body {}

void main() {
    auto a = [1, 2];
    foo(a);
    writeln(a);
}

---------------

import std.stdio: writeln;
struct Foo {
    int x;
    invariant() { this.x -= 10; }
    void incr() { x++; }
}
void main() {
    Foo f;
    writeln(f.x);
    f.incr();
    writeln(f.x);
    f.incr();
    writeln(f.x);
}

---------------

The problem can be reduced if input arguments are seen as const inside pre/post
conditions, and attributes are seen as const inside class/struct invariants.
This is what I have asked:

http://d.puremagic.com/issues/show_bug.cgi?id=3856

But there's an alternative solution, to let the compiler accept only pure
pre/post conditions (and invariants that can only read attributes and write
nothing), but I am not sure if this can be a bit too much restrictive (can you
invent situations where this is too much restrictive?), so for now I have asked
just for the less restrictive thing.

Bye,
bearophile
Feb 26 2010
next sibling parent reply BCS <none anon.com> writes:
Hello bearophile,

 (can you invent situations where this is too much restrictive?),

Logging? Any pre conditions that require external services ("DNS names should have been checked at this point.", "key must exist in the DB")? Those wouldn't work but I'm not sure how much of an issue they are. -- ... <IXOYE><
Feb 26 2010
parent bearophile <bearophileHUGS lycos.com> writes:
BCS:
 Logging? Any pre conditions that require external services ("DNS names should 
 have been checked at this point.", "key must exist in the DB")?
 Those wouldn't work but I'm not sure how much of an issue they are.

Such usages are not common, and the program behaviour can change between release and not release versions, because you can modify a global variable, but I think forbidding them is not that useful. Turning locally attributes and arguments into const looks enough to me. Bye, bearophile
Feb 27 2010
prev sibling parent Lutger <lutger.blijdestijn gmail.com> writes:
Just practically speaking, not being able to call any non-pure functions is 
real pain. You can't even call to!string for example.

I like your original suggestion, thanks for putting it it in bugzilla. I 
hope it will considered some day. 

By the way, I just discovered contract programming is amazingly cool in D 
right now and also very buggy. 
Feb 27 2010