James Poulson James Poulson - 1 year ago 73
Java Question

Enum practices - Define inside a class/separately, make public/private

What is a good practise when defining an enum?

For example, I have a Person class. For this class I have chosen to use an enum which has the values MALE and FEMALE.

Should the enum be defined inside the Person class or separately? Should the enum be defined as private or public? Also, do you have any further advice that would make using an enum as flexible as possible?

Answer Source

IMHO, make it a public static enum inside class Person.

The reason is the enum Gender applies only to Person, so put it in there so they're bound together (Gender has no use without the context of a Person).

The upside:

  • less class bloat
  • if you move Person to another package/project, Gender will always come with it
  • Person, who is the only user, has "control" of it and may alter it as it wants, eg
    • adding private List<HealthIssue> genderSpecificHealthIssues;
    • adding more enums, eg TRANSGENDER, INTERSEX, or whatever

The only downside is you must use a static import to use it, ie import static com.company.Person.Gender.*;.

This pattern is seen in many JDK classes, such as Calendar which defines the many date-related constants it uses inside the class.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download