Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

complex if( ) or enum?

Tags:

java

enums

In my app, I need to branch out if the input matches some specific 20 entries.

I thought of using an enum

public enum dateRule { is_on, is_not_on, is_before,...}

and a switch on the enum constant to do a function

switch(dateRule.valueOf(input))
{
  case is_on : 
  case is_not_on :
  case is_before :
  .
  .
  .
  // function()
  break;
}

But the input strings will be like 'is on', 'is not on', 'is before' etc without _ between words. I learnt that an enum cannot have constants containing space.

Possible ways I could make out:

1, Using if statement to compare 20 possible inputs that giving a long if statement like

if(input.equals("is on") ||
   input.equals("is not on") || 
   input.equals("is before") ...)   { // function() }

2, Work on the input to insert _ between words but even other input strings that don't come under this 20 can have multiple words.

Is there a better way to implement this?

like image 721
aradhak Avatar asked Jun 14 '12 11:06

aradhak


3 Answers

You can define your own version of valueOf method inside the enum (just don't call it valueOf).

public enum State {
    IS_ON,
    IS_OFF;

    public static State translate(String value) {
        return valueOf(value.toUpperCase().replace(' ', '_'));
    }
}

Simply use it like before.

State state = State.translate("is on");

The earlier switch statement would still work.

like image 179
adarshr Avatar answered Sep 20 '22 00:09

adarshr


It is possible to seperate the enum identifier from the value. Something like this:

public enum MyEnumType
{
    IS_BEFORE("is before"),
    IS_ON("is on"),
    IS_NOT_ON("is not on")

    public final String value;

    MyEnumType(final String value)
    {
        this.value = value;
    }
}

You can also add methods to the enum-type (the method can have arguments as well), something like this:

public boolean isOnOrNotOn()
{
    return (this.value.contentEquals(IS_ON) || this.value.contentEquals(IS_NOT_ON));
}

Use in switch:

switch(dateRule.valueOf(input))
{
    case IS_ON: ...
    case IS_NOT_ON: ...
    case IS_BEFORE: ...
}

And when you get the value of IS_ON like for example System.out.println(IS_ON) it will show is on.

like image 24
Simon Forsberg Avatar answered Sep 19 '22 00:09

Simon Forsberg


If you're using Java 7, you can also choose the middle road here, and do a switch statement with Strings:

switch (input) {
    case "is on":
        // do stuff
        break;
    case "is not on":
        // etc
}
like image 40
fivedigit Avatar answered Sep 22 '22 00:09

fivedigit