Skip to content

Instantly share code, notes, and snippets.

@loverdos
Created October 21, 2011 17:57
Show Gist options
  • Save loverdos/1304492 to your computer and use it in GitHub Desktop.
Save loverdos/1304492 to your computer and use it in GitHub Desktop.
Logger with Boolean result on logging methods
// 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(...)
}
@gousiosg
Copy link

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

DBG && logger.debug(...)

when you can perform the test in the debug method?

@loverdos
Copy link
Author

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).

@ittayd
Copy link

ittayd commented Oct 22, 2011

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

@loverdos
Copy link
Author

@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