Logic inside an enum
Posted
by Vivin Paliath
on Stack Overflow
See other posts from Stack Overflow
or by Vivin Paliath
Published on 2010-03-19T00:07:51Z
Indexed on
2010/03/19
0:11 UTC
Read the original article
Hit count: 703
My colleagues and I were having a discussion regarding logic in enums. My personal preference is to not have any sort of logic in Java enums (although Java provides the ability to do that). The discussion in this cased centered around having a convenience method inside the enum that returned a map:
public enum PackageTypes {
Letter("01", "Letter"),
..
..
Tube("02", "Packaging Tube");
private String packageCode;
private String packageDescription;
..
..
public static Map<String, String> toMap() {
Map<String, String> map = new LinkedHashMap<String, String>();
for(PackageType packageType : PackageType.values()) {
map.put(packageType.getPackageCode(), packageType.getPackageDescription());
}
return map;
}
}
My personal preference is to pull this out into a service. The argument for having the method inside the enum centered around convenience. The idea was that you don't have to go to a service to get it, but can query the enum directly.
My argument centered around separation of concern and abstracting any kind of logic out to a service. I didn't think "convenience" was a strong argument to put this method inside an enum.
From a best-practices perspective, which one is better? Or does it simply come down to a matter of personal preference and code style?
© Stack Overflow or respective owner