patternjavaMinor
Configuring toString via a public static variable
Viewed 0 times
publicviavariableconfiguringtostringstatic
Problem
Sometimes I need
Is there any better solution?
toString() to be quite verbose, normally I don't. It can't be nicely solved by using other methods as toString() is what gets shown in debugger (and also in the logs unless I call some method explicitly). As nobody should ever rely on its behavior, I wonder if the following is acceptablepublic static boolean volatile verboseToString;
public String toString() {
return toString(verboseToString);
}
public String toString(boolean verbose) {
if (verbose) {
return longDescription();
} else {
return shortDescription();
}
}Is there any better solution?
Solution
You could try to use Logger level to control verbose mode.
Advantage of this approach is that it's easier to control toString() verbosity level - simply by config file for you logging framework, JMX extension, ...
This could also give you more flexibility - based on log level (INFO, DEBUG, TRACE), your could control how much information you put into toString().
public String toString() {
return toString(logger.isDebugEnabled());
}
public String toString(boolean verbose) {
if (verbose) {
return longDescription();
} else {
return shortDescription();
}
}Advantage of this approach is that it's easier to control toString() verbosity level - simply by config file for you logging framework, JMX extension, ...
This could also give you more flexibility - based on log level (INFO, DEBUG, TRACE), your could control how much information you put into toString().
Code Snippets
public String toString() {
return toString(logger.isDebugEnabled());
}
public String toString(boolean verbose) {
if (verbose) {
return longDescription();
} else {
return shortDescription();
}
}Context
StackExchange Code Review Q#16071, answer score: 6
Revisions (0)
No revisions yet.