Home > Blockchain >  Tell-Don't-Ask principle for finding distance within same class
Tell-Don't-Ask principle for finding distance within same class

Time:08-24

From what I understand of the Tell-Don't-Ask principle, my other classes should not be able to call upon the data stored in any other class. Hence, getters are frowned upon under this principle. In order to prevent access into the data, they are normally written as:

class Point {
    private final double x;
    private final double y;
}

However, if I were to implement methods like distance between 2 points, I would need to access the x and y of the other point. In this case, I would need the getter method.

class Point {
    private final double x;
    private final double y;

    Point(double x, double y) {
        this.x = x;
        this.y = y;
    }

    private double getX() {
        return this.x;
    }

    private double getY() {
        return this.y;
    }

    public double distanceBetween(Point p) {
        double dx = this.x - p.getX();
        double dy = this.y - p.getY();
        return Math.sqrt(dx * dx   dy * dy);
    }
}

Wouldn't this violate the Tell-Don't-Ask principle? As now, I opened the data within the class to be accessed? Or is my understanding of the Tell-Don't-Ask principle wrong?

CodePudding user response:

You are "allowed" to access the data stored in yourself as a Point. So a Point object can access data stored inside itself, but also in other Point objects.

In short, that does not violate Tell-don't-ask (I assume that is what you mean).

Also, you don't need a getter method. Fields marked "private" can be accessed from any method in the class, regardless of instances of that class. The reason for that is exactly the above.

  • Related