On Sun, Feb 15, 2015 at 8:17 AM, Yasuo Ohgaki <yohg...@ohgaki.net> wrote:
> I wrote simple D program "sample.d" to play with. Install D, then > > dmd sample.d && ./sample > > ====sample.d==== > import std.stdio; > > class A { > int x = 1; > int y = 2; > > public: > void set (int x, int y) > in { > assert(x > 0); > assert(y > 0); > } > body { > this.x = x; > this.y = y; > } > int mul() > out (ret) { > assert(ret > 0); > } > body { > return x * y; > } > > invariant { > assert(this.x > 0); > assert(this.y > 0); > } > } > > class B : A { > int a; > int b; > override void set (int a, int b) > in { > assert(a > 4); > assert(b > 2); > } > body { > this.a = a; > this.b = b; > } > override int mul() > out (ret) { > assert(ret > 4); > } > body { > return a * b; > } > > invariant { > assert(this.x > 0); > assert(this.y > 0); > } > } > > class C : A { > override void set (int x, int y) > in { > // Cannot work with override > assert(x > -4); > assert(y > -2); > } > body { > this.x = x; > this.y = y; > } > override int mul() > out (ret) { > assert(ret > -4); > } > body { > return x * y; > } > > // This cannot work. Less restrictive than parent > invariant { > assert(this.x > -4); > assert(this.y > -2); > } > } > > > void main() > { > A a = new A; > B b = new B; > C c = new C; > a.set(4,2); > writeln("Ans: ", a.mul()); > // -1 is invalid > //a.set(-1, 0); core.exception.AssertError@sample.d(10): Assertion failure > > b.set(5,3); // Fine with B. B is different type. > writeln("Ans: ", b.mul()); > } > ================= > > > As you can see, D has type safety by contracts and does non-intuitive > checks. > Question is "Does PHP need this kind of type safety?" > > I totally agree strict type safety is good for writing correct programs, > BTW. > D has type safety feature since it has strong type. If PHP is going to be > strongly typed language as scalar type hint RFC, and might be stronger > type than now. We may consider stricter types later. It's not just time > for it. IMHO. > PHP may be extended to check contracts like D when > declare('strict_types'=1). > I used latest D rpm package for CentOS/Fedore x86_64 from http://dlang.org/download.html It seems invariant() is removed from latest D, but the package can use invariant(). You may get errors if you use real latest D. Regards, -- Yasuo Ohgaki yohg...@ohgaki.net