Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I refer to an object in its constructor?

Can I do the following?

public Manager(String userName) {
    game = new Game(userName);
    game.addManager(this);
}

The problem is that I refer to an object (this) in its constructor (before it was actually created).

like image 384
Roman Avatar asked Dec 28 '22 19:12

Roman


1 Answers

Although it is legal Java, and in the case you describe (where it is the last line of the constructor) it is a pretty safe thing to do (with certain edge cases exempted), as a practice it is a bad thing to do, and like using goto (in languages that support the keyword) it should be something you think long and hard about. For your case, a better practice would be to make the constructor private, remove the call to addManager and expose a static factory method:

 public static Manager createManager(String userName) {
        Manager manager = new Manager(userName);
        manager.game.addManager(manager);
        return manager;
 }

I should also point out that that kind of interdependency among classes (the manager knows about the game and the game knows about the manager) is definitely a code smell, and I would be as concerned about the need for that as I would be about passing this from the constructor.

like image 182
Yishai Avatar answered Dec 31 '22 08:12

Yishai