Feb 16, 2012

Translator pattern

One common task in banking is translating from one form to another. I couldn't find an effectife solution for this problem, but TranslatorPattern offers interesting approach.
I've used similar functionality in Amoeba utility classes:

 private static interface Amoeba<Value> {

  boolean consume(Amoeba<Value> amoeba);

  Value produce() throws Exception;
 }

 private static class AmoebaUtils {

  static <Value> boolean populate(Collection<Amoeba<Value>> colony, Amoeba<Value> nominate) {
   for (Amoeba<Value> citizen : colony) {
    if (citizen.equals(nominate)) {
     return citizen.consume(nominate);
    }
   }
   return colony.add(nominate);
  }

  static <Value> Collection<Value> produce(Set<Amoeba<Value>> colony) throws Exception {
   Set<Value> values = new HashSet<Value>();
   for (Amoeba<Value> citizen : colony) {
    values.add(citizen.produce());
   }

   return values;
  }
 }

This gives ability to absorb source notes by related destination nodes, providing natural grouping and translating of information. This is kind of builder and translator, with non-linear rules of transformation (source node != dest node).

List of Lists

Task: to order input data according 2 integer keys.
Example: we have bunch of options. Options have indexes and legs. Legs have indexes and other useful information.
Question: how to extract one type of information from legs?
Answer:
...
private final List<List<FinDate>> expiryDateByOptionAndLeg;
expiryDateByOptionAndLeg = new ArrayList<List<FinDate>>(size){
...
@Override
public List<
FinDate> get(int index) { 
 List<
FinDate> rez = null;
  rez = super.get(index);
  if(rez == null) {
   rez = new ArrayList<
FinDate>(2);
   add(index, rez);
  }
  return rez;
}
};
...
  expiryDateByOptionAndLeg.get(optionsIndex).set(legIndex, expiryDate);


Answer: To use approach suggested in ThreadLocal class javadocs. In this way we receive clear 2-indeger index without need to create list in business code. Similar approach could be applied to Maps.
It's simpler than creating  separate business object and still readable and expressive.