Search code examples
javaoopinstance-variables

How to force java object to instantiate it's instance variables in specific order?


Having a class:

class Test {

  Object1 object1;
  Object2 object2;

  void setObject2 (Object2 newObject) {
    if (object1.someMethod()) {
      this.object2 = newObject;
    } else {
      someOtherMethod();
    }
  }
}

How can I force object instantiation that object1 must be instantiate before object2?

For now I can think to solve it

1.by making constructor with Object2 as parameter and instantiate it there

Test(Object1 object1) {
  this.object1 = object1;
}

2.by throwing exception from the method which try to set object2

void setObject2 (Object newObject) {
  if (object1 == null) {
    throw new Exception();
  }
  ...

Is there any other, more appropriate way to achieve it?

The reason I need it is that I have to create new advertisement campaign Test for a region object1 to advertise some of the region's sites object2. Before I can add site to campaign I want to check if the site belongs to the region.


Solution

  • A cleaner way design-wise can be to use the Builder-pattern. This way you can setup and create your objects only in correct ways instead of getting exceptions at runtime.

    The programmer doesn't need to read documentation or error messages to find out what he needs to do, since the API does the "guiding" itself.