How to handle cross cutting concerns the Scala way
Asked Answered
T

1

8

I am reading online about cross cutting concerns since I just implemented Log4j into my code. Some people are saying using AspectJ is okay, while others point out that it breaks functional programming. That mixins are Scala's solution for cross cutting concerns.

However, I cringe when I think I will extend a trait to an object/ class that is not related itself.

e.g. new Database with Logger

Here Logger has nothing to do with Database, but its how to mixing to provide logging. I would prefer to do it the Scala way, so I want to find out this is what people mean by mixins.

Can someone please show me a quick example of how to go about this in Scala?

Twoup answered 18/4, 2015 at 6:35 Comment(0)
B
5

This is a big topic with lots of potential "correct" answers. My personal favourite would be using either "by name parameters" or higher order functions.

A a very simple example of this:

object Logging {
  def logCall[T](name: String)(block: => T): T = {
    log.info(s"Invoking: $name")
    block
  }
}

Which would allow you to apply it both in an object that itself knows about the cross cutting concern (something like annotating wrapping a method call with something in java):

class DB {
  import Logging._
  def insert(item: Something) = logCall("insert") {
    ???
  }
}

Or at the call site:

import Logging._
def businessLogic() {
  val user = ???
  val result = logCall("insert user")(DB.insert(user))
  println(result)
}

The nice thing with this is that it is very explicit and self explanatory (which, again, are things you might value high or not).

Bung answered 18/4, 2015 at 10:50 Comment(2)
This is the same as having a global variable in Java. And would negate the purpose of dependency injection.Twoup
It most definitely is not the same thing as having a global variable in Java, if you have dependencies that you want to be available in the cross cutting concern you can pass those as regular or implicit parameters to the cross cutting method. There is nothing requirement Logging to be a singleton, it was only done that way to make the code sample brief (and because since you seldom would inject a logger).Bung

© 2022 - 2024 — McMap. All rights reserved.