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?
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.
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?
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
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 enum
s 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...
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.
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/
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