I’m reviewing some team code and I found something like this :
MyObj obj = null;
try {
obj = myService.findObj(objId)
} catch (MyObjNotFoundException e) {
// The object wasn't found, it's the "normal" path
// Here they create the object in DB (but don't touch the obj variable)
// There is about 60 line of code
}
if (obj != null) {
// The object already exist, logs are written and some queue is filled
// with current objId to be processed later on
}
In my review I will write that using Exception to control the normal program flow isn’t a good idea, in term of performance or maintainability.
The best would be to modify the service to return null instead of throwing an Exception but :
- I’m not sure they own the service (may be another project/team)
- They may really need this exception somewhere else
So apart from the performance problem that will not be solved unless not throwing the Exception, I would like to give them a “cleaner” piece of code.
Here is my thought knowing the service only send this Exception :
try {
obj = myService.findObj(objId)
} finally {
}
if (obj == null) {
// The object wasn't found, it's the "normal" path
} else {
// The object already exist, logs are written and some queue is filled
// with current objId to be processed later on
}
Would you go this way?
Does it really make a step onto readability?
Would you think of something else ?
Thanks a lot.
In your suggestion, if the service throws an ObjectNotFoundException, your method also does. Without changing the signature of the service, what the code does currently is the only way to do it.
Or maybe you meant
This is very similar to the current code. In any case, what should be done IMHO to make the code cleaner, is extracting the 60 lines of code of the normal path into another method, itself splitted in several sub-methods.