Functional Programming + Domain-Driven Design - scala

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.

Related

Refactoring domain model with mutability and cyclical dependencies to work for Scala with good FP practices?

I come from an OO background(C#, javascript) and Scala is my first foray into FP.
Because of my background I am having trouble realizing a domain model that fits my domain problem well and also complies with good practices for FP such as minimal mutability in code.
First, a short description of my domain problem as it is now.
Main domain objects are: Event, Tournament, User, and Team
Teams are made up of Users
Both Teams and Users can attend Tournaments which take place at an Event
Events consist of Users and Tournaments
Scores, stats, and rankings for Teams and Users who compete across Tournaments and Events will be a major feature.
Given this description of the problem my initial idea for the domain is create objects where bidirectional, cyclic relationships are the norm -- something akin to a graph. My line of thinking is that being able to access all associated objects for any given given object will offer me the easiest path for programming views for my data, as well as manipulating it.
case class User(
email: String,
teams: List[TeamUser],
events: List[EventUser],
tournaments: List[TournamentUser]) {
}
case class TournamentUser(
tournament: Tournament,
user: User,
isPresent: Boolean){
}
case class Tournament(
game: Game,
event: Event,
users: List[TournamentUser],
teams: List[TournamentTeam]) {
}
However as I have dived further into FP best practices I have found that my thought process is incompatible with FP principles. Circular references are frowned upon and seem to be almost an impossibility with immutable objects.
Given this, I am now struggling with how to refactor my domain to meet the requirements for good FP while still maintaining a common sense organization of the "real world objects" in the domain.
Some options I've considered
Use lazy val and by-name references -- My qualm with this is that seems to become unmanageable once the domain becomes non-trivial
Use uni-directional relationships instead -- With this method though I am forced to relegate some domain objects as second class objects which can only be accessed through other objects. How would I choose? They all seem equally important to me. Plus this would require building queries "against the grain" just to get a simple list of the second class objects.
Use indirection and store a list of identifiers for relationships -- This removes cyclical dependencies but then creates more complexity because I would have to write extra business logic to emulate relationship updates and make extra trips to the DB to get any relationship.
So I'm struggling with how to alter either my implementation or my original model to achieve the coupling I think I need but in "the right way" for Scala. How do I approach this problem?
TL;DR -- How do I model a domain using good FP practices when the domain seems to call for bidirectional access and mutability at its core?
Assuming that your domain model is backed by a database, in the case you highlighted above, I would make the "teams," "events," and "tournaments" properties of your User class defs that retrieve the appropriate objects from the database (you could implement a caching strategy if you're concerned about excessive db calls). It might look something like:
case class User(email: String)) {
def teams = TeamService.getAllTeams.filter( { t => t.users.contains(this) } )
//similar for events and tournaments
}
Another way of saying this might be that your cyclic dependencies have a single "authoritative" direction, while references in the other direction are calculated from this. This way, for example, when you add a user to a tournament, your function only has to return a new tournament object (with the added user), rather than a new tournament object and a new user object. Also, rather than explicitly modeling the TournamentUser linking table, Tournament could simply contain a list of User/Boolean tuples.
Another option might be to use Lenses to modify your domain model, but I haven't implemented them in a situation like this. Maybe someone with more experience in FP could speak to their applicability here.

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.

Pattern to bridge the gap between Scalas functional immutable style and JavaFX 2 Properties?

currently working on a GUI application using JavaFX 2 as framework. Used in Java allready and know the principles of data binding.
As the functional style programming in scala advocates the use of imutable values (vals), there is a gap.
Is there an other solution than having an mutable fx-property based presentation model for the gui and and immutable model for application logic with an conversion layer?
Greets,
Andreas
Since your question is a bit vague, please forgive if this is largely based on personal opinion: There are, to my knowledge, no other approaches to the mutable property model. I would however argue that you don't want one:
First of, functional programming, at least from a puristic point of view, attempts to avoid side effects. User interfaces, however, are exclusively about causing side effects. There is a slight philosophical mismatch to begin there.
One of the main benefits of immutable data is that you don't have to deal with control structures to avoid concurrent modification. However, JavaFX's event queue implements a very strict single-threaded approach with an implicit control of read and write access. On the other hand, user interface components fit the idea of mutable objects better than most other fields of programming. The node structure is, after all, an inherent hierarchy of stateful components.
Considering this, I think trying to force a functional and immutable paradigm on JavaFX is not going to work out. Instead, I would recommend building a translation layer based on keypath selections - e.g. binding a Label to display an (immutable) Person's name to the Person, not the name property, and having a resolver handle the access to the name attribute. Basically, this would mean having a combination of Bindings#select and a JavaBeanStringProperty.

What are the obstacles for Scala having "const classes" a la Fantom?

Fantom supports provably immutable classes. The advantages of the compiler knowing a class is immutable must be numerous, not the least of which would be guaranteed immutable messages passed between actors. Fantom's approach seems straightforward - what difficulties would it pose for Scala?
There's more interest on Scala side on tracking side effects, which is a much harder proposition, than simply immutability.
Immutability in itself isn't as relevant as referential transparency, and, as a matter of fact, some of Scala's immutable collections would not pass muster on an "proven immutable" test because, in fact, they are not. They are immutable as far as anyone can observer from the outside, but they have mutable fields for various purposes.
One such example is List's subclass :: (the class that makes up everything in a list but the empty list), in which the fields for head and tail are actually mutable. This is done that way so that a List can be composed efficiently in FIFO order -- see ListBuffer and its toList method.
Regardless, while it would be interesting to have a guarantee of immutability, such things are really more of a artifact of languages where mutability is the default. It doesn't come up as a practical concern when programming in Scala, in my experience.
While the approach may be straightforward,
its guarantees can be broken by reflection;
it requires quite a bit of effort, which the Scala team may think not worth it or not a priority.

how to access complex data structures in Scala while preserving immutability?

Calling expert Scala developers! Let's say you have a large object representing a writable data store. Are you comfortable with this common Java-like approach:
val complexModel = new ComplexModel()
complexModel.modify()
complexModel.access(...)
Or do you prefer:
val newComplexModel = complexModel.withADifference
newComplexModel.access(...)
If you prefer that, and you have a client accessing the model, how is the client going
to know to point to newComplexModel rather than complexModel? From the user's perspective
you have a mutable data store. How do you reconcile that perspective with Scala's emphasis
on immutability?
How about this:
var complexModel = new ComplexModel()
complexModel = complexModel.withADifference
complexModel.access(...)
This seems a bit like the first approach, except that it seems the code inside withADifference is going to have to do more work than the code inside modify(), because it has to create a whole new complex data object rather than modifying the existing one. (Do you run into this problem of having to do more work in trying to preserve
immutability?) Also, you now have a var with a large scope.
How would you decide on the best strategy? Are there exceptions to the strategy you would choose?
I think the functional way is to actually have Stream containing all your different versions of your datastructure and the consumer just trying to pull the next element from that stream.
But I think in Scala it is an absolutely valid approach to a mutable reference in one central place and change that, while your whole datastructure stays immutable.
When the datastructure becomes more complex you might be interested in this question: Cleaner way to update nested structures which asks (and gets answered) how to actually create new change versions of an immutable data structure that is not trivial.
By such name of method as modify only it's easy to identify your ComplexModel as a mutator object, which means that it changes some state. That only implies that this kind of object has nothing to do with functional programming and trying to make it immutable just because someone with questionable knowledge told you that everything in Scala should be immutable will simply be a mistake.
Now you could modify your api so that this ComplexModel operated on immutable data, and I btw think you should, but you definitely must not try to convert this ComplexModel into immutable itself.
The canonical answer to your question is using Zipper, one SO question about it.
The only implementation for Scala I know of is in ScalaZ.
Immutability is merely a useful tool, not dogma. Situations will arise where the cost and inconvenience of immutability outweigh its usefulness.
The size of a ComplexModel may make it so that creating a modified copy is sufficiently expensive in terms of memory and/or CPU that a mutable model is more practical.