I have a method which takes an enum and uses it in some fashion. The issue is that I have many different enum types and am not what acceptable practice is to pass an enum to a method.
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
I’m assuming that you mean you have a bunch of different enum classes that mean separate things, and that you want to pass them into one method.
To do that, use a marker interface:
then:
Now your method will accept a parameter of type
SpecialEnumType:Having done that, you can do:
In general, it’s perfectly alright to use an enum as a parameter type for a method argument.
UPDATE
I’ve used this pattern while integrating with third-party API’s. For example, a little while ago I had to integrate with different shipping providers. To do this, I provided a general interface that allowed the developer to send in shipping information (like the addresses, packages, weights, packing options, etc.). If you wanted to implement integration with a new provided, all you needed to do was implement the interface.
Now each shipping provider had its own set of options. Before using marker interfaces, I had a single enum which contained all the options (of all the different shipping providers). This is obviously hard to maintain. But I couldn’t split the enums into different classes because the interface specified a specific type of enum for the method arguments.
Using a marker interface, I was able to get around this problem. I created an interface called
ShippingProviderOption. Then for each provider, I extended the interface and created an enum, with the specific options for that provider. This way I was able to separate out the options, but still present a common interface.As far as code is concerned (greatly simplified and somewhat contrived, for demonstration purposes):
Now in my actual implementation, I have a few methods in the marker interface. So it doesn’t really even have to be a marker interface; it can contain methods.