views:

2430

answers:

5

Hi guys,

I have a method lets say:

private static String drawCellValue(int maxCellLength, String cellValue, String align) { }

and as you can notice, I have a parameter called align. Inside this method I'm going to have some if condition on whether the value is a 'left' or 'right'.. setting the parameter as String, obviously I can pass any string value.. I would like to know if it's possible to have an Enum value as a method parameter, and if so, how?

Just in case someone thinks about this; I thought about using a Boolean value but I don't really fancy it. First, how to associate true/false with left/right ? (Ok, I can use comments but I still find it dirty) and secondly, I might decide to add a new value, like 'justify', so if I have more than 2 possible values, Boolean type is definitely not possible to use.

Any ideas?

+10  A: 

This should do it:

private enum Alignment { LEFT, RIGHT };    
String drawCellValue (int maxCellLength, String cellValue, Alignment align){
  if (align == Alignment.LEFT)
  {
    //Process it...
  }
}
Carra
thanks dude, you're the king :)
ninuhadida
just to clarify things up for beginners in java like me, to pass a value to the 'align' parameter all you need to do is, eg, this:drawCellValue (10, 'Test', Alignment.LEFT);
ninuhadida
Not that it's a big difference with only two values, but wouldn't a switch statement be better?
TM
+1  A: 

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.

Michael Bobick
+1  A: 

You could also reuse SwingConstants.{LEFT,RIGHT}. They are not enums, but they do already exist and are used in many places.

Tom
+7  A: 

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.

jdewald
+1  A: 

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...
}
Zamir
+1 The idea is on the right track. However, the process method should be abstract, and LEFT and RIGHT should each provide an implementation of it.
Chris Jester-Young