Created
October 21, 2011 17:57
-
-
Save loverdos/1304492 to your computer and use it in GitHub Desktop.
Logger with Boolean result on logging methods
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// With Boolean as a return type you get nice compose-ability semantics. | |
// With Unit (void for Java) return type, you only get ugly if()s. | |
trait Logger { | |
def isDebugEnabled: Boolean | |
def isInfoEnabled: Boolean | |
def debug(...): Boolean | |
def info(...): Boolean | |
} | |
class LoggerImpl { | |
def debug(...) = { | |
// do whatever | |
false | |
} | |
} | |
class ClientCode { | |
val DBG = logger.isDebugEnabled // make it false/true if you like | |
// instead of this: | |
if(logger.isDebugEnabled) logger.debug(...) | |
// do this: | |
DBG && logger.debug(...) | |
} |
Well, if I'd have to write those isDebugEnabled() calls, I'd prefer the Booleans instead. :)
Also, let's have in mind all those string concatenations or varargs array creation that may happen in order to finally do the actual call (depending on the logging framework, the developer etc).
Why not use call by name?
def debug(msg: => String) = if (isDebugEnabled) doActualLogging(msg)
Then the price for calling debug is the creation of a function object and the call itself
@ittayd Yes I am aware of the the by-name approach. The initial motivation was an attempt to get rid of IMO ugly if().
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
IMO, the client should never test whether the debug mode is enabled in order to print a debug message. A method call is quite cheap in the JVM, so why polute the code with statements like
when you can perform the test in the debug method?