Last active
August 26, 2015 19:49
-
-
Save nipafx/5b2b7c84d71426a368c9 to your computer and use it in GitHub Desktop.
Null-Infested Address
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
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