I have a method lets say:
private static String drawCellValue(
int maxCellLength, String cellValue, String align) { }
and as you can no
You can use an enum in said parameters like this:
public enum Alignment { LEFT, RIGHT }
private static String drawCellValue(
int maxCellLength, String cellValue, Alignment align) {}
then you can use either a switch or if statement to actually do something with said parameter.
switch(align) {
case LEFT: //something
case RIGHT: //something
default: //something
}
if(align == Alignment.RIGHT) { /*code*/}
I like this a lot better. reduces the if/switch, just do.
private enum Alignment { LEFT, RIGHT;
void process() {
//Process it...
}
};
String drawCellValue (int maxCellLength, String cellValue, Alignment align){
align.process();
}
of course, it can be:
String process(...) {
//Process it...
}
You could also reuse SwingConstants.{LEFT,RIGHT}. They are not enums, but they do already exist and are used in many places.
Sure, you could use an enum. Would something like the following work?
enum Alignment {
LEFT,
RIGHT
}
private static String drawCellValue(int maxCellLength, String cellValue, Alignment alignment) { }
If you wanted to use a boolean, you could rename the align parameter to something like alignLeft. I agree that this implementation is not as clean, but if you don't anticipate a lot of changes and this is not a public interface, it might be a good choice.
Even cooler with enums you can use switch:
switch (align) {
case LEFT: {
// do stuff
break;
}
case RIGHT: {
// do stuff
break;
}
default: { //added TOP_RIGHT but forgot about it?
throw new IllegalArgumentException("Can't yet handle " + align);
}
}
Enums are cool because the output of the exception will be the name of the enum value, rather than some arbitrary int value.
I am not too sure I would go and use an enum as a full fledged class - this is an object oriented language, and one of the most basic tenets of object orientation is that a class should do one thing and do it well.
An enum is doing a pretty good job at being an enum, and a class is doing a good job as a class. Mixing the two I have a feeling will get you into trouble - for example, you can't pass an instance of an enum as a parameter to a method, primarily because you can't create an instance of an enum.
So, even though you might be able to enum.process() does not mean that you should.