Last active
September 28, 2020 22:45
-
-
Save soverby/44ba06ae53f0c38c71adee1bf4ef648d to your computer and use it in GitHub Desktop.
Using Optional.ofNullable and flatMap chaining to retrieve deeply nested properties without having to write a bunch of null checks.
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
package com.soverby.test; | |
import org.junit.Test; | |
import java.util.Optional; | |
import java.util.function.Function; | |
import static org.assertj.core.api.Java6Assertions.assertThat; | |
public class NullableChain { | |
// Prevent NPEs when extracting a value from a property graph, without having to manually check every one. | |
public static final Function<DomainType, String> getDeeplyNestedValue = (test) -> | |
Optional.ofNullable(test) | |
.flatMap(uwrap -> Optional.ofNullable(uwrap.getPropertyDomainType())) | |
.flatMap(uwrap -> Optional.ofNullable(uwrap.getPropertyDomainType())) | |
.flatMap(uwrap -> Optional.ofNullable(uwrap.getPropertyDomainType())) | |
.flatMap(uwrap -> Optional.ofNullable(uwrap.getValue())) | |
.orElseThrow(() -> new IllegalArgumentException("Get chain may not be null")); | |
@Test(expected=IllegalArgumentException.class) | |
public void retrievedNestedValue_nullTopLevel() { | |
getDeeplyNestedValue.apply(null); | |
} | |
@Test(expected=IllegalArgumentException.class) | |
public void retrievedNestedValue_nullThirdLevel() { | |
DomainType one = new DomainType("one"); | |
DomainType two = new DomainType("two"); | |
one.setPropertyDomainType(two); | |
getDeeplyNestedValue.apply(one); | |
} | |
@Test | |
public void retrievedNestedValue_returnsExpectedValue() { | |
DomainType one = new DomainType("one"); | |
DomainType two = new DomainType("two"); | |
DomainType three = new DomainType("three"); | |
DomainType four = new DomainType("four"); | |
three.setPropertyDomainType(four); | |
two.setPropertyDomainType(three); | |
one.setPropertyDomainType(two); | |
assertThat(getDeeplyNestedValue.apply(one)).isEqualTo("four"); | |
} | |
public static class DomainType { | |
private DomainType propertyDomainType; | |
private String value; | |
public DomainType(String value) { | |
this.value = value; | |
} | |
public DomainType getPropertyDomainType() { | |
return this.propertyDomainType; | |
} | |
public void setPropertyDomainType(DomainType one) { | |
this.propertyDomainType = one; | |
} | |
public String getValue() { | |
return this.value; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment