Last Updated: February 25, 2016
·
713
· jxcoder

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.

2 Responses
Add your response

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 ·