Created
May 16, 2011 10:48
-
-
Save andypalmer/974225 to your computer and use it in GitHub Desktop.
Instead of checking nulls all the way down the list
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import static org.junit.Assert.*; | |
import org.junit.Test; | |
import static org.hamcrest.CoreMatchers.*; | |
public class SomethingOrNothingTest { | |
@Test | |
public void shouldGiveMeSomething() throws Exception { | |
final String nonNullString = "hello"; | |
String result = somethingOrNull( | |
new Some<String>() { | |
public String result() { | |
return nonNullString.toString(); | |
} | |
}); | |
assertThat(result, is(notNullValue())); | |
} | |
@Test | |
public void shouldGiveMeNothing() throws Exception { | |
final String nullString = null; | |
String result = somethingOrNull( | |
new Some<String>() { | |
public String result() { | |
return nullString.toString(); | |
} | |
}); | |
assertThat(result, is(nullValue())); | |
} | |
public <T> T somethingOrNull(Some<T> something) { | |
try { | |
return (T) something.result(); | |
} catch (NullPointerException e) { | |
return null; | |
} | |
} | |
public abstract class Some<T> { | |
public abstract T result(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment