1

So let's say I have 2 classes, House and Dog

I would like the Dog to know about the House it resides in, and vice versa.

I currently have these 2 classes setup:


House class:

public class House {

private String address;
private Dog dog;

public House(String address, Dog dog) {
    setAddress(address);
    setDog(dog);
    dog.setHouse(this);
}

public void setDog(Dog dog) {
    this.dog = dog;
}

public String getAddress() {
    return address;
}

public void setAddress(String address) {
    this.address = address;
}

public String getDog() {
    return dog.getName();
    }

}

Dog class:

public class Dog {

private House house;
private String name;

public Dog(String name) {
    setName(name);
}

public void setHouse(House house) {
    this.house = house;
}

public String getHouse() {
    return house.getAddress();
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
    }

}

Finally I have this main class to tie them both together:

public class Main {

public static void main(String[] args) {

    Dog dog = new Dog("Alex");
    House house = new House("123 Main street", dog);

    System.out.println(dog.getName() + " resides in " + dog.getHouse());
    System.out.println(house.getAddress() + " has a dog named " + house.getDog());

    }

}

Console output:

Alex resides in 123 Main street
123 Main street has a dog named Alex

I would essentially like to know if there is a better way of having both of these classes exchange data/information between each other. I feel like what I have right now is likely very messy/sloppy, and probably not good design practice. Open for any feedback/advice.

Thanks

Steven F.
  • 13
  • 2
  • you could look into builder design pattern may be – benjamin c Mar 17 '18 at 07:53
  • 1
    @benjaminc the builder design pattern is for: situations when you have complex objects where the creation should be independent of the parts that make it up OR the construction process must allow different representations for the object that's constructed. (i pulled this straight from the Gang of Four) book. this situation doesn't match either use case. –  Mar 17 '18 at 08:06
  • interesting.... – benjamin c Mar 17 '18 at 08:13
  • You are having cyclic dependency in your code + from constructor you are passing the `this`, it might happen that current constructor was invoked from another overloaded constructor or from a constructor of sub classes and thereby all the states may not be set. Based on these two points you can search as how to resolve these one by one. You are on the right track if you ask this question. Refactor your code based on these 2 points. – nits.kk Mar 17 '18 at 08:15

1 Answers1

0

i think what you're looking for is in this: Managing Bidirectional Associations in my Java Model question which as it so happens has links to other useful stack overflow answers.