Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The best way to pass Java reference down the chain of objects

Let's consider a chain of objects like this:

Earth->Continent->Country->City->name

Let's also consider Earth.class has public static void main(String[] args)

When the application is executed with command-line option e.g. Barcelona, what would be the best way to pass it down to City object without introducing intermediate parameters?

Objects are created at different stages during program execution.

Should we make name variable static or use IoC such as Spring or Google Guice? Are there other options?

Any ideas are welcome.

like image 336
Ivan Balashov Avatar asked May 05 '12 16:05

Ivan Balashov


2 Answers

  • I like IOC best for this task. Let the IOC pass the dependency when it constructs the City.
  • Alternative: Use a static service registry, which can be queried for a value. The City could get its name from the service registry.
  • Alternative: Implement the Composite Pattern on your hierarchy, including a function such as find, which could return the City. Then you just have to query and set earth.find(BarcelonaID).setName(args[0]);

An example of how a IoC solution in PicoContainer would look like:

PicoContainer container = new DefaultPicoContainer();
container.addComponent(Earth.class);
container.addComponent(Continent.class);
container.addComponent(Country.class);
container.addComponent(City.class, new ConstantParameter(cityName));

City barcelona = container.getComponent(City.class);
like image 80
Christopher Oezbek Avatar answered Oct 25 '22 05:10

Christopher Oezbek


You can build data structures from the top-down -- the Continent constructs the city, or from the bottom-up -- main constructs the city and passes that to the Country, or using some combination. DI favors the latter.

public static void main(String... argv) {
  // Bottom up.
  City city = new City(/* args relevant to city */);
  Country country = new Country(city, /* args relevant to country */);
  Continent continent = new Continent(country, /* args relevant to continent */);
  Planet planet = new Planet(continent, /* args relevant to planet */);
}

class City {
  City(/* few parameters */) { /* little work */ }
}
class Country {
  Country(/* few parameters */) { /* little work */ }
}
...
class Planet {
  Planet(/* few parameters */) { /* little work */ }
}

which can be much cleaner than top-down:

public static void main(String... argv) {
  // Top down.
  Planet earth = new Planet(
    /* all the parameters needed by Earth and its dependencies. */);
}
class Planet {
  Planet(/* many parameters */) { /* lots of work */ }
}
...

The DI folk maintain that the bottom-up construction leads to much more maintainable and testable code but you don't need a DI framework to use it.

like image 32
Mike Samuel Avatar answered Oct 25 '22 05:10

Mike Samuel