Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it ok and safe to work with references passed to constructor - Java

I've got the following code:

public class Triangle {

    private Point left;
    private Point right;
    private Point top;

    public Triangle(Point left, Point right, Point top) {
        this.left = left;
        this.right = right;
        this.top = top;
    }

    // more program logic...
}

I was wondering if it's okay and safe to construct an object like that, because I fear that some of the three variables of type Point could be modified from the outside(break encapsulation). For example:

public static void main(String[] args) {

    Point left = new Point(0.0, 1.0);
    Point right = new Point(2.4, 3.2);
    Point top = new Point(5.8, 2.0);

    Triangle t = new Triangle(left, right, top);

    top.setX(10.2);
    top.setY(23.4); 
}

This will undoubtedly manipulate the same "top" object that's being referenced in the Triangle variable. So is the fix doing the following inside the Triangle constructor:

public Triangle(Point left, Point right, Point top) {
    this.left = new Point(left);
    this.right = new Point(right);
    this.top = new Point(top);
}

(keep in mind that I have a copy constructor in the Point class, so the three statements above are valid)

like image 881
Mr. Nicky Avatar asked Feb 07 '23 11:02

Mr. Nicky


1 Answers

You could clone the original points in the constructor and keep the clones hidden from the outside world. If Point already implements Cloneable or if you can implement it yourself, use it this way:

public Triangle(Point left, Point right, Point top) {
    this.left = left.clone();
    this.right = right.clone();
    this.top = top.clone();
}

If Point doesn't implement Cloneable and you have no access to its source code, just clone points manually:

public Triangle(Point left, Point right, Point top) {
    this.left = new Point(left.getX(), left.getY());
    this.right = new Point(right.getX(), right.getY());
    this.top = new Point(top.getX(), top.getY());
}
like image 187
Andrew Lygin Avatar answered Apr 30 '23 06:04

Andrew Lygin