开发者

Approaches for simplifying try / catch in Java

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


Actually, this is a clear example of something that can be solved via Aspect Oriented Programming (AOP). The idea is you can inject standard logic for issues that cut across your whole application. Classic examples are error handling and logging. There are several ways to do AOP with Java including Spring and AspectJ. See http://www.voelter.de/data/articles/aop/aop.html for more information.


You should refer the following thread in stack overflow When to choose checked and unchecked exceptions

The main idea is to only catch exception with which you can do something more. Otherwise you should let the exception propagate to the last layer and only catch Exception there directly before logging it.


If I understand your problem you are trying to copy properties from one bean to another. You may consider using dozer for that...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