Flexibility of Scala's Actor Model - scala

I've been using actor based programming model with Microsoft's Asynchronous Agents library for C++.
Having started experimenting with Scala, it seems to me that its model is not that rich as in Asynchronous Agents. For example Async Agent provides a lot of different Asynchronous Message Blocks which can be combined in different ways to make network of agents.
How does this map to Scala's native actors, or actors using Akka?

Scala has something called a "case class" that can be used to define any number of message types. As for behaviors, that is what actors are for. The things defined here http://msdn.microsoft.com/en-us/library/dd504833.aspx all sound like behaviors to me, and most would be simple to implement with an actor.

Related

What are the differences between the Command Dispatcher and Mediator Design Pattern?

Recently I've been introduced to the Command Dispatcher Pattern which could help the commands to be decoupled from the command handlers in our project that's based on the Domain-Driven Design approach and CQRS pattern.
Anyway, I'm confused it with the Mediator design pattern.
Robert Harvey has already answered a question about the Command Dispatcher pattern as following:
A Command Dispatcher is an object that links the Action-Request with
the appropriate Action-Handler. It's purpose is to decouple the
command operation from the sending and receiving objects so that
neither has knowledge of the other.
According to the Wikipedia, The mediator pattern is described as:
With the mediator pattern, communication between objects is
encapsulated within a mediator object. Objects no longer communicate
directly with each other, but instead communicate through the
mediator. This reduces the dependencies between communicating objects,
thereby reducing coupling.
So, as my understanding both of them are separating the command form the commander which allow us to decouple from the caller.
I've seen some projects on Github that are using the Command Dispatcher Pattern to invoke the desired handler for the requested command while the other ones are using mediator pattern to dispatch the messages. (E.g. in most of the DotNet projects, the MediatR library is used to satisfy that).
However, I'd like to know what are the differences and benefits of using one pattern than another in our project that is based on the DDD approach and CQRS pattern?
The Command Dispatcher and Mediator patterns (as well as the Event Aggregator Pattern) share similarities in that they introduce a mediating component to decouple direct communication between components. While each can be used to achieve use cases for which the other pattern was conceived, they are each concrete patterns which differ in their original targeted problems as well as the level to which they are suited for each need.
The Command Dispatcher Pattern is primarily a convention-over-configuration approach typically used for facilitating UI layer calls into an Application Layer using discrete types to handle commands and queries as opposed to a more traditional Application Service design. When representing the queries and commands that might typically be represented in a course-grained service (e.g. OrderService) as discrete components (e.g. CreateOrderCommand, GetOrderQuery, etc.), this can result in quite a bit of noise in UI-level components such as ASP.Net MVC Controllers where a constructor might otherwise need to inject a series of discrete interfaces, only one of which would typically be needed for each user request (e.g. Controller Action). Introducing a dispatcher greatly reduces the amount of code needed in implementing components such as ASP.Net MVC Controllers since the only dependency that need be injected is the dispatcher. While not necessarily a primary motivation of the pattern, it also introduces the ability to uniformly apply other patterns such as Pipes and Filters, and provides a seam where command handler implementations can be determined at run time. The MediatR library is actually an implementation of this pattern.
The Mediator Pattern concerns the creation of mediating components which encapsulate domain-specific orchestration logic that would otherwise require coupling between components. That is to say, the mediating component in this case isn't just a dumb dispatcher ("Hey, anybody know how to handle an XYZRequest?"), but is purpose-built to follow a specific set of operations that need to occur when a given operation happens, potentially across multiple components. The example given in the GoF Design Patterns book is a UI component with many interconnected elements such that changes to one need to effect changes to a number of other components and vice-versa (e.g. typing into a text field causes changes to a drop-down and multiple check boxes and radio buttons, while selecting entries within the dropdown effect changes to what's in the text field, check boxes, and radio buttons, etc.). With the provided solution, a mediating component contains logic to know exactly which components need to get updated, and how, when each of the other components change.
So, the Mediator Pattern would be used when you need a component custom-built to facilitate how a number of other components interact where normal coupling would otherwise negatively affect maintainability whereas the Command Dispatcher Pattern is simply used as a dumb function router to decouple the caller from the called function.
Mediator pattern is more low level and generic in its pure concept. Mediator pattern does not define the kind of communication or the kind of message you use. In Command Dispatcher you are in a upper layer (contextually and conceptually) in which the kind of communication and message is already defined.
You should be able to implement a Command Dispatcher patter with a Mediator pattern (ergo with MediatR) as foundation.

Scala Actors - any suggestions when converting OOP based approach?

I'm learning Scala and its Actors (via Akka lib) approach for handling concurrency. I'm having some questions while trying to convert typical OOP (think - Java style OOP) scenarios to Actor based ones.
Let's consider the overused e-commerce example Webstore where Customers are making Orders that contain Items. If it is simulated in OOP-style you end up with appropriately named domain model classes that interact between themselves by calling methods on each other.
If we want to simulate concurrency e.g. many customers buying items at once we throw in some sort of threading (e.g. via ExecutorService). Basically each Customer then implements Runnable interface and its run() method calls e.g. shop.buy(this, item, amount). Since we want to avoid data corruption caused by many threads possibly modifying shared data at once, we have to use synchronization. So the most typical thing to do is synchronize the shop.buy() method.
Now let's move on to Actor based approach. What I understand is that Shop and each Customer now become Actors who, instead of calling buy() method on shop directly, sends message to shop. But here come the difficulties.
Should all the other domain models (Order, Item) become Actors too and all the communication between all the domain models be message driven? In other words it is a question whether it is OK or not to leave some OOP style interaction between domain models via method invoking. For example, in OOP based approach Order would typically have a reference to List which you could populate when user is buying something by calling add(item) in buy() method. Does this (and similar) interactions have to be remodeled by messaging to make most use of Actor based approach? In yet another words it is a question when do we communicate with internal state of an actor directly and when do we extract internal state to another Actor?
In OOP based solution you pass to methods instances of classes. I read in documentation that in Actor model one is supposed to pass immutable messages. So if I understand correctly, instead of messaging objects themselves you message only some data that makes it possible to identify which entities have to be processed e.g. by messaging their IDs and the type of action you want to perform.
Answering your questions:
2) Your domain model (including shops, orders, buyers, sellers, items) should be described with immutable case classes. Actors should exchange (immutable) commands, which may use these classes, like AddItem(count: Int, i: Item) - AddItem case class represents command and encapsulates business entity called Item.
1) Your protocol, e.g. interaction between shops, orders, sellers, buyers etc., should be encapsulated inside actor (one actor class per protocol, one instance per state). Simply saying, an actor should manage any (mutable) state, changing between requests, like current basket/order. For instance, you may have actor for every basket, which will contain information about choosed items and receive commands like AddItem, RemoveItem, ExecuteOrder. So you don't need actor for every business entity, you need actor for every business process.
In addition, there is some best practices and also recommendations about managing concurrency with routers.
P.S. The nearest JavaEE-based approach is EJB with its entities (as case-classes) and message-driven beans (as actors).

Functional programming equivalents for the following [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I am trying to make the leap from functional programs for "hello world" equivalents to more real-world applications.
As I come from a Java world and have been exposed to all it's design patterns, my modeling process is still very Java oriented (e.g. I think in terms of *Managers, *Factory, *ClientFactory, *Handler etc.)
Changing my thought process in one shot, will be hard so I was hoping to get some pointers on how the following scenarios (described in a OO way) would be modeled in a functional language.
Examples in a functional language like Clojure/Haskell (or perhaps a hybrid like Scala) would be helpful.
Stateless Request handlers
E.g. is a Servlet. It is essentially a request handler with methods like doGet, doPost. How would one model such a class in a functional language?
Orchestrator classes
Such classes don't do anything by themselves, but just orchestrate the whole process or workflow. They offer multiple entry point APIs.
E.g. A OrderOrchestrator orchestrates a multiple step workflow starting with payment instrument validation, shopping cart management, payment, shipment initiation etc.
They might maintain some internal state of their own that is used by the different steps like payment, shipment etc.
ClientFactory pattern
Let's say you have written a client that for a LogService that is used by your client to log traffic data about their services. The client logs the data in S3 under buckets and accounts managed by you and you provide additional services like reporting and analytics on this data.
You don't want your customer to worry about providing the configuration information like AWS account info etc and hence you provide a ClientFactory that instantiates the appropriate client object based on whether this is for testing or production purposes without requiring the customer to provide any configuration. E.g. LogServiceClientFactory.getProdInstance() or LogServiceClientFactory.getTestInstance().
How is such a client modeled in a functional language?
Builder Pattern and other Fluent API designs
Client libraries often provide Builders to create objects with complex configuration. Sometimes APIs are also fluent to make it easy to create. An example of Fluent API is Mockito APIs : Mockito.when(A.get()).thenReturn(a) IIRC this is internally implemented by returning progressively restrictive Builders to allow the developer to write this code.
Is this a parallel to this in the functional programming world?
Datastore instances
Let's say that your codebase uses data stored in a ActiveUserRegistry from multiple places. You want only 1 instance of this registry to exist and have the entire code base access this registry. So you provide a ActiveUserRegistry.getInstance() that guarantees that all the code base accesses the instance (Assume that the instance is thread-safe etc.)
How is this managed in a functional setting? Do we have to make sure the same instance is passed around in the entire codebase?
Below is something to get started:
Stateless Request handlers
Clojure: Protocols
Haskell: Type classes
Orchestrator classes
State monad
ClientFactory pattern
LogServiceClientFactory is a Module and getProdInstance and getTestInstance being the functions in the module.
Builder Pattern and other Fluent API designs
Function composition
Datastore instances
Clojure: Function that uses an atom (to store and use the single instance)
Haskell: TVar,MVar
I'm not vary familiar with the many of these Java-style structures, but I'll take a stab at answering:
Stateless Request handlers
These exist in the functional world as well. Functions can fill this role easily, even with something as simple as a function from requests to responses. The Play Framework uses something more powerful, specifically a function from the Request to an Iteratee (type (RequestHeader) ⇒ Iteratee[Array[Byte], SimpleResult]). The Iteratee is an entity that can progressively consume input (Array[Byte]) as it is received and eventually produce the response (SimpleResult) to give back to the client. The request handler function is stateless and can be reused. The Iteratee is also stateless - the result of feeding it each chunk is actually to get a new Iteratee back, which is then fed the next chunk. (I'm oversimplifying really, it uses Futures, is entirely non-blocking, and has effective error handling - worth looking at to get a feel of the power and simplicity that functional-style code can bring to this problem).
Orchestrator classes
I'm not familiar with this pattern, so forgive me if this makes no sense. Having one giant mutable object that gets passed around is an anti-pattern. In functional code, there would be separate datatypes to represent the data that needs to passed between each stage of the process. These datatypes would be immutable.
As for things that organize other things, look at Akka and how one actor can monitor other actors underneath it, handling errors or restarting them as needed.
Builder Pattern and other Fluent API designs
Functional program has these and takes them to their logical conclusion. Functional code allows for very powerful DSLs. As for an example, check out a parser combinator library, either the one in the Scala standard library or one of the libraries for Haskell.
ClientFactory pattern and Datastore instances
I don't think this is any different in functional code. Either you have a singleton, or you do proper dependency injection. The Factory pattern is used in functional code as well, though first-class functions make many design patterns too trivial to be worth naming (from the GoF: Factory, Factory method, Command, and at least some instances of Strategy and Template can usually just be functions).
Have a look at Functional Programming Patterns in Scala and Clojure: http://pragprog.com/book/mbfpp/functional-programming-patterns-in-scala-and-clojure .
It should exactly have what you need.

Functional Programming + Domain-Driven Design

Functional programming promotes immutable classes and referential transparency.
Domain-driven design is composed of Value Object (immutable) and Entities (mutable).
Should we create immutable Entities instead of mutable ones?
Let's assume, project uses Scala as main language, how could we write Entities as case classes (immutable so) without risking stale status if we're dealing with concurrency?
What is a good practice? Keeping Entities mutable (var fields etc...) and avoiding great syntax of case classes?
You can effectively use immutable Entities in Scala and avoid the horror of mutable fields and all the bugs that derives from mutable state. Using Immutable entities help you with concurrency, doesn't make things worse. Your previous mutable state will become a set of transformation which will create a new reference at each change.
At a certain level of your application, however, you will need to have a mutable state, or your application would be useless. The idea is to push it as up as you can in your program logic. Let's take an example of a Bank Account, which can change because of interest rate and ATM withdrawal or
deposit.
You have two valid approaches:
You expose methods that can modify an internal property and you manage concurrency on those methods (very few, in fact)
You make all the class immutable and you surround it with a "manager" that can change the account.
Since the first is pretty straightforward, I will detail the first.
case class BankAccount(val balance:Double, val code:Int)
class BankAccountRef(private var bankAccount:BankAccount){
def withdraw(withdrawal) = {
bankAccount = bankAccount.copy(balance = bankAccount.balance - withdrawal)
bankAccount.balance
}
}
This is nice, but gosh, you are still stuck with managing concurrency. Well, Scala offers you a solution for that. The problem here is that if you share your reference to BankAccountRef to your Background job, then you will have to synchronize the call. The problem is that you are doing concurrency in a suboptimal way.
The optimal way of doing concurrency: message passing
What if on the other side, the different jobs cannot invoke methods directly on the BankAccount or a BankAccountRef, but just notify them that some operations needs to be performed? Well, then you have an Actor, the favourite way of doing concurrency in Scala.
class BankAccountActor(private var bankAccount:BankAccount) extends Actor {
def receive {
case BalanceRequest => sender ! Balance(bankAccount.balance)
case Withdraw(amount) => {
this.bankAccount = bankAccount.copy(balance = bankAccount.balance - amount)
}
case Deposit(amount) => {
this.bankAccount = bankAccount.copy(balance = bankAccount.balance + amount)
}
}
}
This solution is extensively described in Akka documentation: http://doc.akka.io/docs/akka/2.1.0/scala/actors.html . The idea is that you communicate with an Actor by sending messages to its mailbox, and those messages are processed in order of receival. As such, you will never have concurrency flaws if using this model.
This is sort of an opinion question that is less scala specific then you think.
If you really want to embrace FP I would go the immutable route for all your domain objects and never put any behavior them.
That is some people call the above the service pattern where there is always a seperation between behavior and state. This eschewed in OOP but natural in FP.
It also depends what your domain is. OOP is some times easier with stateful things like UI and video games. For hard core backend services like web sites or REST I think the service pattern is better.
Two really nice things that I like about immutable objects besides the often mentioned concurrency is that they are much more reliable to cache and they are also great for distributed message passing (e.g. protobuf over amqp) as the intent is very clear.
Also in FP people combat the mutable to immutable bridge by creating a "language" or "dialogue" aka DSL (Builders, Monads, Pipes, Arrows, STM etc...) that enables you to mutate and then to transform back to the immutable domain. The services mentioned above uses the DSL to make changes. This is more natural than you think (e.g. SQL is an example "dialogue"). OOP on the other hand prefers having a mutable domain and leveraging the existing procedural part of the language.

Different Scala Actor Implementations Overview

I'm trying to find the 'right' actor implementation. I realized there is a bunch of them and it's a bit confusing to pick one. Personally I'm especially interested in remote actors, but I guess a complete overview would be helpful to many others. This is a pretty general question, so feel free to answer just for the implementation you know about.
I know about the following Scala Actor implementations (SAI). Please add the missing ones.
Scala 2.7 (difference to)
Scala 2.8
Akka (http://www.akkasource.org/)
Lift (http://liftweb.net/)
Scalaz (http://code.google.com/p/scalaz/)
What are the target use-cases for these SAIs (lightweight vs. "heavy" enterprise framework)?
do they support remote actors? What shortcomings do remote actors have in the SAIs?
How is their performace?
How active is there community?
How easy are they to get started? How good is the documentation?
How easy are they to extend?
How stable are they? Which projects are using them?
What are their shortcomings?
What are their design principles?
Are they thread based or event based (receive/ react) or both?
Nested receiveS
hotswapping the Actor’s message loop
This is the most comprehensive comparison I have seen so far:
http://doc.akka.io/docs/misc/Comparison_between_4_actor_frameworks.pdf via http://klangism.tumblr.com/post/2497057136/all-actors-in-scala-compared
As of Scala 2.10, scala actors is now deprecated and Akka Actors is now part of standard distribution
Scala 2.7.7. vs 2.8 after The Scala 2.8.0 RC3 distribution:
New Reactors provide more lightweight, purely event-based actors with optional, implicit sender identification. Support for actors with daemon-style semantics was added. Actors can be configured to use the efficient JSR166y fork/join pool, resulting in significant performance improvements on 1.6 JVMs. Schedulers are now pluggable and easier to customize.
There's also a design document of Haller: Scala Actors: Unifying Thread-based and Event-based Programming
As far as I know, only Scala and Akka support remote actors.
Akka is backed up by scalablesolutions, which offer commerical support and plug ins for akka.
Akka seems like a heavyweight solution, which targets integration with existing frameworks (camel, AMQP, JTA, Comet, Spring, Redis) and additionally STMs and persistence.
Akka compared to Scala doesn't support nested receives, but supports hotswapping the actors message loop and has both, thread based and event based actors and so called "Event-based single-threaded" ones.
I realized that akka enforces exhaustive matches. So even if technically receive expects a partial function, the function must not be partial. This means you have to handle every message immediately.