Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use constants instead of enums?

I've seen in lots and lots of Java libraries the use of lots of constants where enums could have easily been used. Even in Swing, there is a lot of code that uses constants instead of enums. Why?

What are the disadvantages to using enums?

like image 316
Michael Studebaker Avatar asked Aug 08 '11 07:08

Michael Studebaker


2 Answers

Because enums were introduced in Java 5, and those libraries have been written long before. Refactoring them would break a bazillion of existing applications.

like image 69
JB Nizet Avatar answered Nov 13 '22 09:11

JB Nizet


  • There is a lot of documentation of using pre-enum solutions.
  • There are lots of developers who are using Java for the first time and have experience with another language where using constants is the norm.
  • A lot of libraries wanted to support Java 1.4 and earlier. Java 1.3 & 1.4 are still used today.
  • Working code hasn't been re-written just to use enums.

I find I still telling people to use enum for a Singleton even though it has been around for 7 years now. :P

When would use use constants instead of enum? When you have many associated but not directly related constants.

public static final int BUFFER_SIZE = 32 * 1024;
public static final String ERROR = "Error: ";
public static final char TAB = 't';
like image 31
Peter Lawrey Avatar answered Nov 13 '22 08:11

Peter Lawrey