Event sourcing: making it functional (7)

TL;DR

It’s the seventh chapter of making event sourcing functional. In the last post we introduced the base class for aggregates capturing events and applying them on the state. In this entry we question this choice and make the final step to make our code more functional. Let’s go!

All entries in this series:

Question your choices

Let’s again take a look at the method responsible for receiving the gateway response

paymentstate

This is a void method. It’s not a pure function though. It “returns” its result by passing emitted events to the apply function. We could rewrite it in the following manner:

paymentstate

Now you can probably see, that there are two methods in there. One that emits, the event, possibly taking the state into consideration and the second that applies the event. We can make the first one even more generic and make it return IEnumerable of events.

PaymentState.png

Final revelation

Now you can see, that ReceiveImpl is the true implementation of the aggregate action, but it does not require the aggregate class at all! It gets the state, the action parameter and returns events! The ReceiveGatewayResponse is now just an infrastructure code that applies events, which is totally unneeded! We no longer have the Payment aggregate! All we have is just a set of functions that acts on the state basis, accepts some parameters and returns events. We can make it even an extension to call it in an easier way.

paymentstate

This pure function is so easy to test. You can test it using Given, When, Then with events, but you can test it with regular unit testing as well.

Now you can see that we were able to split the Payment aggregate into set of functions, that accept a state and other needed parameters returning a enumerable of events. Is there anything easier to test and to work with? For sure you need to pay some tax by introducing storing and applying events on the infrastructure side, but still it’s worth it, as we change aggregates, from being classes to just sets of simple functions.

Summary

I hope you enjoyed this series and that I was able to encourage you to see aggregates and event sourcing from a bit more functional point of view. All the commenters, thank you for providing valuable feedback. See you soon!

Event sourcing: making it functional (6)

TL;DR

In the last entry we changed the Payment aggregate to modify state by raising events. The events weren’t captured though. In this post, we’ll change the aggregate to enable recording of these changes.

All entries in this series:

Capturing events

The easiest way to capture events is to make them pass one additional method. We could provide one Apply method in the aggregate itself that beside applying the event it would. To make it usable in all the aggregates we could create a base class that would have this method. Let’s apply it to the Payment first

paymentstate

Now, we need the aggregate base class to hold the capture the applied events.

The base aggregate

We use the base class to track the changes and provide one point of entry to applying events. The dynamic is used to implement it fast. If you wanted to optimize, you could remove it by writing a custom dispatcher that calls directly a method from the derived aggregate.

paymentissued.png

When the action ends, a handler executing it calls GetEvents and gets all the events that were raised during this session. This enables you to write simple tests with a Given-When-Then approach and easily extract the changes for persistence purposes. On the other hand, we introduced the base class for the aggregate. What could be done more?

Summary

By introducing a base AggregateRoot class we enabled capturing all raised events. This simplified a little bit Payment aggregate itself, but introduced the base class. It’s time to move to the final part where we make it functional removing some code we’ve written so far.

Event sourcing: making it functional (5)

TL;DR

After defining events of the Payment aggregate it’s time to move on and work on applying these events.

All entries in this series:

State

To apply events, the state of Payment will be extracted to a separate class. This should be a familiar pattern to all event sourcing practitioners, but let me show the code for clear understanding of our approach

paymentstate

How to construct the state

  1. There are no public setters. The state has readonly properties.
  2. All events are applied with an Apply method.
  3. The only way to change the state is to apply an event.
  4. No Apply throws an exception. The event has already happened and the state is just an accumulator of the changes.

New Payment Aggregate

The Payment aggregate now can be transformed to use this state, by removing all the state changes and raising/applying events in these places:

paymentstate

Summary

We know how to extract a state from the aggregate and apply all the events. Although Payment uses events, it does not store them in any form nor allows accessing them for processing. In the current shape the Payment isn’t much different from the previous version. We extracted a few event classes and the state, but we still can’t treat events as the first class citizen. we need to move one step further and we will do it in the next blog post.

Event sourcing: making it functional (4)

TL;DR

In the last entry we defined the aggregate implementation that we’ll work on. Let’s move forward and make it an event sourced aggregate.

All entries in this series:

Events

The first and the most important event, is the fact of issuing the payment itself. Let’s define it in the following way:

paymentissued

The event contains all the data provided to the constructor of the payment aggregate in the past.

The next one is raised and applied when the payment is processed successfully. Let’s make it a class without any members. We just want to record a notion of success.

paymentissued

The last but not least is the one raised in case of the error. We make the errors explicit in here as we’d like to react to payments failure. One could model it in a different way, providing one event class, but then again, just follow this take on the payment problem.

paymentissued

Summary

We discovered three meaningful events:

  1. PaymentIssued
  2. PaymentProcessedSuccessfully
  3. PaymentProcessedWithFailure

In the next entry we will start rewriting the aggregate to use these.

Event sourcing: making it functional (3)

TL;DR

We’re on our journey to move from event sourcing oriented on the aggregates to a more functional approach. In the first entry, we went through some of the DDD building blocks. In the second, we defined an interface of the aggregate that we’ll work with. Before, going to the event sourced approached, let’s go through the aggregate’s implementation, somehow related to the Blue Book approach, without event sourcing.

All entries in this series:

Payment aggregate!

Let’s dive straight into the code

paymentapi

We can see that a payment is issued for a user, with a specified payment method and a given amount of money. Yes, it’s simplistic, but bear with me, and follow its implementation for a while.

The other method is responsible for receiving the gateway response and applying it onto the aggregate. The status and the description are updated accordingly.

So far so good? In the next entry we’ll make this aggregate event sourced!

Event sourcing: making it functional (2)

TL;DR

In the last post we covered the basic concept of DDD, the aggregate and its root. Before we move on with the non-functional approach, let’s try to define at least one aggregate, that could be used as an example for future posts and code samples.

All entries in this series:

A payment

For sake of providing an aggregate example let me reuse the payment example I introduced for the service kata purposes. The aggregate boundary is handling a single payment. This includes:

  • selecting payment method
  • registering an answer from the payment gateway
  • storing status

Having this we can easily imagine that the API of this aggregate could be similar to:

paymentapi

As you can see, there are no dummy setters or meaningless primitive properties. We exposed meaningful methods and properties for showing the part of the state we want to show. Additionally, the payment constructor shows all the parameters that are required to issue a payment.

With this example we can move forward and provide more insight into its initial implementation and refactoring it towards more functional design.

Event sourcing: making it functional (1)

TL;DR

This article starts a series of entries that will guide you through my experiences with making event sourcing functional. There are a few existing entries about a functional approach to event sourcing, but I want to share my path and a story behind migrating from one approach to another. I’ll start with some fundamentals. This will show from where I started, as well as it may help you to learn some basics of DDD and event sourcing if you’re not into the topic.

All entries in this series:

The Blue Book51szw87slrl-_sx258_bo1204203200_

There’s a book that is a must read, Domain-Driven Design by Eric Evans. It’s quite old and a lot of has changed in our industry. Still, the basic need of having developers understanding the domain they work on, the strategies and tactics they could use to embrace it, they are the same. Eric covers a lot of topics in there, one of them which is a really low level concept (and not the most important one) is the aggregate.

The aggregate

Let me quote Eric’s descriptions of the aggregate first:

An AGGREGATE is a cluster of associated objects that we treat as a unit for the purpose of data changes. Each AGGREGATE has a root and a boundary. The boundary defines what is inside the AGGREGATE. The root is a single, specific ENTITY contained in the AGGREGATE. The root is the only member of the AGGREGATE that outside objects are allowed to hold references to, although objects within the boundary may hold references to each other. ENTITIES other than the root have local identity, but that identity needs to be distinguishable only within the AGGREGATE, because no outside object can ever see it out of the context of the root ENTITY.

The vital part of this description is the boundary. That’s what aggregate is for – to distill boundaries existing in a domain you work on. So once you set a boundary of data changed together, you ensure that they stay together. Additionally, you operate on this data only via the Aggregate Root, which might be treated as the public API of an aggregate, something that others interacts with.

The aggregate boundaries

If an aggregate is defined by its boundaries, one could design a system, that would be just one aggregate. This would enable to access all the data and still have a defined boundary, right? Wrong. What you want to do is to define aggregates following these two simple rules:

  1. aggregates are as big as there have to
  2. aggregates are as small as possible

Aggregates are as big as there have to

The very first rule says that the size of an aggregate is determined by a domain and a model. A domain can require some consistency across different entities, making an aggregate bigger. The same with model. Frequently it’s up to the modeller (a model’s creator) to create bigger or smaller aggregate, but not bigger than needed.

Aggregates are as small as possible

Distilling just one aggregate would mean, that a system can execute one action at a time (when optimistic concurrency applied). This isn’t enough for the majority of applications. Making aggregates small improves your system’s scalability and performance, not to mention your ability to design and model in small chunks.

Summary

This ends the first entry of this series. We recalled the aggregate’s definition and discussed briefly two rules of modelling an aggregate. Still, there’s more to come on our way of making the event sourcing functional. First, we need to visit a non-functional approach.