Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 230
Oh Chin Boon Avatar asked Jun 12 '11 02:06

Oh Chin Boon


People also ask

Should enum class be pass by value or reference?

enum class holds an integral value just like a regular enum so you can safely pass it by value without any overhead. Notice that compiler may sometimes optimize pass by reference as well by replacing it with pass by value. But passing by reference may result in some overhead when such an optimization is not applied.

Can enum be parameterized?

Enums can be parameterized.

Can you pass an enum as a parameter Java?

Yes, you can pass enum constants to methods, but you shouldn't use the 'enum' keyword in the method declaration, just like you don't use the 'class' keyword in a method declaration.

Should you use equals or == for enum?

Enum (see below code) uses == operator to check if two enum are equal.


1 Answers

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.

like image 100
btreat Avatar answered Oct 06 '22 00:10

btreat