Does this also violate Demeter’s law? Or would this be excessive warping?

very simple point:

class Point
{
    private $x, $y;

    public function __constructor($x, $y)
    {
        $this->x = $x;
        $this->y = $y;
    }

    public function getX()
    {
        return $this->x;
    }

    public function getY()
    {
        return $this->y;
    }
}

and circle

class Circle
{
    private $r;
    private $point;

    public function __constructor (Point $point, $r)
    {
        $this->point = $point;
        $this->r = $r;
    }

    public function getPoint() // here is the law breaking
    {
        return $this->point;
    }
}

$circle = new Circle(new Point(1,2), 10);
$circle->getPoint()->getX(); // here is the law breaking
$circle->getPoint()->getY(); // here is the law breaking

Of course, this violates the law of Demeter. So let me refrain from this:

class Circle
{
    private $r;
    private $point;

    public function __constructor (Point $point, $r)
    {
        $this->point = $point;
        $this->r = $r;
    }

    public function getPointX()
    {
        return $this->point->getX();
    }

    public function getPointY()
    {
        return $this->point->getY();
    }
}

$circle = new Circle(new Point(1,2), 10);
$circle->getPointX();
$circle->getPointY();

besides it looks better, I see no advantage - just two additional packaging features. Technically, I again have full access to Point, and there is no way to add to Pointmore methods. Should I use the second refractory method?

+4
source share
3 answers

Besides the fact that this is rather an opinion-based question, I would do it as follows:

class Circle extends Point
{
    private $r;

    public function __constructor (Point $point, $r)
    {
        $this->x = $point->getPointX();
        $this->y = $point->getPointY();
        $this->r = $r;
    }
}

$circle = new Circle(new Point(1,2), 10);
$circle->getPointX();
$circle->getPointY();
+1
source

I agree with @Webdesigner that this is more of an opinion based question.

, , , demeter , , Point value object.

public function center() : Point { ... };

.

+1

, , - " ". , , , , , , (, ).

, , . Getters (accessors) , , .

: - . , , , , :)

Ok, so how do you code without the getters you are asking about? Well, you add methods that do something for you with coordinates. Things you need. The distance between points, conversion points, etc. Everything you need in your current application. Think about what Point means in your current context.

See The Genius of the Demeter . "

+1
source

Source: https://habr.com/ru/post/1687079/


All Articles