I'm creating a canvas drawing with 2 objects: Rectangles, and Lines connecting the Rectangles. Each Line should be aware of the 2 Rectangles it connects.
Every Rectangle can have multiple lines that connect it to other Rectangles.
class Rectangle {
List<Line> connections;
void setConnection(Line line) {
connections.add(line);
}
}
class Line {
Rectangle from, to;
public Line(Rectangle from, Rectangle to) {
this.from = from;
this.to = to;
from.setConnection(this);
to.setConnection(this);
}
}
I feel this might not be a good design, because when I delete a Line, I will also have to delete the Line from the connections list in the Rectangle it connects.
When I delete a Rectangle, I also have to remove the Lines that are connected to the rectangle, as they should not exist without. Therefore I have to iterate through all connections of the deletable Rectangle, and for each connection get the from/to rectangle, and there again get the connection list and remove the Line reference.
My problem is not to write that code (I already have it working), but it seems to me I'm doing a lot of back-and-forth references.
Can this be done better? Somehow: if a rectangle is deleted, then all deep connections from the lines are removed/invalidated automatically? Something similar to Hibernate's many-to-many cascading? I can't just use Hibernate because this is supposed to be a client side app, without a database.