Since Java doesn't have a null-coalescing operator like C# does, I wrote a method that does the same. The code and tests:
public class Coalesce
{
public static <T> T coalesce(T value, T defaultValue)
{
return value != null ? value : defaultValue;
}
}
public class CoalesceTest
{
@Test
public void shouldReturnValueIfNotNull()
{
Double nonNullValue = 123d;
Double defaultValue = 1d;
Double result = coalesce(nonNullValue, defaultValue);
assertEquals(nonNullValue, result);
}
@Test
public void shouldReturnDefaultValueIfValueIsNull()
{
Double nullValue = null;
Double defaultValue = 1d;
Double result = coalesce(nullValue, defaultValue);
assertEquals(defaultValue, result);
}
@Test
public void shouldReturnNullIfBothArgumentsNull()
{
Double nullValue = null;
Double defaultValue = null;
Double result = coalesce(nullValue, defaultValue);
assertNull(result);
}
}
It looks like Google's Guava library has a firstNonNull method that does the same thing, the only difference being that it throws a NullPointerException if both arguments are null. I guess throwing the exception makes sense, particularly if the name is firstNonNull, but at the moment I lean towards just having the method return null if both arguments are null, similar to how the C# operator works.
0 comments:
Post a Comment