Best approximation for determining a LinkedHashSet in a domain model

What would be the best definition for LinkedHashSet in the Java Domain Model of the two options

Option 1

private Set<String> myCollection;

public Set<String> getMyCollection() {
    if (myCollection == null) {
        return new LinkedHashSet<String>();
    } else {
        return myCollection;
    }

}

public void setMyCollection(Set<String> myCollection) {
    this.myCollection = myCollection;
}

Option 2

private LinkedHashSet<String> myCollection;

public LinkedHashSet<String> getMyCollection() {
    return myCollection;
}

public void setMyCollection(LinkedHashSet<String> myCollection) {
    this.myCollection = myCollection;
}
+4
source share
1 answer

As a good practice, you should return empty collections, not zeros, even if they do not contain elements. A good way to be safe is to create them when declaring.
Secondly, you should program on interfaces, and not as they are implemented. If your client code does not use any feature of the implementation class, you must declare and return the interface type. This allows you to subsequently change the implementation without violating the client code.

Thus, your ad could be written as:

private Set<String> mySet = new LinkedHashSet<String>();

( ) - . , , . .

Seelenvirtuose, , . ( , ). . java.util.Collections.unmodifiableSet(), . (, ).

, JB Nizet, . , , . , , , .
, , . .

+1

All Articles