Domain-Driven Design with
F# and EventStore

Lev Gorodinski

gorodinski.com

@eulerfx

Goals

  • Go beyond OOP
  • Learn F# / Functional Programming
  • Learn EventStore / Event sourcing
  • Supple design
Domain-Driven Design Implementation Path

The Domain

SaaSOvation / Collaboration

Forum Aggregate

Behaviors

  • Start
  • Assign Moderator
  • Change Description
  • Change Subject
  • Close
  • Re-Open

C#


public class Forum : EventSourcedRootEntity
{
	public void AssignModerator(Moderator moderator)
	{
		AssertionConcern.AssertArgumentNotNull(moderator, "The moderator must be provided.");
	    AssertOpen();        
	    Apply(new ForumModeratorChanged(this.tenantId, this.forumId, moderator, this.exclusiveOwner));
	}

	void AssertOpen()
	{
	    if (this.closed)
	        throw new InvalidOperationException("Forum is closed.");
	}

	void When(ForumModeratorChanged e)
	{
	    this.moderator = e.Moderator;
	}
}
        
source

public abstract class EventSourcedRootEntity : EntityWithCompositeId
{
	readonly List<IDomainEvent> mutatingEvents;
	readonly int unmutatedVersion;

	protected void Apply(IDomainEvent e)
	{
	    this.mutatingEvents.Add(e);
	    When(e);
	}

	void When(IDomainEvent e)
	{
	    // dynamic dispatch
	    (this as dynamic).When(e);
	}    
}
      

Issues

  • Verbose
  • Not POCO
  • Double dispatch voodoo
  • Misuse of inheritance
  • Conflation of state and identity

F#

    
type State = { 
    moderator      : Collaborator;
    description    : NonEmptyString;
    closed         : bool; }
      

Record Type

  • Immutable by default
  • No inheritance
  • Structural equality, comparison

Events & Commands

    
type Command = 
    | AssignModerator of Collaborator
    | ChangeDescription of NonEmptyString
    
type Event =
    | ModeratorChanged of Id * Collaborator * ExclusiveOwner
    | DescriptionChanged of Id * NonEmptyString * ExclusiveOwner
      

Union Type

  • Mutually exclusive, named cases
  • Similar: closed class hiearachy, C union, enum on steroids
  • Pattern matching

let apply state = function
    | ModeratorChanged (_,moderator,_) -> 
    	{ state with moderator = moderator }
    | DescriptionChanged (_,desc,_)    -> 
    	{ state with description = desc }
      

Pattern Matching

  • Switch statement on steroids
  • ...lots of steroids
  • Customizable

let exec state =         
    let assertOpen = validator (fun _ -> state.closed <> true) 
    	["Forum must be open."] state
    function
    | AssignModerator moderator -> assertOpen <?> [ModeratorChanged(...)]
    | ChangeDescription desc -> assertOpen <?> [DescriptionChanged(...)]
      
source

Improvements

  • Brevity
  • Explicitness
  • Uniformity
  • Single responsibility
  • Static verification
  • Cohesion

Benefits for DDD

  • Focus on behavior
  • Declarative
  • Assertions
  • Side-effect free
  • Closure of operations

Challenges

  • New paradigm
  • Different paradigms collide for attention
  • Less tooling support
  • C# interop can be less than pleasant
  • Missing some advanced functional features

Event Sourcing


AHA!


let apply state = function
    | ModeratorChanged (_,moderator,_) -> { state with moderator = moderator }
    | DescriptionChanged (_,desc,_)    -> { state with description = desc }
        

Event Sourcing

Capture all changes to an application state as a sequence of events.
Martin Fowler

Capture all changes to an application state behaviors as a sequence of events.

Reconstitution

Replay all past events to bring aggregate into current state.

Aggregate Abstraction


	type Aggregate<'TState, 'TCommand, 'TEvent> = {          
		zero : 'TState;
		apply : 'TState -> 'TEvent -> 'TState;
		exec : 'TState -> 'TCommand -> 'TEvent; }
      

Replay


      let events = load (typeof<'TEvent>,id)
      let state = events |> Seq.fold aggregate.apply aggregate.zero        
      
source

EventStore Integration


  let load (typ,id) =
      let slice = conn.ReadStreamEventsForward(id,1,Int32.Max,false)
      slice.Events 
      |> Seq.map (fun e -> decode(typ,e.Event.EventType,e.Event.Data))
      
source

Event Persistance


  let commit (id,expectedVersion) e =
        let eventType,bytes = serialize e
        let meta = [||] : byte array
        let data = EventData(Guid.NewGuid(),eventType,true,bytes,meta)
        if version = 0 then 
          conn.CreateStream(id, Guid.NewGuid(), true, metaData)
        conn.AppendToStream(id,expectedVersion,data)
      
source

Projections

  • Project stream onto new stream
  • State
  • Declared with JavaScript
  • Simple read-models
  • CEP

Read Model Projection


fromCategory('Forum').foreachStream().when({
  $init: function() {
    return { description: null, moderator: null };
  },
  "ModeratorAssigned": function (s, e) {
    s.moderator = e.body.moderator;
    var streamId = "ReadModel-" + 
          e.streamId.replace("Forum-", "");
    var eventType = e.eventType + "_ReadModel";
    emit(streamId, eventType, s);
  },
  "DescriptionChanged": function (s, e) {
    s.description = e.body.description;
    var streamId = "ReadModel-" + 
          e.streamId.replace("Forum-", "");
    var eventType = e.eventType + "_ReadModel";
    emit(streamId, eventType, s);
  }
});
        

Challenges

  • Less tooling support
  • Non-trivial shift in data modelling
  • Queries must be implemented separately
  • Eventual consistency
  • Lack of referential integrity
  • Schema maintenance, refactoring

Why F# / Functional Programming?

  • .NET, VisualStudio
  • Multi-paradigm
  • Powerful type inference
  • Language oriented
  • Better coupling characteristics
  • Smaller, more numerous types
  • Function as unit of coupling
  • More explicit, declarative
  • Pattern matching
  • Avoid nulls
  • Isolate, minimize state
  • OOP patterns taken care of
  • Draw on math research

Why EventStore / event sourcing?

  • Immutable, preserve information
  • Uniform
  • Append only
  • Natural model of reality

Acknowledgements

  • Vaughn Vernon
  • Paul Rayner
  • Community

References

Lev Gorodinski

gorodinski.com

@eulerfx

github.com/eulerfx

eulerfx@gmail.com