Is it correct to use enumeration in this case?
This is a best practice / style question.
I have a Printer class that can print an item with different colors. Is it correct to use Enum for input like this:
public class Printer {
public enum Color{RED, GREEN, BLUE}
public void print (Color color){
MyElement myElement = new MyElement();
switch (color) {
case RED:
myElement.setColor("#xxxxxx");
break;
case GREEN:
myElement.setColor("#xxxxxx");
break;
case BLUE:
myElement.setColor("#xxxxxx");
break;
}
myElement.print();
}
}
And then just call a method from another class like this:
Printer p = new Printer();
p.print(Printer.Color.RED);
... or it would be better to add values ββto the enum like this:
public class Printer {
public enum Color {
RED("#xxxxxx"),
GREEN("#xxxxxx"),
BLUE("#xxxxxx");
private final String hex;
Color(String hex){
this.hex = hex;
}
public String getHex(){
return this.hex;
}
}
public void print (Color color){
MyElement myElement = new MyElement();
myElement.setColor(color.getHex());
myElement.print();
}
}
... or maybe not use an enum at all and just use a regular string?
source to share
I see no problem with your solution. The only thing I would like to suggest is to create a constructor in the Enum and store the color value there. But this is just a suggestion.
It will be like this:
public class Printer {
public enum Color{
RED("#FF0000"), GREEN("#00FF00"), BLUE("#0000FF");
private String colorAsString;
private Color(String colorAsString) {
this.colorAsString = colorAsString;
}
public String getColorAsString() {
return this.colorAsString;
}
}
public void print (Color color){
MyElement myElement = new MyElement();
myElement.setColor(color.getColorAsString());
myElement.print();
}
}
source to share
Using constants enum
instead of constants usually makes sense. If the application is as simple as described in the question, then only 1 parameter (color value) using string constants is also effective.
If used enum
, the second approach is preferred (i.e. one that stores the color value through a constructor enum
).
source to share