Latest Posts »
Latest Comments »
Popular Posts »

Yet Another Java Trick

Written by Jevgeni Kabanov on April 5, 2008 – 10:38 am

Recently I ran into a bit of trouble when coding a particular method. It had a number of exit points, something like this:

JAVA:
  1. boolean method() {
  2.   if (conditionA)
  3.     return resultA;
  4.  
  5.   if (conditionB)
  6.     return resultB;
  7.  
  8.   if (conditionC)
  9.     return resultC;
  10. }

The problem was that I also needed to log the result before exiting. Since there was a lot of exit points I had a choice of two usual options:

  1. Log the result at each exit point
  2. Introduce a result variable and convert exit points to if blocks

I didn’t like either of them. The first introduces copy-paste, while the second makes method more complex (blocks are harder to follow than test-and-exit idiom).

Therefore I did something different:

JAVA:
  1. boolean method() {
  2.   boolean result = false;
  3.  
  4.   try {
  5.     if (conditionA)
  6.       return (result = resultA);
  7.  
  8.     if (conditionB)
  9.       return (result = resultB);
  10.  
  11.     if (conditionC)
  12.       return (result = resultC);
  13.   }
  14.   finally {
  15.     log(result)
  16.   }
  17. }

The idiom basically makes the return value available in the finally clause. It’s quite concise and the only gotcha is that on an exception the value will be initialized to the default one. Happy coding!


Tags: ,
Posted in creative | 32 Comments »