I'm working on computational geometry project. I have classes representing geometrical objects: Point, LineSegment and class, which performs calculations on those objects: Geometry. I'm confused with the Law of Demeter and "MethodWithPointAndLineSegment
".
class Point
{
public int X { get; set; }
public int Y { get; set; }
...
}
class LineSegment
{
public Point InitialPoint { get; set; }
public Point TerminalPoint { get; set; }
...
}
class Geometry
{
private ... MethodWithThreePoints(Point p1, Point p2, Point p3)
{
// accessing X and Y properties of passed points
...
}
public ... MethodWithPointAndLineSegment(Point p1, LineSegment segment)
{
MethodWithThreePoints(p1, segment.InitialPoint, segment.TerminalPoint);
...
}
}
My question is: does MethodWithPointAndLineSegment
violates the Law od Demeter? I suppose yes, because it accesses InitialPoint and TerminalPoint properties and pass them as parameters to the MethodWithThreePoints
, which accesses X and Y properties of those points. In the other words, MethodWithThreePoints
uses properties of properties of objects passed to the class method.
If it violates the Law of Demeter, then I can't see best and reasonable solution for this problem. I know, I can add additional properties to the LineSegment class to satisfy LoD:
class LineSegment
{
...
public int InitialPointX
{
get { return InitialPoint.X; }
set { InitialPoint.X = value; }
}
//etc...
}
But when I want to invoke MethodWithThreePoints
within MethodWithPointAndLineSegment
it forces me to create new points: new Point(segment.InitialPointX, segment.InitialPointY)
... and pass those new points to the MethodWithThreePoints
. It introduces some additional and unwanted performance cost, because I have to create new objects and pass to them constructors values returned by the multi-level accessors.
I'm not sure, what would be the best solution for this problem and for many similar problems: satisfy LoD or convenience and in this case performance (those methods will be invoked many times in a short period for performing algorithms calculations).
Any suggestions and explanations are welcome.