Reputation: 11621
I am working on a large code base that was written 90% in Java and 10% in Groovy. I only started learning Groovy recently and would like some advice. I have come across code like this in a Groovy method:
throw new RuntimeException(getErrorMessage(state));
This works most of the time. The problem is that on this very rare occasion, getErrorMessage(state)
returned null instead of a String. I cannot change the implementation of getErrorMessage()
.
I can fix this particular issue like this:
throw new RuntimeException((String) getErrorMessage(state));
or like this:
throw new RuntimeException(getErrorMessage(state) ?: '(no detail available)');
This issue would not arise if I used @CompileStatic
, but there are other parts of the code that rely on dynamic features.
My problem is that I can only fix such issues by coming across them as a result of a bug report, which is not good for the application's reliability and reputation. (Also the problem is not just with getErrorMessage
but with all possible situations in which an ambiguous overload exception can happen at runtime.)
How can I foresee such issues beforehand? (Currently available static analysis tools don't seem to be clever enough to catch this.)
Upvotes: 0
Views: 1293
Reputation: 9224
Do a search for all getErrorMessage()
and replace them for myGetErrorMessage()
:
public String myGetErrorMessage(int state) {
return getErrorMessage(state) ?: '(no detail available)';
}
Aspect-Oriented Programming may be overkill for this particular case, but it will get you what you want. You will still need to somehow identify all the methods that need intervention. This is an article describing several AOP libraries.
Upvotes: 1