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");
}
Pass by enum
public buy(Item item){}
Pass by literal value
public buy(String itemValue){}
Cheers.
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.
Enums can be parameterized.
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.
Enum (see below code) uses == operator to check if two enum are equal.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With