Java try / catch simplification approaches

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

+4
source share
3 answers

Actually, this is a clear example of what can be solved using Aspect Oriented Programming (AOP). The idea is that you can introduce standard logic for problems that affect your entire 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 details.

+2
source

You must reference the next thread in the stack overflow. When to select marked and unchecked exceptions

The main idea is to only throw an exception from which you can do something more. Otherwise, you must allow the exception to propagate to the last level and only catch the exception there immediately before recording it.

+2
source

If I understand your problem, you are trying to copy properties from one bean to another. You can use dozer for this ...

0
source

Source: https://habr.com/ru/post/1307461/


All Articles