Skip to content

Instantly share code, notes, and snippets.

@andypalmer
Created May 16, 2011 10:48
Show Gist options
  • Save andypalmer/974225 to your computer and use it in GitHub Desktop.
Save andypalmer/974225 to your computer and use it in GitHub Desktop.
Instead of checking nulls all the way down the list
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