Using Enums for Configurable Settings in Java

When writing Spigot plugins for clients, it was common for them to request for everything to be configurable. Usually this was just the messages sent to players, in case they wanted to tweak something to be more consistent with other messages or change the language. 

Usually, this led to quite a lot of code being written for every single message sent. It was really annoying. Instead of writing "player.sendMessage("Player " + player.getName() + " not found!");" I had to write "player.sendMessage(config.getString("player-not-found").replace("{player}", player.getName()));. Then, in the config, I would have to write the entry with the default value so it can be read. Sometimes I would get the name of the config entry wrong, leading to ten minutes of figuring out the issue and recompiling/testing. 

Overtime, I wrote better methods of taking config values that would lead to less repetitive code being written. What I finally ended up with, and what I used for more than just messages, was a method that used Java's enums.

An enum class in Java is a set (constant) instances. They were created at compile time, and are accessed with syntax like "MyEnum.ENUM_OBJECT", the naming convention requiring all upper case with underscores. Enums can take constructors, so you can give them constant data as well. For settings, this is usually the default value and sometimes the readable description. An enum declaration looks like this:

MY_ENUM("Default value", "An example of an enum")

They can also have fields for each enum, which are writable. An example of how I use this method for messages would be to generate a file with all the configurable options by iterating through each enum instance and creating a field for each one using the name and default value. When I want to get the message value, I have a function on the enum which reads the value from the config file.