d語言之契約編程編程
參考自d程序設計語言---個人博客http://my.oschina.net/u/218155/blog?fromerr=SwOkb7Sw fllow meide
import std.stdio; import std.exception; import std.algorithm; import std.range; import std.conv; import std.regex; //contract progarm //assert //before func //after func //invirant class Date{ private: uint year,month,day; invariant(){ assert(1 <= month && month <=12); switch(day){ case 29: assert(month != 2 || leapYear(year)); break; case 30: assert(month != 2); break; case 31: assert(longMonth(month)); break; default: assert(1<=day && day <= 20); break; } } static pure bool leapYear(uint y){ return (y%4) == 0 && (y%100 || (y %400)==0); } static pure bool longMonth(uint m){ return !(m & 1) == (m > 7); } void nextMonth(){ //__call_invariant(); //scope(exit)__call_invariant(); if(month == 12){ ++year; month = 1; }else{ ++month; adjustDay(); } } private void adjustDay(){ //__call_invariant(); //scope(exit)__call_invariant(); switch(day){ case 29: if(month == 2 && !leapYear(year)) day = 28; break; case 30: if(month == 2) day = 28+leapYear(year); break; case 31: if(month == 2) day = 28+leapYear(year); break; default: break; } } } int add(int x,int y) in{ if(x > 1){ writeln("x is bigger than 1"); } } out(result){ if(result > 10) { writeln("result > 10"); } } body{ return x+y; } class BasicDate { private uint day,month,year; string format(string spec) in{ writeln("fath"); assert(spec == "%Y/%m%d"); } body{ return text(year,'/',month,'/',day); } } class Mydate:BasicDate{ override string format(string spec) in{ writeln("son"); auto parttern = regex("(%[mdY%]|[^%])*"); assert(!match(spec,parttern).empty); }{ string result; return result; } } void main() { //test assert //enforce(false,"enforce false "); auto d = new Date(); d.year = 2000; d.month = 12; d.nextMonth(); writeln(d); int a = 1; int b = 1; assert(a == b); //test in out auto c = add(11,2); }