Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

enums

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?

like image 906
James P. Avatar asked Jun 26 '11 12:06

James P.


1 Answers

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.

like image 163
Bohemian Avatar answered Sep 28 '22 11:09

Bohemian