简体   繁体   中英

Should i pass an enum as a parameter or pass its literal value

i was thinking along the line when design some interfaces and classes whether i should be passing enum as a parameter or its literal value.

At this juncture, i am all for passing its literal value as i have read somewhere i could not remember about coupling issues passing the enum.

Does anyone have any opinion on this? :)

public enum Item{
CANDY("candy"), APPLE("apple");
}
  1. Pass by enum

    public buy(Item item){}
  2. Pass by literal value

    public buy(String itemValue){}

Cheers.

I would recommend passing the enum value as it is more strongly typed. In your example, if "candy" and "apple" are the only valid arguments to the 'buy' method, you can enforce that at compile time by requiring the enum rather than the String as the method argument.

Definitely pass by enum. My reasons being:

  1. It'll be much easier to work with the enum object rather than the string in the implementation of buy . For example, if you do need to do switch etc.
  2. Much better maintainability. You can easily see if you break anything if you do change the string representation, or the available enumeration values, whereas its not as easy to see when its converted to a String .
  3. When looking at the implementation of buy later on, you'll easily be able to see how each of the different enumeration values are handled. When you pass it as a String , you might not know looking at the method what all the possible input values are and how they are handled.

In most cases, I would pass the actual Enum type ( Item in this example) rather than a String representation. This ensures proper typing and is the purpose of Enums.

One situation where you might want to pass the String representation (obtained from Enum.name() ) is due to serialization/versioning issues.

For example, if you have several instances of an application running and you can't always be sure they are running the same versions, you may want to just pass the String representation between them, and attempt to manually deserialize them (using valueOf() ) and handle any differences that way.

Enums are classes but with a set of predefined values. As such you must both declare the enum and give a variable for its instance.

Try this example:

public class ItemDemo {

public enum Item { 
    CANDY("candy"), APPLE("apple"); 
   }

CANDY c;
APPLE a;

public ItemDemo(String name, int age, double money, CANDY c, APPLE a) {
       this.c= c;
       this.a= a;
     }
   }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM