Java Tip #2. Start to use "has*" methods!
Use "has*" methods instead of "get & check".
import java.util.Arrays;
import java.util.List;
class SomeObject {
private List<String> aliases;
public List<String> getAliases() {
return aliases;
}
public void setAliases(List<String> aliases) {
this.aliases = aliases;
}
public boolean hasAliases() {
List<String> currentAliases = getAliases();
return (currentAliases != null) && !currentAliases.isEmpty();
}
}
public class Main {
public static void main(String[] args) {
SomeObject someObject = new SomeObject();
someObject.setAliases(Arrays.asList(
"first-alias", "second-alias", "third-alias"
));
// bad!
List<String> someObjectAliases = someObject.getAliases();
if (someObjectAliases != null && !someObjectAliases.isEmpty()) {
/* ... */
}
// good!
if (someObject.hasAliases()) {
/* ... */
}
}
}
Using hasAliases method make the code more clear and human-oriented. Also, the method encapsulates check logic and prevents code duplication.
Written by Maks Atygaev
Related protips
2 Responses
there are issers also... for that
over 1 year ago
·
Yeap, isSet* methods is also more clear then "get & check" way!
over 1 year ago
·
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Java
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#