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.
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);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With