Reputation: 144
I'm trying to write a REST endpoint to return data depending on the staff type. And the staff are categorised according to their role within the organisation, like so.
public enum StaffType {
ADMIN("Admin"),
CASUAL("Casual"),
CORE("Core"),
MANAGEMENT("Management");
private String type;
StaffType(String type) {
this.type = type;
}
public String getType() {
return type;
}
}
Now in my REST endpoint, I cannot refer to these enums explicitly. The best I can do is refer to the String text associated with each, E.g. "Admin" or "Casual".
@RequestMapping(value = "/staff", method = RequestMethod.GET)
public ResponseEntity getStaff(
@RequestParam(value = "", required = false, defaultValue = "Admin")
StaffType staffType) {
But I do not like repeating this same string in two places when they are directly linked, and should always be the same.
So I thought of creating a constants, and having both refer to the constants in that class
public class Constants {
public static String ADMIN = "Admin";
public static String CASUAL = "Casual";
...
}
public enum StaffType {
ADMIN(Constants.ADMIN),
CASUAL(Constants.CASUAL),
...
}
@RequestMapping(value = "/staff", method = RequestMethod.GET)
public ResponseEntity getStaff(
@RequestParam(value = "", required = false, defaultValue = Constants.ADMIN)
StaffType staffType) {
My question is, does there a better, more widely accepted way to solve this problem? Or is this an appropriate solution?
Upvotes: 4
Views: 807
Reputation: 31269
Looks appropriate to me. However I would put the string constants inside the enum class though, that's better place to put them as they belong together with the enum constants. To get around the "no forward references" constraint you can put them in a static inner class inside the enum:
public enum StaffType {
ADMIN(Strings.ADMIN),
CASUAL(Strings.CASUAL);
public static class Strings {
public static String ADMIN = "Admin";
public static String CASUAL = "Casual";
}
// ...
}
@RequestMapping(value = "/staff", method = RequestMethod.GET)
public ResponseEntity getStaff(
@RequestParam(value = "", required = false, defaultValue = StaffType.Strings.ADMIN)
StaffType staffType) {
Upvotes: 5