Avoiding multiple else ifs

Hi,

I am accepting an argument from a method and I want to enforce the user to send only a particular list of arguments (say: "Dog", "Cat", "Monkey"). So, I have created an interface and stored these values as constants.

Ideally the user of this method will call this method like:

myClass.myMethod(AnimalInterface.CAT);

But I have to check whether the argument sent will equal any of the interface constants defined in the AnimalInterface inside of my method. If it doesn't match, then I have to throw an IllegalArgumentException.

But, my problem is in the AnimalInterface, let's if I have about 20 constants, writing 20else ifs seems to be very weird. Is there any other way to get around this problem.

Thank you!

null

[778 byte] By [sri1025a] at [2007-10-3 3:21:40]
# 1

Use 1.5 and make an Enum.

If that's not an option, you'll have to simulate an enum yourself (using String/int constants inside an interface is not the way to go) and pass an instance of that, instead of a String.

final class AnimalsEnum {

private AnimalsEnum(String name) { myName = name; }

private final String myName;

public static final AnimalsEnum DOG = new AnimalsEnum("Dog");

public static final AnimalsEnum CAT = new AnimalsEnum("Cat");

//etc...

//probably implement toString to return myName

}

//and you would declare the target method as

void myMethod(AnimalsEnum animal);

//instead of

void myMethod(String animal);

If you can't use 1.5 Enums, I think something like that is the best solution; no more need to check inside your method since the argument can't have any other value than the ones defined in your class.

Lokoa at 2007-7-14 21:14:01 > top of Java-index,Other Topics,Patterns & OO Design...
# 2

Define your constants within an enum class instead of an interrface. Then you can call a static method within the enum to get your constant value.

public enum AnimalEnum {

// list your animals

...

public static AnimalEnum valueOf(String name) {

// find the defined constant matching the String

// maybe return null if there's no match

}

}

Method myMethod can then throw an llegalArgumentException if it is passed a null.

myClass.myMethod(AnimalEnum.valueOf(userString));

BillKriegera at 2007-7-14 21:14:01 > top of Java-index,Other Topics,Patterns & OO Design...
# 3
Thank you!And thank you very much for that little effective example cause we dont use 1.5 in our project. :)
sri1025a at 2007-7-14 21:14:01 > top of Java-index,Other Topics,Patterns & OO Design...