Skip to content

Instantly share code, notes, and snippets.

@nipafx
Last active August 26, 2015 19:49
Show Gist options
  • Save nipafx/5b2b7c84d71426a368c9 to your computer and use it in GitHub Desktop.
Save nipafx/5b2b7c84d71426a368c9 to your computer and use it in GitHub Desktop.
Null-Infested Address
public class Address {
private final String addressLine; // never null
private final String city; // never null
private final String postcode; // optional, thus may be null
// constructor ensures non-null fields really are non-null
// optional field can just be stored directly, as null means optional
public Address(String addressLine, String city, String postcode) {
this.addressLine = Preconditions.chckNotNull(addressLine);
this.city = Preconditions.chckNotNull(city);
this.postcode = postcode;
}
// normal getters
public String getAddressLine() {
return addressLine;
}
public String getCity() {
return city;
}
// special getter for optional field
public Optional<String> getPostcode() {
return Optional.ofNullable(postcode);
}
// return optional instead of null for business logic methods that may not find a result
public static Optional<Address> findAddress(String userInput) {
return... // find the address, returning Optional.empty() if not found
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment