Design : putting domain constraint at right place

A common question arises where to put Domain constraints ? Of course in domain object but where ? Most suitable place is constructor .Suppose I have a square grid – a position in grid is represented by x,y  – lower left of this grid is at 0,0 and upper right is at 7,7 .Now In my application I can move a point with in the grid but point should never be outside of grid .If we carefully examine this –It is a domain constraint which says that Coordinate should never be out of grid .One Not good approach would be like this –

public class Position() {
    private int x;
    private int y;
    //assume Grid is autowired by DI
    private Grid grid;
    public Position(int x,int y){
        this.x=x;
        this.y=y;
   }
   public Position add(int x,int y){
       //imposing constraint here
       if (grid.isPostionInsideGrid(this.x+x,this.y+y)){
           return new Position(this.x+x,this.y+y);
       }else {
           throw new RuntimeException("Position " +"(" +this.x+x+","+this.y+y+")" +"is outside grid");
       }
   }
}

If you carefully examine above code ,you would see a big gotcha [Domain constraint violation ] ,It allows you to create an initial position which itself is out of Grid  – like new Position(100,101) .This is outside of grid which is bounded  by lower left 0,0 and upper right  7,7.Lets see a better way –

public class Position()
    private int x;
    private int y;
    //assume Grid is autowired by DI
    private Grid grid;
    public Position(int x,int y){
        this.x=x;
        this.y=y;
        //now this condition would always maintian class invariant that a point is always inside grid
        if (!grid.isPostionInsideGrid(this.x,this.y)){
             throw new RuntimeException("Position " +"(" +this.x+","+this.y+")" +"is outside grid");
        }
    }
    public Position add(int x,int y){
         return new Position(this.x+x,this.y+y);
    }
}

In new code- Domain constraint (Class invariant ) is hold always.You can never have a position which is outside grid.

Advertisements
This entry was posted in Design. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s