I am looking for ways to simplify a lot of ugly catch catch code all over the place. For example, I see:
try { objectA.setFieldX(objectB.getFieldY()); } catch(NullPointerException e) { ...stuff } catch(OtherException e) { ...stuff }
Such things are repeated everywhere for different fields, some of them differ slightly in their behavior, based on whether the field is optional or not. It is cumbersome, poorly documented, and leaves the reader with a distinct impression that (in addition to bad code) this may be wrong.
If my DataTransferObejcts (in addition to the standard sets (values) and get ()) are the "common" get and set methods that took some enumerated FieldID (for example, get () or set (, the value of the object) then (in the class with with lots of sets wrapped up in ugly try / catch) I could just define some helpers, for example:
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 that executes all the sets will have the following code:
setRequiredField(source, <FieldIDAsource>, dest, <FieldIDAdest>); setOptionalField(source, <FieldIDBsource>, dest, <FieldIDBdest>);
It becomes much less bulky, more readable, more correct.
... but there are some problems like:
1) dropping wazoo: in general methods (in data transfer objects) I will need to do a lot of casting.
2) by making the general methods complete / correct: I assume that with Enum I could lock things up a bit, but there is a fear of errors in the general methods (makes me want to โgenerateโ data transfer objects using something like FreeMarker, but they have some "domain logic" in them ...).
In any case, if anyone has pointers on how to do it right, I would like to know