A nice D coding pattern
    bearophile via Digitalmars-d-learn 
    digitalmars-d-learn at puremagic.com
       
    Mon Nov 24 14:50:32 PST 2014
    
    
  
In some D programs I'm using this coding pattern:
struct Foo {
     // Instance fields here.
     @disable this();
     this(in string[] data) pure @safe
     in {
         // Many pre-conditions here.
     } out(result) {
         // Some post-conditions here.
     } body {
         // ...
     }
     Nullable!(string[][]) doIt() pure {
         //...
     }
     // Various other methods here...
}
void main() {
     // Created at compile-time.
     enum something = "........".Foo;
     // Something much larger is done at run-time.
     immutable const result = something.doIt;
}
The structure is created at compile-time using data known at 
compile-time (here a string). This struct has a constructor that 
runs at compile-time that has many pre-conditions that avoid 
wrong input data at compile-time.
The largest part of the computation is done at run-time calling 
one or more struct methods.
And the @disable this() assures that a struct is correctly 
initialized by the constructor.
This pattern has significant advantages regarding code 
reliability.
You can see an example of this pattern that I've used here:
http://rosettacode.org/wiki/Solve_a_Hopido_puzzle#D
Bye,
bearophile
    
    
More information about the Digitalmars-d-learn
mailing list