Freemarker JavaBeans Databinding

Freemarker is a template engine for java which can be used to generate text (e.g. html) using a normal POJO/java beans data model.

In one of my current projects the customer wants to see a generated html documentation in a separate view which should automatically update when the user changes elements which are part of this documentation.

To achieve this we decided to use a template engine like Freemarker which makes life much easier (than using StringBuffer). As we are using a model which supports PropertyChangeEvent (even for lists), it is easy to listen to changes on the model an the regenerate the html document and update the view.

But in this case the PropertyChangeListener needs to know which properties are actually displayed using the html template to update in the correct cases. This is even more difficult when you have a more complex model with list of lists of things. So the idea was: “Why is there no extension for freemarker which registers a PropertyChangeListener to all lists/properties which are used in the template?”

The freemarker JavaBeans Databinding

So I decided to see how hard it would be to add this feature to freemarker. First you need to decorate the BeansWrapper implementation so you can provide your own StringModel and CollectionModel implementations. The StringModel is used for entities and the method StringModel#get(String key) is called to access properties of the entity. The CollectionModel is used for lists and the method iterator() is called to access the lists items. So when the template accesses a property or a list, we want to register one propertychangelistener to it. So I created to decorator classes ListeningStringModel and ListeningCollectionModel. Finished.

freemarkerdatabinding

 

Here you can download the complete project: FreemarkerDataBinding
Feel free to take this as an example and use it in your own code.

DISCLAIMER: This is not production ready! There might be important things missing!

 

instanceof is bad design

I often see code like this:

public void displayVehicles(List<Vehicle> vehicles){
  for (Vehicle vehicle : vehicles) {
    setManufacturer(vehicle.getManufacturerName());
    
    if (vehicle instanceof Car) {
      setIcon("CarIcon");
      Car car = (Car) vehicle;
      String displayText = car.getCarName()+ " "+car.getModelName();
      setDisplayText(displayText);
    }
    if (vehicle instanceof Truck){
      setIcon("TruckIcon");
      Truck truck = (Truck) vehicle;
      String displayText = truck.getTruckSerie();
      setDisplayText(displayText);
    }
    
  }
}

Of course, you might immediately see that this is not what inheritance should look like and how you could solve this. The worst thing is that when you would add a third implementation “Bike” you will surely forget about this view-code.

There are different ways of improving this:

  1. Put a getDisplayText() and getIcon() method in the Vehicle interface
  2. Create an own object which contains all information necessary for this view. (or Composition)
  3. In some (rare) cases a visitor pattern might help as it allows dynamic dispatch. (Remark: There are languages which support multiple/double dispatch by default, like Lisp or Xtend)

As number 1 and 2 are quite easy solution it might not always make sense to change your domain model just for getting data for a view. So I have prepared a solution with the visitor pattern. In general, I’m actually not a big fan of it, but it is better than instanceof.

The Visitor Pattern

also read Wikipedia 🙂

The Visitor interface which needs to be implemented with one method for each concrete type.

public interface VehicleVisitor {

  void visit(Car car);

  void visit(Truck car);
}

I added an accept method to the Vehicle interface and really simple implementations to both Car and Truck which look identically. It is important, that it is added to every subclass and not to a abstract super class, as the reference this refers to the concrete type now.

 public void accept(VehicleVisitor vehicleVisitor){
   vehicleVisitor.visit(this);
 }

Now comes the ugly part. As the visit-Methods do not have a return type, I need to remember its state in the Visitor itself. I’m using simple fields here.

public class DisplayNameModelVisitor implements VehicleVisitor {

  private String displayText;
  private String icon;

  public void visit(Car car) {
    displayText = car.getCarName() + " " + car.getModelName();
    icon="CarIcon";
  }

  public void visit(Truck truck) {
    displayText = truck.getTruckSerie();
    icon="TruckIcon";
  }
  
  public String getDisplayName(){
    return displayText;
  }
  
  public String getIcon() {
    return icon;
  }
}

The implementation of my VehicleDisplay class got a lot easier now:

