Skip to content

Instantly share code, notes, and snippets.

@philipschwarz
Last active January 12, 2016 22:16
Show Gist options
  • Save philipschwarz/e723885970c0f8202e59 to your computer and use it in GitHub Desktop.
Save philipschwarz/e723885970c0f8202e59 to your computer and use it in GitHub Desktop.
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