I'm looking for ways to simplify lots of ugly try catch code all over the place. For instance I'm seeing:
try {
objectA.setFieldX(objectB.getFieldY());
}
catch(NullPointerException e) {
...stuff
}
catch(OtherException e) {
...stuff
}
This kind of thing is repeated all over the place for the various fields, some are slightly different in behavior based on if the field is optional or not. It is bulky, poorly documented, and leaves the reader with the distinct impression that (aside from being poor code) it might be wrong.
If my DataTransferObejcts had (in addition to the standard set(value) and get()) "generic" get and set methods that took some kind of enumerated FieldID (like get(), or set(, object value)- then (in the class with many sets, wrapped in ugly try/catches) I could simply define some helpers like:
setRequiredField(objSource, <FieldIDsource>, objDest, <FieldIDdest) {
object SourceField = objSource.get(<FieldIDsource>);
if (sourceField != null) {
try {
objDest.set(<FieldIDdest>, SourceField);
}
catch (OtherException) {
... stuff (like logging) here
}
}
else {
... stuff (like logging) here
}
}
Then the method doing all the sets would have code like:
setRequiredField(source, <FieldIDAsource>, dest, <FieldIDAdest>);
setOptionalField(source, <FieldIDBsource>, dest, <FieldIDBdest>);
It becomes a lot less bulky, more readable, more correct....
...but there are some issues like:
1) casting up the wazoo: In the generic methods (in the Data Transfer Objects) I'd need to do a lot of casting.
2) making the generic methods complete/correct: I suppose using an Enum I could lock things up somewhat but there is a worry of making some mistake in the generic methods (makes me want to "generate" the Data Transfer Objects with something like FreeMarker- but they have some "domain logic" in them...).
Anyway, if someone has some pointers how to do this right I'd like to know