2006-08-09

Java vs. Ruby: Dependency Injection

Java using the Spring framework:

<!-- beans.xml -->
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
  "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
  <bean id="warmer" class="examples.Warmer">
    <property name="heater"><ref bean="heater"/></property>
    <property name="potSensor"><ref bean="potSensor"/></property>
  </bean>
  <bean id="heater" class="examples.Heater"/>
  <bean id="potSensor" class="examples.PotSensor"/>
  <bean id="boiler" class="examples.Boiler"/>
  <bean id="coffeeMaker" class="examples.CoffeeMaker">
    <property name="warmer"><ref bean="warmer"/></property>
    <property name="boiler"><ref bean="boiler"/></property>
  </bean>
</beans>
// java
InputStream is = new FileInputStream("beans.xml");
XmlBeanFactory factory = new XmlBeanFactory(is);
CoffeeMaker coffeeMaker = (CoffeeMaker)factory.getBean("coffeeMaker");

Ruby equivalent using the DIM framework:
container = DIM::Container.new
container.register(:warmer) { |c| Warmer.new(c.heater, c.pot_sensor) }
container.register(:heater) { Heater.new }
container.register(:pot_sensor) { PotSensor.new }
container.register(:boiler) { Boiler.new  }
container.register(:coffee_maker) { |c| CoffeeMaker.new(c.warmer, c.boiler) }
coffee_maker = container.coffee_maker

Jim Weirich's DIM framework is less than 30 lines of code. I don't know how many lines of code for Spring.

Reference: DIM