public void displayVehiclesWithVisitor(List<Vehicle> vehicles){
  DisplayNameModelVisitor modelVisitor = new DisplayNameModelVisitor();
  for (Vehicle vehicle : vehicles) {
    setManufacturerName(vehicle.getManufacturerName());
    vehicle.accept(modelVisitor);
    setDisplayText(modelVisitor.getDisplayName());
    setIcon(modelVisitor.getIcon());
  }
}

So for me this is a valid way to remove the uses of instanceof. A major advantage is that when you add a bike class and you insert the accept method on the class you will realize that you have to extend the Visitor interface and all Visitor implementations to be able to handle bikes now correctly.

I have the complete maven eclipse project here: InstanceOf-Visitor-Example

Guice Dependency Injection – Assisted

Hi everyone. With this blog post I want to start a new category called “well-intentioned” (German: “gut gemeint”) which is about information on the internet which might lead to misunderstandings.

Today I talk about a blog post from Cédric Beust which is quite well ranked on google:
http://beust.com/weblog/2012/08/21/advanced-dependency-injection-with-guice/

In general I agree with Cédric: Dependency Injection (DI) is a pretty comfortable thing and I don’t want to miss it in any of my projects. Especially guice is a Easy-To-Use concept. I would always recommend to use Constructor injection as it can be simply used without DI as well (e.g. in Unit Tests).

BUT: The example in his blog post could be misleading. (Sadly the exampe on Guice’s website is as bad: https://github.com/google/guice/wiki/AssistedInject)

Here some statements:

Dependency on Guice in all classes

When using a external framework you try to have dependencies to it only in a small part of your software. This makes it easier to switch to a different framework. When you use the @Assisted annotation, you introduce a dependency to guice. This is even worse if you use google’s @Inject annotation. You should always prefer to use @javax.inject.Inject (https://code.google.com/p/atinject/). (In most code snippets in the internet no imports are shown.)

Constructor in the example contains Service and field data

When developing (with Java) you should distinguish clearly between data classes (Entity/DTO/POJO…) and worker classes (Services, Handlers, Controllers, Managers…). The data objects contain the state of your domain’s entities and the worker classes should be stateless.

Dependeny Injection is much more useful for the worker classes. Here you need to build a complex object graph of Processors, Facades, Proxies and more.

In the blog example, the data class uses a service which is not the way you should do it.

Real Life example for Assisted Injection

I tried to come up with a real life example where it is really good advice to use Assisted Injection. As it seems quite hard I’m not sure if there is one at all. Perhaps a Service which gets a Configuration Object which cannot be injected as it needs to be created programmatically (e.g. from a Properties file).

Simple Guice Example

import javax.inject.Inject;

public class AddressValidationService {

 @Inject
 public AddressValidationService(GeoService geoService, AddressConfiguration addressConfiguration) {
 this.addressConfiguration = addressConfiguration;
 this.geoService = geoService;
 }
}

In this simple example we use Constructor injection. So it is quite easy to write a Unit Test for this class as there is no need to use Guice there. Here an example with Mockito:

public class AdressValidationFacadeTest{

@Test
 public void testValidation() {
 GeoService geoService = mock(GeoService.class);
 AddressConfiguration addressConfiguration = mock(AddressConfiguration.class);
 AddressValidationService addressValidation = new AddressValidationService(geoService, addressConfiguration);
 assertTrue(addressValidation.validate());
 }
}

 

Extended example with Assisted Injection

It might be the case that the AddressConfiguration object is not available via injection and therefore needs to be provided manually. To do so, you might consider using assisted injection mechanism, which automatically generates you a Factory class.

You just need to add the Assisted annotation and provide a factory interface which needs to be registered to the FactoryModuleBuilder:

public class AddressValidationService {

  @Inject
 public AddressValidationService(GeoService geoService, @Assisted AddressConfiguration addressConfiguration) {
 this.addressConfiguration = addressConfiguration;
 this.geoService = geoService;
 }

The factory interface:

public interface AddressValidationServiceFactory {

 AddressValidationService create(AddressConfiguration addressConfiguration);
}

In the Guice Module:

public void configure(Binder binder) {
 binder.install(new FactoryModuleBuilder().build(AddressValidationServiceFactory.class));
 }

So when you now use the factory by Injecting it to one of your classes a auto-generated implementation is bound by guice. MAGIC 🙂

Here is the complete maven project: Guice Example With Assisted Injection