I had implemented a logging function as following:
void log (String output)
{
if(debug)
{
String val = <some string captured>;
Log.write("Logging: " + val + output, this.handle);
}
}
This log is used at several places as,
log("value is " + str + " " + val); // 'str','val' can be a string or class with '.toString()'
log("error: " + e1 + ". Exiting."); // 'e1' can be a class with overloaded '.tostring()'
Now, the problem is (got as code review comments), the class object to string conversion will happen even if debug condition is not ON. At several places, this will lead to unwanted performance downgrade.
I don’t want to clutter my code by putting that if() condition everywhere where only output matters and rest of the things are repeated. What is the best way of solving this problem using Java facilities?
I thought of using generics:
<T> void log (String output, T arg)
{
if(debug)
{
String val = <some string captured>;
Log.write("Logging: " + val + output + arg.toString(), this.handle);
}
}
Will this approach make a good optimization ? Also, can I elegantly extend this generic function to take multiple arguments ?
Actually, you don’t even need generics – you can use
Object:For multiple objects you can use varargs and
MessageFormat, for example, as follows:.