Asking for code review - contract programming

Ali Cehreli acehreli at
Tue Jan 11 17:40:48 UTC 2022

On 1/7/22 06:03, chopchop wrote:

 > I am actually asking the community for code review

I've just looked at this.

 > - correct any mistake you could find

It looks fine to me. There are a few places that made me think:

In general, adding two Coordinates is suspicious to me:

However, subtracting two Coordinates makes sense and should return a 
Distance object.

The following invariant check might be a 'static assert':

(invariant has runtime cost.)

Accounting for the walls with +1, -1, etc. looks scary to me. I wonder 
whether the playground could be detached from the walls and you could 
use the familiar 0 indexed access. Perhaps by slicing inside a bigger 
area or by a special type that hides that logic from us.

A random thought about 'in' and 'out' contract blocks: Instead of adding 
statements inside these blocks, one can use functions to give a name to 
the check and also use the new contract syntax:

So, instead of the following:

     in {
         // The snake shall not backtrack on itself
         assert(body[0] + unitMotion[direction] != body[1]);

Something like this:

   bool updateBody(Direction direction)
   in (!doesBackTrack(direction), "Snake backtracks")
     // The body of the function ...

(Note 'do' is not used with the new syntax.)

 > Important note: I discovered there are 2 levels of contract testing.
 > 1. Checking that the code is sound, like verifying func param, etc

That is also a responsibility of unit testing.

 > 2. Ensuring that the game will work as a standard snake game! Think
 > win/loose conditions, etc.

That part is definitely outside of unit testing and is handled both by 
contract programming and by functional testing.

 > I am from the aero industry [...] Buffer overflow on board a plane [...]
 > I had been wondering for a while if D could be a part of the solution,
 > hence this project.

What do you think? Can the industry guidelines be sufficient to make D 
safe enough? Otherwise, a D program can spend a long time during a GC 
cycle. (So can other languages where destruction of even a single object 
can spend a lot of time but nobody pays attention to that.) Also, the 
program can run out of memory unless run-time dynamic allocation is 
banned by guidelines.


More information about the Digitalmars-d mailing list