I have a static StringWriter variable in a web application's Handler class, used by multiple private methods in the class. Each method appends a String to this variable, and finally the StringWriter writes the concatenated String to file. But while testing the web app I realized that the StringWriter was still holding the values from the all the previous tests. I used the answer from this question (How do you "empty" a StringWriter in Java?) as a workaround, but I feel this isn't correct in terms of design pattern and security.
Is it correct? Is there a better way?
public class BaseHandler {
private static StringWriter sw = new StringWriter();
public static void writeToFile(){
firstMethod();
secondMethod();
finalMethod();
}
private static void firstMethod(){
sw.append("Pandora's");
}
private static void secondMethod(){
sw.append("Box");
}
private static void finalMethod(){
sw.append("!");
//sw writes value to file
...
sw.getBuffer().setLength(0);
}
}
I would ask myself, do I need a BaseHandler which hold state? Now your handler is holding a state in the sw
field, but if you don't need this state then you don't create a field.
For example you can do this:
public class BaseHandler {
public static void writeToFile(){
StringWriter sw = new StringWriter();
firstMethod(sw);
secondMethod(sw);
finalMethod(sw);
}
private static void firstMethod(StringWriter sw){
sw.append("Pandora's");
}
private static void secondMethod(StringWriter sw){
sw.append("Box");
}
private static void finalMethod(StringWriter sw){
sw.append("!");
//sw writes value to file
...
}
}
Exiting writeToFile the StringWriter is marked for garbage collection.