Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java enum best practice

Tags:

java

enums

This might seem like a trivial question, but I'm a bit muddled in my thinking regarding enums..

So I have a class - let's say its called DVDPlayer - and I want to have an enum that represents whether it's ON, OFF, or STANDBY.

So I can put the enum in the class - it doesn't make sense outside of the class. My question is this - should the enum be public, so that other classes can query values, or should I make it private, and then have "isOn", "isOFf" and "isStandby" methods?

The latter sounds a bit daft, but I'm unsure as to whether it's a good idea to have the enum as public as well.

like image 324
pecks Avatar asked Aug 27 '10 08:08

pecks


People also ask

Is it good to use enum in Java?

You should use enum types any time you need to represent a fixed set of constants. That includes natural enum types such as the planets in our solar system and data sets where you know all possible values at compile time—for example, the choices on a menu, command line flags, and so on.

How do you use enums efficiently?

The Enum<T> generic base class provides quite a few convenient methods. Two frequently used among them are: String name(): Returns the name of the enum constant. int ordinal(): Returns the ordinal of this enumeration constant.

What is the point of Java enums?

The main objective of enum is to define our own data types(Enumerated Data Types). Declaration of enum in Java: Enum declaration can be done outside a Class or inside a Class but not inside a Method.

Are enums immutable Java?

Each item in a Java enum is called a constant, an immutable variable — a value that cannot be changed.


2 Answers

I would say it seems like a good idea to make it public. Main reason being that the application is easier to extend since you wouldn't have to think about adding new methods each time you add a state.

If you decide to make it public, you should consider having it as top-level enum. I don't really see why you say "it doesn't make sense outside of the class". I think a DVDPlayerState sounds like a perfectly fine public / top-level enum.

like image 90
aioobe Avatar answered Oct 19 '22 01:10

aioobe


It depends on how you want to use the DVDPlayer class from the outside world:

if (dvdPlayer.getState() == State.ON)

or

if (dvdPlayer.isOn())

I think the first one is a better option. You don't have to pollute your code with delegating methods.

like image 29
Petar Minchev Avatar answered Oct 19 '22 00:10

Petar Minchev