I'm working on JSF project with Spring and Hibernate which among other things has a number of Converters that follow the same pattern:
getAsObjectreceives the string representation of the object id, converts it to a number, and fetch the entity of the given kind and the given idgetAsStringreceives and entity and returns the id of the object converted toString
The code is essentially what follows (checks omitted):
@ManagedBean(name="myConverter")
@SessionScoped
public class MyConverter implements Converter {
private MyService myService;
/* ... */
@Override
public Object getAsObject(FacesContext facesContext, UIComponent uiComponent, String value) {
int id = Integer.parseInt(value);
return myService.getById(id);
}
@Override
public String getAsString(FacesContext facesContext, UIComponent uiComponent, Object value) {
return ((MyEntity)value).getId().toString();
}
}
Given the large number of Converters that are exactly like this (except for the type of MyService and MyEntity of course), I was wondering if it was worth using a single generic converter.
The implementation of the generic by itself is not difficult, but I'm not sure about the right approach to declare the Beans.
A possible solution is the following:
1 - Write the generic implementation, let's call it MyGenericConverter, without any Bean annotation
2 - Write the specific converter ad a subclass of MyGenericConverter<T> and annotate it as needed:
@ManagedBean(name="myFooConverter")
@SessionScoped
public class MyFooConverter implements MyGenericConverter<Foo> {
/* ... */
}
While writing this I realized that maybe a Generic is not really needed, so maybe I could simply write a base class with the implementation of the two methods, and subclass as needed.
There a few non trivial details that have to be taken care of (like the fact that I'd have to abstract the MyService class in some way) so my first question is : is it worth the hassle ?
And if so, are there other approaches ?