Functional programming equivalents for the following [closed] - scala

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.

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, GUI and immutability

I created an algorithm that calculates certain things. This can be considered as the model. The algorithm is implemented in a fully functional way, so it uses immutable classes only.
Now using this model, I would like to develop a GUI layer on the top of it. However I do not know anything about the best-practises of building GUI in Scala. I intend to use ScalaFX.
My problem is the following: in ScalaFX (similarly to JavaFX) you can bind values from the GUI to object properties. This clearly violates the functional paradigm, but seems very convenient.
This would require rewriting my classes to use bindable properties which would feel like the tail wagging the dog — the model would depend on the GUI.
On the other hand, I could have an independent GUI layer. In this case I would need proxy objects to bind to and I would have to create my model objects based on these proxy objects. This would feel more idiomatic but implies a lot of code duplication and extra work. My model and the proxy objects would have to be kept in sync and I would have to take care of copying the attributes.
What is a good way of doing this? A GUI is always full of mutability so functional programming does not feel right here. Nevertheless I love Scala so I would like to keep using it for the GUI, too.
Despite the extra effort, take the second approach. Create small mutable "view" instances for each of your model. Bind the views to the widgets and install observers or hooks that update the view proxies based on changes in your model. Don't let the GUI API dictate how your concurrency approach and model should look like.
I believe there are a few open source libraries around that provide a more functional and/or reactive abstraction layer to the plain Scala-Swing or Scala-FX.

Is it possible to do DDD and REST interface and language mapping?

REST has a uniform interface constraint which is the following in a very zipped opinion based format.
You have to use standards like HTTP, URI, MIME, etc...
You have to use hyperlinks.
You have to use RDF vocabs to annotate data and hyperlinks with semantics.
You do all of these to decouple the client from the implementation details of the service.
DDD with CQRS (or without it) is very similar as far as I understand.
By CQRS you define an interface to interact with the domain model. This interface consists of commands an queries classes.
By DDD you define domain events to decouple the domain model from the persistence details.
By DDD you have one ubiquitous language per bounded context which expresses the semantics.
You do all of these to completely decouple the domain model from the outside world.
Is it possible to map the REST uniform interface to the domain interface defined by commands and queries and domain events? (So the REST service code would be generated automatically.)
Is it possible to map the linked data semantics to the ubiquitous languages? (So you wouldn't need to define very similar terms, just find and reuse existing vocabs.)
Please add a very simple mapping example to your answer, why yes or why not!
I don't think this is possible. There is a term which I believe describes this problem, it is called ontology alignment.
In this case have have at least 3 ontologies:
the ubiquitous language (UL) of the domain model
the application specific vocab (ASO) of the REST service
the linked open data vocabs (LODO) which the application specific vocab uses
So we have at least 2 alignments:
the UL : ASO alignment
the ASO : LODO alignment
Our problem is related to the UL : ASO alignment, so let's talk about these ontologies.
The UL is object oriented, because we are talking about DDD and domain model. So most of the domain objects entities, value objects are real objects and not data structures. The non-object-oriented part of it are the DTOs like command+domainEvent, query+result and error on the interface of the domain model.
In contrast the ASO is strictly procedural, we manipulate the resources (data structures) using a set of standard methods (procedures) on them.
So from my aspect we are talking about 2 very different things and we got the following options:
make the ASO more object oriented -> RPC
make the UL less object oriented -> anaemic domain model
So from my point of view we can do the following things:
we can automatically map entities to resources and commands to operations by CRUD, for example the HydraBundle does this with active records (we can do just the same with DDD and without CQRS)
we can manually map commands to operations by a complex domain model
the operation POST transaction {...} can result a SendMoneyCommand{...}
the operation GET orders/123/total can result a OrderTotalQuery{...}
we cannot map entities to resources by a complex domain model, because we have to define new resources to describe a new service or a new entity method, for example
the operation POST transaction {...} can result account.sendMoney(anotherAccount, ...)
the operation GET orders/123/total can result in an SQL query on a read database without ever touching a single entity
I think it is not possible to do this kind of ontology alignment between DDD+CQRS and REST, but I am not an expert of this topic. What I think we can do is creating an application specific vocab with resource classes, properties and operations and map the operations to the commands/queries and the properties to the command/query properties.
You have posed some interesting questions here.
To start with I do not quite agree with
By DDD you define domain events to decouple the domain model from the
persistence details.
I think you might be confusing Event Sourcing ES with DDD, ES can be used with DDD but its very much optional in fact you should give it a lot of thought before choosing it as your persistence mechanism.
Now to the bulk of your question, of whether REST and DDD get along if yes how ?
My take on it, yes they do get along, however generally you do not want to expose your domain model via a REST interface, you want to build a abstraction over it and then expose that.
You can refer to this answer here, for a little more detail.
However i cannot recommend enough the Implementing Domain-Driven Design book, Chapter 14 Application deals with your concern to a fair degree.
I could not have explained it more thoroughly than the book and hence referring you there :)

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.

How to expose read model from shared module

I am working on developing a set of assemblies that encapsulate parts of our domain that will be shared by many applications. Using the example of an order management system, one such assembly will contain all of the core operations an application can perform to/with an order. We are applying a simple version of CQS/CQRS so that all operations that change the state of the "system" are represented as public commands, such as CancelOrderCommand, ShipOrderCommand and CreateORderCommand. The command handlers are internal to the assembly.
The question I am struggling to answer is how to best expose the read model to consuming code?
The read model will be used by consuming code to perform queries. I don't know how all of the ways the read model will be used so the interface needs to be flexible to allow any query.
What complicates it for me is that I not only need to expose my aggregate root but there are also several "lookup" lists of related data that client applications may use. For example, each order has an associated OrderType which is data-driven (i.e., not an enum) and contains several properties that will drive some of our business rules that control what operations can/cannot be performed, etc. It is easy inside my module to manage this relationship; however, a client application that allows order creation will most likely need to display the list of possible OrderTypes to the user. As a result, I need to not only expose the list of Order aggregates but the supporting list of OrderTypes (and other lookup lists) from my read model.
How is this typically done?
I'm not sure what else to explain that will help trigger a solution, so please ask away...
I have never seen a CQRS based implementation expose a full dataset for ad-hoc querying so this is an interesting situation! In a typical CQRS scenario you would expose very specific queries because you may want to raise events when they are called (for caching for example - see this post for more details on that).
However since this is your design, let's not worry about "typical" or "correct" CQRS, I guess you just need a solution! One of the best new mechanisms for exposing data for flexible querying I have seen is the Open Data Protocol (OData). It will allow consumers to implement their own filtering, sorting and paging over a data source you expose.
Most implementations of this seem to deal with relational data. If you are dealing with a relational data source then OData might be a nice way to go. I suspect by your comment of "expose my aggregate root" that you might be using a document database? If so, there is one example I have seen of OData services on top of MongoDB: http://bloggingabout.net/blogs/vagif/archive/2012/10/11/mongodb-odata-provider-now-supports-arrays-and-nested-collections.aspx.
I hope that helps, OData is definitely worth looking into. It seems to be growing really quickly and is getting good support on both server and client technology platforms.