11

I've been reading through the details of the System libraries set and get methods yet the parameters are usually Strings.

Would you consider the use of String as parameters bad practise since the inclusion of enum?

A better alternative at minimum might be public final String, No?

4

7 回答 7

23

I would consider Enums to be a better approach than Strings. They are type safe and comparing them is faster than comparing Strings.

As a pre Java 1.5 alternative you could use the type-safe enum pattern suggested by Joshua Bloch in his book Effective Java. For type-safe enums see also http://www.javacamp.org/designPattern/enum.html

于 2008-11-10T08:44:55.123 回答
15

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

If your set of parameters is open and unkown at compile time, use strings.

于 2008-11-10T09:50:38.377 回答
6

Just because you declare a public final String as something you expect to have passed into a method as a parameter, there's nothing stopping me from passing in anything I like.

Using enums means that I can't create my own object to pass in, protecting both sides of the issue. The only time I can think you should be using constant Strings in lieu of enums is if you need to allow room for the user to extend your method to enable custom functionality...

于 2008-11-10T08:46:45.727 回答
4

If you're referring to System.setProperty(), System.getProperty(), or System.getenv(), I think Strings are appropriate here since the set of possible keys is open. The key parameter corresponds to an actual text/string type value in some file or store somewhere.

If you have a closed set of keys, I think enums would be much preferred.

于 2008-11-10T08:47:46.520 回答
4

Although using enums is type safe, the need of converting enum to string and vice versa is quite frequent. And there is no built-in feature to do that in Java. And you'll eventually end up with using valueOf() and toString(). And using that approach will be no much different from using just strings. Because you'll need to handle situations where string can not be converted to Enum.

So just using static final strings is easy and is a common practice, AFAIK.

For example, you'll want to interact with a server using some API. You'll need to define every method and a response as Enum. And then you'll need to add toString and valueOf methods. Why just not use String?

于 2011-04-21T19:30:40.447 回答
3

I've learned the "method of least surprise". Instinctively, using enum is the right thing. So i would go for it. I'm sure the Java makers think alike.

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

于 2008-11-10T08:45:23.280 回答
0

Usage of strings in existing APIs is not bad practice; it is bad practice to change the APIs just because Java has now support for enums. For new APIs, I agree with what everybody else said.

于 2008-11-10T08:47:52.980 回答