2011-05-10 80 views
2

这是违反Law of Demeter的?这是否违反了德米特法?

private void MoveEmptyCells() 
{ 
    IEnumerable<Cell> cells = this.internalGrid.GetAllEmptyCells(); 
    foreach(Cell cell in cells) 
    { 
      cell.RowIndex += this.moveDistance; // violation here? 
    } 
} 

这个怎么样?

private void MoveEmptyCell() 
{ 
    Cell cell = this.internalGrid.GetEmptyCell(); 
    cell.RowIndex += this.moveDistance; // violation here?   
} 

回答

0

Law of Demeter说:

更正式地,迪米特为功能法律要求的方法的对象O的 m可以仅调用以下种 对象的方法:

O本身
m的参数
创建/实例化的任何对象 在m内
O的直接组件对象
全局变量, 被O访问,在m

(...)这是范围,代码a.b.Method()打破地方 a.Method()不规律。

Cell cell = this.internalGrid.GetEmptyCell(); // is O's direct component Object 
cell.RowIndex += this.moveDistance; // Cell is a object created/instantiated within m 

this.moveDistance; // // O本身的方法。
返回没有行为的RowIndex对象,因此Demeter不适用。

0

这是如果不破,那么它是略微弯曲德米特法。

你可以尝试的方式实现它,让您可以拨打:

(...) 
this.internalGrid.MoveEmptyCellBy(this.moveDistance); 
(...)