2

Is this a violation of the Law of Demeter?

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

How about this one?

private void MoveEmptyCell()
{
     Cell cell = this.internalGrid.GetEmptyCell();
     cell.RowIndex += this.moveDistance; // violation here?         
}
bitbonk
  • 48,890
  • 37
  • 186
  • 278

2 Answers2

0

Law of Demeter says:

More formally, the Law of Demeter for functions requires that a method m of an object O may only invoke the methods of the following kinds of objects:

O itself
m's parameters
Any objects created/instantiated within m
O's direct component objects
A global variable, accessible by O, in the scope of m

(...) That is, the code a.b.Method() breaks the law where a.Method() does not.

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; // Method of // O itself.
Return a RowIndex object with no behavior, and so Demeter does not apply.

Cobaia
  • 1,503
  • 3
  • 22
  • 41
0

It is if not breaking, then it is slightly bending the Demeter Law.

You could try implementing it in a way so that you can call:

(...)
this.internalGrid.MoveEmptyCellBy(this.moveDistance);
(...)
Adam Adamaszek
  • 3,914
  • 1
  • 19
  • 24