How to Define Constants in Java
Learn more about defining constants in Java!
Join the DZone community and get the full member experience.
Join For FreeThere seems to be a lot of confusion around the topic of constants in Java. Some people make use of integers or Strings to define constants, while others make use of enums.
I’ve also come across constants defined in their own interface — where classes that make use of the constants have to implement the interface. This strategy is often referred to as the interface constant design pattern.
In this article, we’ll have a look at the two most common strategies for storing constants in Java: integers and enums.
First and foremost, whenever you decide to use constants, you should be pretty certain that the constants won’t change over time so you can avoid recompiling.
In this article, we’ll work with a very common candidate for constants – weekdays!
Tip: Check out our review of the top 10 best Java courses on Udemy!
Let’s assume that we have a class representing an order in an online store, where we want to keep track of which day of the week the order occurred.
Our class looks like this:
public class Order {
private [datatype] weekDay;
public [datatype] getWeekDay() {
return weekDay;
}
public void setWeekDay([datatype] weekDay) {
this.weekDay = weekDay;
}
}
Note that the class won’t compile for the moment – [datatype] is simply a placeholder for the type of constant we’ll use.
Defining Constants With Integers
One of the most common ways to define constants in Java is through integers, where the integer variables are static.
public static int MONDAY = 0;
public static int TUESDAY = 1;
public static int WEDNESDAY = 2;
public static int THURSDAY = 3;
public static int FRIDAY = 4;
public static int SATURDAY = 5;
public static int SUNDAY = 6;
The first question to ask when defining integer constants is where to place them. Do we place them directly in the Order
class? Or do we give them their own class?
Since days are pretty general, and not necessarily just connected to objects of type Order
, we’ll define them in their own class WeekDay
.
public class WeekDay {
private WeekDay(){}
public static int MONDAY = 0;
public static int TUESDAY = 1;
public static int WEDNESDAY = 2;
public static int THURSDAY = 3;
public static int FRIDAY = 4;
public static int SATURDAY = 5;
public static int SUNDAY = 6;
}
You probably noticed the private constructor – this is to avoid clients from instantiating the class. The class holds only static variables, which are not tied to an object, so there is no need to instantiate the class.
Now, whenever we need to set a particular day to an order, we do it like this:
Order order = new Order();
order.setWeekDay(WeekDay.MONDAY);
And when we want to check whether an order occurred on a Friday, we can simply call write:
if(order.getWeekDay() == WeekDay.FRIDAY)
So far, so good. There surely can’t be any problems with this design?
Well, let’s assume that you’re coming back to this code a year later – and you have to check whether an order occurred on a Monday.
Oh, and of course – you have completely forgotten about the WeekDay
class...
In this scenario, you might try something like this:
if(order.getWeekDay() == 1)
At that moment, having completely forgotten about the WeekDay class, this code makes perfect sense. Monday is the first day of the week, so weekday should be 1, right?
But no, it isn’t, because the static int variable Monday is defined as 0 in our WeekDay
class!
This is a great example of why you should consider avoiding the use of integer constants. They are error-prone, confusing, and hard to debug.
Defining Constants With Enums
One other alternative to defining constants in Java is by using enums.
When using enums, our constants class will look something like this:
public enum WeekDay {
MONDAY,
TUESDAY,
WEDNESDAY,
THURSDAY,
FRIDAY,
SATURDAY,
SUNDAY
}
Notice the absence of the private constructor — there’s no need for the programmer (you!) to enforce that the class is non-instantiable since enums are non-instantiable by default!
The syntax for setting a WeekDay
to an order is exactly the same as with integer constants:
order.setWeekDay(WeekDay.MONDAY);
There is also no difference in how we can whether the order was processed on a Friday:
if(order.getWeekDay() == WeekDay.FRIDAY)
However, the key difference is that this is the only way you can set and compare values for the weekday variable in the Order
class.
Both order.setWeekDay(1);
and if(order.getWeekDay() == 1)
will make the compiler throw an error since you are trying to use variables of type integerwhen they should be of type WeekDay
!
Think back to the scenario when you had completely forgotten about the WeekDay
class.
With enums, this is no longer an issue. If you try to use integers instead of members of the WeekDay
enum, the compiler will simply throw an error, telling you that you need to use the WeekDay
enum.
Said in other words, the only thing that will work for you to check whether an order occurred on a Friday is:
if(order.getWeekDay == WeekDay.FRIDAY)
It doesn’t get any clearer than this!
You’re no longer forced to remember the constants class, and if any clients were to use your code, they don’t have to wonder whether Monday is actually represented by a 0 or a 1.
I hope this example demonstrated to you why you should consider using enums over integers when defining constants.
Enums will make your code less error-prone, easier to read, and more maintainable!
A quick tip: If you wish to expand your Java skill-set and become an advanced Java developer, I highly recommend you to get yourself a copy of the best-selling Effective Java, by Joshua Bloch!
Published at DZone with permission of An Eng. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments