I am playing around with Scala right now and tried to figure out some best practices about how to design classes. (Trying Scala since a week or so.)
Since my Erlang time I am a huge fan of message passing and actor based software. In most Scala examples actor classes are implemented like this:
object Foo
object Bar
class MyActor extends Actor {
def receive = {
case Foo => ...
case Bar => ...
case _ => ...
}
}
But what I learned from my object oriented (interfaces and polymorphism) carrier tells me that this concept is not very flexible.
MyActor could be replaced by MyAdvancedActor but there is no contract which defines which messages an MyActor implementation needs to implement.
When I think about writing Actors in Scala I tend to write a trait which specifies some methods. The MyActor implementation needs to implement this methods in which the can send its own private messages to itself.
With this approach we have a specified interface and can replace the MyActor implementation in a type-safe manner.
In my time of reading scala tutorials and examples I did not come across such an class design. Is it not common sense or are there better ways in doing this in Scala? Or are these tutorials just to small to cover such a topic?
Common practice is to use an algebraic data type in such cases: you could create a sealed base type for all messages like this:
sealed trait MyActorMessages
object Foo extends MyActorMessages
object Bar extends MyActorMessages
But this kind of contract is not enforced by compiler. You could use use Typed Channels to enforce this contract:
class MyActor extends Actor with Channels[TNil, (MyActorMessages, MyActorReply) :+: TNil] {
channel[MyActorMessages] { (req, snd) ⇒
req match {
case Foo ⇒ ...
case Bar ⇒ ... // You'll get a warning if you forget about `Bar`
}
}
}
Compiler will force you (with warning) to process all possible message types (in this case all subtypes of MyActorMessages), and senders will be forced to send only valid messages using <-!- method (with compilation error).
Note that senders can also use unsafe method ! to send invalid messages.
I really like the solution from #senia. It's an effective use of Akka's new Typed Channels feature. But if that solution does not suit you, I can offer something a bit more traditional to the OO world. In this solution you specify the actual message handling behavior for the actor via a strategy implementation that the actor is constructed with. The code would look something like this:
//Strategy definition
trait FooStrategy{
def foo1(s:String):String
def foo2(i:Int):Int
}
//Regular impl
class RegularFoo extends FooStrategy{
def foo1(s:String) = ...
def foo2(i:Int) = ...
}
//Other impl
class AdvancedFoo extends FooStrategy{
def foo1(s:String) = ...
def foo2(i:Int) = ...
}
//Message classes for the actor
case class Foo1(s:String)
case class Foo2(i:Int)
//Actor class taking the strategy in the constructor
class FooActor(strategy:FooStrategy) extends Actor{
def receive = {
case Foo1(s) => sender ! strategy.foo1(s)
case Foo2(i) => sender ! strategy.foo2(i)
}
}
Then to create instances of this actor:
val regFooRef = system.actorOf(Props(classOf[FooActor], new RegularFoo))
val advFooRef = system.actorOf(Props(classOf[FooActor], new AdvancedFoo))
One benefit here is that you are decoupling the business logic of the actor from it's normal message handling behavior. You are letting the actor class just do actor stuff (receive from mailbox, reply to sender, etc...) and then the real business logic is encapsulated in a trait. This also makes it much easier to test the business logic in isolation with unit tests for the trait impls. If you needed actor type stuff in the trait impls, then you could always specify an implicit ActorContext to the methods on FooStrategy, but then you would lose the complete decoupling of actor and business logic.
Like I said earlier, I like the solution from #senia; I just wanted to give you another option that might be more traditional OO.
Related
I wrote an Akka base-actor that can handle some common messages. I want to reuse this basic behavior in a sub-actor, by extending the base-actor (not by composition of the base-actor).
I have seen several approaches in previous questions. They are all valid but also may be improved:
How extend behaviour of super actor in akka
and
How do I best share behavior among Akka actors?
To make the implementation cleaner, I am trying to achieve the following:
When defining the sub-actor, I try to extend only the base-actor (not both Actor and sub-actor). However, I was not able to force the compiler to do this.
I also try to not rename the receive partial function, because it is a kind of convention.
Here is a sample of my implementation:
//This is the base-actor that implements the common behavior
trait BetterActor extends Actor {
abstract override def receive = {
super.receive orElse { case _ => println("Missing pattern!") }
}
}
//This is the actor that implements the additional behavior.
//I actually wanted to extend BetterActor. It was not possible.
class MyActor extends Actor {
def receive = {
case i: Int =>
println(s"Yay!!! Got $i")
}
}
Here are two alternative ways how I can create an instance of the sub-actor, which combines both the common and the additional behaviors:
//1.
val myBetterActor = system.actorOf(Props(new MyActor with BetterActor), "myBetterActor")
//2.
class MyBetterActor extends MyActor with BetterActor
val myBetterActor = system.actorOf(Props[MyBetterActor], "myBetterActor")
Finally, I may invoke the sub-actor by:
myBetterActor ! 2
myBetterActor ! "a"
Problems with my implementation:
When I create an instance of the sub-actor, only then I can mix in the base-actor, either directly (1) or by defining a new class that mixes in the base-actor.
Like I said before, I would prefer to mix in the base-actor when I define the sub-actor. Not when I try to create an instance of the sub-actor.
P.S. It's fascinating that the designers of this framework did not see it necessary to make this common requirement easy to accomplish.
i suppose as long as you're not trying to override behavior with BetterActor, you could try something like this:
trait BetterActor extends Actor {
override def unhandled(message: Any): Unit = message match {
case e: CommonMessage => println("COMMON!")
case e => super.unhandled(e)
}
}
class MyActor extends BetterActor {
override def receive = {
case i: Int => println(s"Yay!!! Got $i")
}
}
The Akka Typed Actors documentation states that it will be superseded by Akka Typed. I am inferring from this that Akka Typed can be used to implement the Active Object pattern; but it is not too clear to me how. Here is my attempt so far; I'm aware it stinks :D
object HelloWorld {
final case class Greet(whom: String, replyTo: ActorRef[Greeted])
final case class Greeted(whom: String)
private val greeter = Static[Greet] { msg ⇒
println(s"Hello ${msg.whom}!")
msg.replyTo ! Greeted(msg.whom)
}
private val system = ActorSystem("HelloWorld", Props(greeter))
def greet(whom: String): Future[Greeted] = system ? (Greet(whom, _))
}
Cheers
The Active Object Pattern as defined by the page you link to is not desirable for all the reasons why TypedActors are being removed: the fact that a method is executed asynchronously is so important that it should not be hidden by technologies like proxy objects that implement normal interfaces. Instead, Akka Typed allows you to write nearly the same code as if it was an Active Object while retaining the asynchronous marker: instead of selecting a method with the . syntax you send a message using ? (or ! if the protocol is not simple request–response). Your example would look like this:
object HelloWorld {
final case class Greet(whom: String)(replyTo: ActorRef[Greeted])
final case class Greeted(whom: String)
val greeter = Static[Greet] { msg ⇒
println(s"Hello ${msg.whom}!")
msg.replyTo ! Greeted(msg.whom)
}
}
object Sample extends App {
import HelloWorld._
val system = ActorSystem("HelloWorld", Props(greeter))
val fg = system ? Greet("John")
}
Please note that creating a separate thread (or ActorSystem) per object may sound okay as per the classical pattern, but doing that foregoes many of the benefits of a message-driven architecture, namely that many Actors can share the same resources for more efficient execution and they can form supervision hierarchies for principled failure handling etc.
This is an continuation of my previous question How do I get around type erasure on Akka receive method
I have 10 type of events which extends from Event that I need to handle.
I want to implement business logic for each event in separate trait, because because mixing all 10 event handler functions will produce several hundreds(if not thousands) lines of code.
I don't want to create different Actor types for each event. For example:
class Event1Actor extend Actor{
def receive ={
case Event1(e) => //event1 Business Logic
}
}
class Event2Actor extend Actor{
def receive ={
case Event2(e) => //event2 Business Logic
}
}
and the same Event3Actor, Event4Actor,etc....
Such code seems ugly to me, because I need to implement business Logic inside each Actor.
Implementing 10 different traits and 10 different Actor classes seems also as bad design.
I'm seeking for some kind generic solution based on design pattern, for example strategy pattern.
case class EventOperation[T <: Event](eventType: T)
class OperationActor extends Actor {
def receive = {
case EventOperation(eventType) => eventType.execute
}
}
trait Event {
def execute //implement execute in specific event class
}
class Event1 extends Event {/*execute implemented with business logic*/}
class Event2 extends Event {/*execute implemented with business logic*/}
hope this is what you are looking for and helps, I have used this patternt to remove the redundant amount of actors wrapping all actions under a single actor executing different type of events.
You could try something like this, which involves auto-composing receive functionality via a base trait. First the code:
case class Event1(s:String)
case class Event2(i:Int)
case class Event3(f:Float)
trait EventHandlingActor extends Actor{
var handlers:List[Receive] = List.empty
override def preStart = {
val composedReceive = handlers.foldLeft(receive)((r,h) => r.orElse(h))
context.become(composedReceive)
}
def addHandler(r:Receive) {
handlers = r :: handlers
}
def receive = PartialFunction.empty[Any,Unit]
}
trait Event1Handling{ me:EventHandlingActor =>
addHandler{
case Event1(s) => println(s"${self.path.name} handling event1: $s")
}
}
trait Event2Handling{ me:EventHandlingActor =>
addHandler{
case Event2(i) => println(s"${self.path.name} handling event2: $i")
}
}
trait Event3Handling{ me:EventHandlingActor =>
addHandler{
case Event3(f) => println(s"${self.path.name} handling event3: $f")
}
}
So you can see in the EventHandlingActor trait we set up a List of type Receive that can be added to by each specific handling trait that we stack into a concrete actor. Then you can see the definitions of the handling functionality for each event defined in a separate trait that is calling addHandler to add another piece of handling functionality. In preStart for any kind of EventHandlingActor impl the receive functions will be composed together with receive being the starting point (empty by default) before hot-swapping out the receive impl with context.become.
Now for a couple of impl actors as an example:
class MyEventHandlingActor extends EventHandlingActor
with Event1Handling with Event2Handling with Event3Handling
case class SomeOtherMessage(s:String)
class MyOtherEventHandlingActor extends EventHandlingActor with Event1Handling{
override def receive = {
case SomeOtherMessage(s) => println(s"otherHandler handling some other message: $s")
}
}
The first one only handles events, so all it needs to do is define which ones it handles my mixing in the appropriate traits. The second one handles one type of event but also some other message that is not an event. This class overrides the default empty receive and provides functionality to handle the non-event message.
If we tested the code like so:
val system = ActorSystem("test")
val handler = system.actorOf(Props[MyEventHandlingActor], "handler")
handler ! Event1("foo")
handler ! Event2(123)
handler ! Event3(123.456f)
val otherHandler = system.actorOf(Props[MyOtherEventHandlingActor], "otherHandler")
otherHandler ! Event1("bar")
otherHandler ! SomeOtherMessage("baz")
Then we would see output similar to this (with the order changing due to asynch handling of messages):
otherHandler handling event1: bar
handler handling event1: foo
handler handling event2: 123
handler handling event3: 123.456
I'm using cake pattern in Scala 2.10 to inject required trait to my actor acording to some bussiness logic:
I have several types f Events:
sealed abstract class Event(val timeStamp:Long)
case class StudentEvent(override val timeStamp:Long, studentId:Long) extends Event(timeStamp:Long)
case class TeacherEvent(override val timeStamp:Long, teacherIdId:Long) extends Event(timeStamp:Long)
Now I have traits which implement action for each type of event:
Abstract:
trait Action[T <: Event] {
def act[T](event:T):Unit
}
And two impls:
trait StudentAction extends Action[StudentEvent]{
override def act[StudentEvent](event:StudentEvent):Unit = println(event)
}
and
trait TeacherAction extends Action[TeacherEvent]{
override def act[TeacherEvent](event:TeacherEvent):Unit = println(event)
}
Now my Actor:
class ActionActor[T <: Event] extends Actor{
self:Action[T]=>
override def receive= {
case msg: T => act(msg)
case _ => println("Unknown Type")
}
}
And I inject required trait this way:
val actionActor = system.actorOf(Props(new ActionActor[StudentEvent] with StudentAction))
actionActor ! StudentEvent(1111L,222L)
On compile I'm getting error:
Warning:(14, 14) abstract type pattern T is unchecked since it is eliminated by erasure
case msg:T => act(msg)
^
I know that somehow I need to use TypeTag, but I failed to understand how can I do it.
Please help.
Update:
In reality, I have 10 type of events which extends from Event that I need to handle.
I want to implement business logic for each event in separate trait, because because mixing all 10 event handler functions will give me several hundreds(if not thousands) lines of code.
I don't want to create different Actor types for each event. For example:
class Event1Actor extend Actor{
def receive ={
case Event1(e) => //event1 Business Logic
}
}
class Event2Actor extend Actor{
def receive ={
case Event2(e) => //event2 Business Logic
}
}
and the same Event3Actor, Event4Actor,etc....
Such code seems ugly to me, because I need to implement business Logic inside each Actor.
I'm seeking for some kind generic solution based on design pattern, for example strategy pattern.
First, I would suggest defining your events as:
sealed trait Event { def timeStamp: Long }
case class StudentEvent(timeStamp: Long, studentId: Long)
extends Event
case class TeacherEvent(timeStamp: Long, teacherId: Long)
extends Event
This is the standard encoding for algebraic data types.
Second, this business where you're using a self-type seems really confusing to me. Surely the same object shouldn't be both an "actor" and an "action"? Why not use composition here instead of inheritance? (It kinda feels like you're just throwing Scala features together. So a general piece of advice here would be: slow down.)
But to address your main question, I think you're fundamentally on the wrong path. Almost any time you end up butting heads with type erasure and/or TypeTag, it's a sign that your design is flawed and you should back up and rethink — unless you realllllllly know what you're doing.
In any case, you're not going to be able to get Akka to attach a TypeTag to your messages. Akka just doesn't work that way. (There have been a series of efforts to add "typed actors" or "typed channels" to Akka, and you might look those up, but it's probably overkill in your use case unless you're realllllly sure it isn't.)
What is the underlying architectural problem that you're trying to solve here? What motivated this design?
Check out Composing trait behavior in Scala in an Akka receive method, it seems really similar, and after digesting it, I think you'll be in a better position to decide what to do next.
I noticed it is legal to write this scala code:
val fussyActor = actor {
loop {
receive {
case s: String => println("I got a String: " + s)
case _ => println("I have no idea what I just got.")
}
}
}
I know from documentation that actor is a trait, which has loop and receive value members. But how is it possible to stack these methods like above? Is it implementing or overriding these methods? I am quite confused at this syntax. Please provide some good references/pointers.
First, a standard disclaimer. Scala Actors have been deprecated in favor of Akka Actors. If you want to continue down the path of learning to use Actors with Scala, you should look into Akka instead of researching Scala Actors.
Now, about your question. There are a couple of things in play here, so let's first start out with what you need to do in order to define a new Scala Actor. If you look at the Scala Actor trait, you see that there is one abstract method that you must provide called act():Unit. This is a method that takes no inputs and returns no inputs. It defines the actors behavior. So in it's simplest form, a custom Scala Actor could be:
class MyActor extends Actor{
def act(){
}
}
Now this not a very interesting actor as it does nothing. Now, one way to provide behavior is to invoke the receive method, providing a PartialFunction[Any,R] where R is a generic return type. You could do that like so:
class MyActor extends Actor{
def act(){
receive{
case "foo" => println("bar")
}
}
}
So now if this actor receives a message "foo", it will print "bar". The problem here is that this will only happen for the first message and then won't do anything after. To fix that. we can wrap our call to receive with a call to loop to make it continue to do the provided receive call for each received message:
class MyActor extends Actor{
def act(){
loop{
receive{
case "foo" => println("bar")
}
}
}
}
So this is now starting to look like your example a bit more. We are leveraging the loop and receive methods that come with the Actor trait in order to give this actor behavior. Lastly, instead of defining an explicit class as my actor, I can define one on the fly with the actor method on the Actor companion object. That method takes a function body that will be used as the act impl like this:
def actor(body: => Unit){
val a = new Actor {
def act() = body
override final val scheduler: IScheduler = parentScheduler
}
}
So in your example, you are creating a new actor implementation on the fly and providing an impl for act that will loop and call receive continually with the partial function you supplied for message handling.
Hopefully this clarifies things a bit. The only method you are "overriding" (providing an impl for) is act. When you see loop and receive, those are not overrides; they are simply calls to those existing methods on the Actor trait.
Actually it's illegal without import Actor._.
Your code without that import:
val fussyActor = Actor.actor {
Actor.loop {
Actor.receive { ... }
}
}
actor, loop and receive are methods of object Actor.
def actor(body: ⇒ Unit): Actor
def loop(body: ⇒ Unit): Unit
def receive[A](f: PartialFunction[Any, A]): A
Method actor accepts by-name Untit parameter body - some code block to execute in separate thread and creates an Actor with act method implemented using parameter body.
Method loop accepts by-name Untit parameter body - some code block to execute in infinite loop.
Method receive accepts PartialFunction as parameter f and calls f with message as parameter. It takes message from actor associated with current thread.
Note that scala actors are deprecated, you should use akka actors. See The Scala Actors Migration Guide.