Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do Java libraries use constant ints more than enums?

I am not sure if this is a definitive statement, but it seems to me that the Java API prefers constant ints over enums. From the parts of the API that I have used, I've encountered many final static int constants where an enum could have been used instead. Once such example that I happen to be staring at this moment:

From java.awt.BasicStroke:

public final static int CAP_BUTT = 0;
public final static int CAP_ROUND = 1;
public final static int CAP_SQUARE = 2;

In fact, I don't think I've ever seen an enum used in a standard Java API class. Why is this?

I'm designing an API for my own application (about a billion times smaller than the Java API, but I'm still trying to be smart about it), and trying to decide whether to use constant ints or enums. THIS post references a very popular book I haven't read yet which implies enums have many advantages. Most other highly scored answers in that same thread agree. So why does Java not seem to use its own enum capabilities?

like image 807
The111 Avatar asked Feb 23 '13 23:02

The111


2 Answers

BasicStroke pre-dates enum which arrived in Java 1.5. The code has been left as-is for backward compatibility. When writing any new code, enums are definitely a better design choice over final static variables.

like image 196
Reimeus Avatar answered Sep 28 '22 23:09

Reimeus


It's nothing to do with constant int being better than an enum: it's just that enum was only added in JDK 5, so most of the java API was written before enum was available: constant ints were the only option, so were used.

If the java API was re-written it would include far more enums, and you can expect to see them appear in new additions to the API in JDK6 or later.

You should probably use enums for your application, they are generally the better option.

like image 33
Jon Story Avatar answered Sep 28 '22 22:09

Jon Story