Java: `enum` vs` String` as parameters

I read the details of the System library set and get methods, but the parameters are usually strings.

Don't you consider using String as a bad practice of parameters since enum turned on?

A better alternative, at least, could be public final String , No?

+7
java string enums const
source share
7 answers

I would think that Enums is better than Strings. They are type safe and compare them faster than string comparisons.

As an alternative to pre Java 1.5, you can use the enumerated template proposed by Joshua Bloch in his book Effective Java. For types of secure enumerations, see also http://www.javacamp.org/designPattern/enum.html

+18
source share

If your parameter set is limited and known at compile time, use enum .

If your parameter set is open and does not appear at compile time, use strings.

+12
source share

Just because you declare a public final String as something that you expect to pass to a method as a parameter, nothing prevents me from passing anything I like.

Using enum means that I cannot create my own access object, protecting both sides of the problem. The only time I can think that you should use constant strings instead of enumerations is if you need to give the user the opportunity to extend your method to enable user functionality ...

+5
source share

If you mean System.setProperty (), System.getProperty () or System.getenv (), I think the lines are suitable here, since the set of possible keys is open. The key parameter corresponds to the actual value of the text / string type in some file or somewhere is stored somewhere.

If you have a private key set, I think that enumerations will be very preferable.

+4
source share

I learned the "method of least surprise." Instinctively, using an enumeration, this is correct. So I would go for it. I'm sure Java developers think alike.

Edit : Great POLS explanation: http://benpryor.com/blog/2006/06/29/api-design-the-principle-of-least-surprise/

+3
source share

Although using enumerations is type safe, the need to convert an enumeration to a string and vice versa is quite common. And there is no built-in function to do this in Java. And you will end up using valueOf () and toString (). And using this approach will not be much different than using just strings. Because you will need to handle situations where a string cannot be converted to Enum.

Thus, just using static end lines is easy and is common practice, AFAIK.

For example, you will want to interact with the server using some API. You will need to define each method and answer as Enum. And then you will need to add the toString and valueOf methods. Why not just use String?

+1
source share

Using strings in existing APIs is good practice; it is a bad practice to change APIs just because Java now supports enumerations. For the new APIs, I agree with what everyone else has said.

0
source share

All Articles