vendredi 10 mai 2019

Java Bidirectional Object References using "this" in Constructor

I'm trying to create and object and a component object that have bi-directional references to each other. In this example, I have a Bike class and a Wheel class. One option I considered (Option 1) is to have Bike create Wheel, then pass a reference of itself to Wheel in its constructor. However, I've read that I shouldn't be passing "this" outside of a constructor, and that it's better to create Wheel object outside of the Bike constructor. So I should create Wheel first, then pass it to Bike, then call setBike() method for Wheel (Option 2). It looks to me like Option 1 is the simplest way to create the bi-directional references between Bike and Wheel, but it also seems to be violating some design principles. Can someone explain why option 2 would be preferred over option 1?

Option 1:

public class Wheel {

    private Bike bike;

    Wheel(Bike bike) {
        this.bike = bike;
    }
}

public class Bike {

    private Wheel wheel;

    Bike() {
        this.wheel = new Wheel(this);
    }
}

Bike bike = new Bike();

Option 2 :

public class Wheel {

    private Bike bike;

    public void setBike(Bike bike) {
        this.bike = bike;
    }
}

public class Bike {

    private Wheel wheel;

    Bike(Wheel wheel) {
        this.wheel = wheel;
    }
}

Wheel wheel = new Wheel();
Bike bike = new Bike(wheel);
wheel.setBike(bike);

Aucun commentaire:

Enregistrer un commentaire