Das Beispiel für schlechte Programmierung must nicht sein: Es ist wirklich kein Hexenwerk, man erzeugt zunächst ein nur allzu sinnvolles Interface, das sowohl von CachingCollectableFieldsProvider, als auch von DatasourceBasedCollectableFieldProvider implementiert wird:
public interface DefaultValueProviderWithIds extends DefaultValueProvider {
List<CollectableField> getCollectableFields(List<Integer> lstFieldIds) throws CommonBusinessException;
}
Und schon sieht der ganze Code viel freundlicher und logischer aus, ohne Codeverdoppelung und wirre Verschachtelung:
private CollectableField getValueFromValueListProvider(CollectableField clctfValue) {
if (clctfValue == null) {
return null;
}
if (getValueListProvider() instanceof DefaultValueProviderWithIds) {
DefaultValueProviderWithIds dvpwi = (DefaultValueProviderWithIds)getValueListProvider();
try {
List<Integer> ids = Collections.singletonList(IdUtils.unsafeToId(clctfValue.getValueId()));
CollectableField cf = CollectionUtils.getSingleIfExist(dvpwi.getCollectableFields(ids));
if (cf != null) {
return cf;
}
} catch (IllegalArgumentException e) {
// ignore here. VLP has no id or value column set.
} catch (Exception e) {
throw new NuclosFatalException(e);
}
}
return clctfValue;
}
private void setFieldInitial(CollectableField clctfValue) {
getModel().setFieldInitial(getValueFromValueListProvider(clctfValue));
}
@Override
public void setField(CollectableField clctfValue) {
super.setField(getValueFromValueListProvider(clctfValue));
}
Überblick
Inhalte
Kommentar
Andreas Lämmlein sagt:
Besser wäre es ganz ohne den unseligen instanceof Operator, da so eine Architektur leicht zu Laufzeit-Fehlern führt.
Siehe z.B.
https://dzone.com/articles/instanceof-considered-harmfulhttps://dzone.com/articles/instanceof-considered-harmful
http://www.javapractices.com/topic/TopicAction.do?Id=31
Leider kommt das in Nuclos tausendfach vor.