Wednesday, April 1, 2009

java NVL function

NVL is a function in Oracle PL/SQL that is more or less this:

NVL(a,b) ==> (a == null)?b:a

And that's all well and good. The only problem occurs when the value of a either has side effects or either a or b are long and complex. You could write


foo a = ... long complicated code with possible side effects ...
foo b = ...yadda yadda yadda...
a = (a==null)?b:a;


But wouldn't it be easier to read as



a=nvl(... long complicated code with possible side effects ..., ... yadda yadda yadda ...)

?

Well, nvl() is easy to write, except that Java wants the arguments to be strongly typed.

Or does it?

You can declare the arguments are return as Object, but then you have to cast the return, and the compiler will not protect you from type mismatches.

The solution is generics. Write nvl like this:


public <T> T nvl(T a, T b) {
return (a == null)?b:a;
}


Mischief managed. The compiler will guarantee that there can be no type clashes, and so long as the same type is used for the two args and return, you're good to go.

5 comments:

German said...

Thanks man, great snippet!

Diego Souza said...

Obrigado pela dica!

alfasin said...

Awesome!
I was googling to see if there's a Java equivalent to NVL when I ran into your post - it would be nice if there was a builtin function - but since this implementation is compact & elegant - I guess I can just add it to a Util class ;)

Aschwin Versteegden said...

Here we are in july 2014 still using a post written in 2009! EPIC!
Thx for placing the snippet

FrankD said...

nice, thank you for the snippet