Reputation: 6546
public String getPreviewMessageForWebdavResponse(){
String format="<preview><currentNumber>%d</currentNumber><totalNumber>%d</totalNumber></preview>";
return String.format(format, currentNumber,totalNumber);
}
Sometimes, I encounter a string. I can't judge if it needs to be a constant or local var. The String is only used once in the method and need not be exposed outside the method.
How to choose?
Upvotes: 1
Views: 2096
Reputation: 262464
Your question is a bit unclear. I will answer the three possible question that come to mind:
(all of them are questions of style only).
Should I use a variable at all, or just inline the String literal into the one place it is used?
I'd say, at least in your case, where the sheer length of the String suggests this, keep it as a variable with a descriptive name, and keep it at the top of the method. Makes it easier to find and update later if necessary, makes it easier to refactor if you do need it more than once later, makes it easier to read.
Should the variable be local and final?
Should it be a class-level constant (
static final
)?
Always keep scope and visibility as limited as possible.
If it is only used in the one method, keep it in the method.
If it is used in multiple methods in the same class, make it private static final
.
If it is used in multiple places in the same package, make it static final
.
If it is used throughout the project, only then make it public
.
Upvotes: 3