Saturday, October 8, 2011

Beautiful Hunk of Java

I know, the title reads to some as an oxymoron, especially in light of Java's gnarly syntax requirements for closures. Still, some things are made beautiful partly because of the ugliness of the constituent material. Imagine a sculpture of Jessica Biel made of excised warts.
public enum SubstitutionVariable
{
AdjusterEstimator("Adjuster / Estimator", new ValueProvider()
{
public String get(Database db, OrderRec hdr) throws Exception
{
return hdr.selectAdjusterName(db) + " / " + hdr.selectEstimatorName(db);
}
}),
CustomerName("Customer Name", new ValueProvider()
{
public String get(Database db, OrderRec hdr) throws Exception
{
return hdr.selectCustomerName(db);
}
}),
InsuredName("Insured Name", new ValueProvider()
{
public String get(Database db, OrderRec hdr) throws Exception
{
return hdr.oInsured;
}
}),
WorkOrderClaim("Work Order / Claim", new ValueProvider()
{
public String get(Database db, OrderRec hdr) throws Exception
{
return hdr.oWorkOrder + " / " + hdr.oClaim;
}
});
interface ValueProvider
{
String get(Database db, OrderRec hdr) throws Exception;
}
//
//...some boring details left out...
//
private final String description;
private final ValueProvider valueProvider;
public static String substitute(String p, Database db, OrderRec hdr) throws Exception
{
for (SubstitutionVariable v : sortedByLengthDescending)
{
p = v.replace(p, db, hdr);
}
return p;
}
//
private SubstitutionVariable(String description, ValueProvider performer)
{
this.description = description;
this.valueProvider = performer;
}
//
public String getDescription()
{
return description;
}
//
private String replace(String p, Database db, OrderRec hdr) throws Exception
{
return StringKit.replace(p, "%" + name() + "%", valueProvider.get(db, hdr));
}
}