Reputation: 834
I have a class similar to this:
class DomainTypes {
public static final DomainType DOMAIN_1 = DomainType.of("example1.com");
public static final DomainType DOMAIN_2 = DomainType.of("example2.com");
public static final DomainType DOMAIN_3 = DomainType.of("example3.com");
public static Set<DomainType> getDomainTypes() {
return ImmutableSet.of(
DOMAIN_1, DOMAIN_2, DOMAIN_3
);
}
}
But this is error prone. In case somebody adds a domain as a new constant, she can forget to add it into getDomainTypes()
method. I don't want to use reflection if possible.
I need to have DomainType class in different module (jar) - kind of API module - let's say dns-api module, than DomainTypes. DomainTypes is rather configuration and it is in web-app module, which is dependent on dns-api module. With enum, I couldn't separate configuration from the object with implemented logic and I wouldn't be able to reuse dns-api module in another application. So I think tha using enum
is not a solution for me.
Upvotes: 1
Views: 803
Reputation: 206796
Use an enum
instead of a class with constants:
public enum DomainType {
DOMAIN_1("example1.com"),
DOMAIN_2("example2.com"),
DOMAIN_3("example3.com");
private final String url;
DomainType(String url) {
this.url = url;
}
public String getUrl() {
return url;
}
}
Enums automatically have a values()
method which gives you an array of all the values:
DomainType[] domainTypes = DomainType.values();
Upvotes: 1