We're implementing an adapter for Jaxen (an XPath library for Java) that allows us to use XPath to access the data model of our application.
This is done by implementing classes which map strings (passed to us from Jaxen) into elements of our data model. We estimate we'll need around 100 classes with over 1000 string comparisons in total.
I think that the best way to do this is simple if/else statements with the strings written directly into the code — rather than defining each strings as a constant. For example:
public Object getNode(String name) {
if ("name".equals(name)) {
return contact.getFullName();
} else if ("title".equals(name)) {
return contact.getTitle();
} else if ("first_name".equals(name)) {
return contact.getFirstName();
} else if ("last_name".equals(name)) {
return contact.getLastName();
...
However I was always taught that we should not embed string values directly into code, but create string constants instead. That would look something like this:
private static final String NAME = "name";
private static final String TITLE = "title";
private static final String FIRST_NAME = "first_name";
private static final String LAST_NAME = "last_name";
public Object getNode(String name) {
if (NAME.equals(name)) {
return contact.getFullName();
} else if (TITLE.equals(name)) {
return contact.getTitle();
} else if (FIRST_NAME.equals(name)) {
return contact.getFirstName();
} else if (LAST_NAME.equals(name)) {
return contact.getLastName();
...
In this case I think it's a bad idea. The constant will only ever be used once, in the getNode()
method. Using the strings directly is just as easy to read and understand as using constants, and saves us writing at least a thousand lines of code.
So is there any reason to define string constants for a single use? Or is it acceptable to use strings directly?
PS. Before anyone suggests using enums instead, we prototyped that but the enum conversion is 15 times slower than simple string comparison so it's not being considered.
Conclusion: The answers below expanded the scope of this question beyond just string constants, so I have two conclusions:
- It's probably OK to use the strings directly rather than string constants in this scenario, but
- There are ways to avoid using strings at all, which might be better.
So I'm going to try the wrapper technique which avoids strings completely. Unfortunately we can't use the string switch statement because we're not on Java 7 yet. Ultimately, though, I think the best answer for us is to try each technique and evaluate its performance. The reality is that if one technique is clearly faster then we'll probably choose it regardless of its beauty or adherence to convention.
switch
labels. Use a switch instead ofif
cascades.