<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Roman Provazník on Medium]]></title>
        <description><![CDATA[Stories by Roman Provazník on Medium]]></description>
        <link>https://medium.com/@dzoukr?source=rss-43a58c6c8a64------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*75bH6nj2JXsspwYLrSxpUg.png</url>
            <title>Stories by Roman Provazník on Medium</title>
            <link>https://medium.com/@dzoukr?source=rss-43a58c6c8a64------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 15 Nov 2026 19:51:41 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@dzoukr/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Event Sourcing - Step by step in F#]]></title>
            <link>https://medium.com/@dzoukr/event-sourcing-step-by-step-in-f-be808aa0ca18?source=rss-43a58c6c8a64------2</link>
            <guid isPermaLink="false">https://medium.com/p/be808aa0ca18</guid>
            <category><![CDATA[fsharp]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[event-sourcing]]></category>
            <dc:creator><![CDATA[Roman Provazník]]></dc:creator>
            <pubDate>Wed, 19 Dec 2018 08:31:06 GMT</pubDate>
            <atom:updated>2018-12-19T08:31:06.732Z</atom:updated>
            <content:encoded><![CDATA[<p>This article is part of traditional <a href="https://sergeytihon.com/2018/10/22/f-advent-calendar-in-english-2018/">#fsadvent</a>. Thanks all the writers involved in it and of course thanks Sergey for organization!</p><h3>Why Event Sourcing again?</h3><p>Well, looking back at this year agenda, Event Sourcing was somehow the thin red line of me and F# in 2018. Yes, I could write about few more things I did this year like writing my first <a href="https://github.com/fsprojects/OpenAPITypeProvider">type provider for OpenAPI specification</a> (type provider has always been in my mind as something like graduation for F# developers, so hurraayyy), starting new F# commercial projects in our company, co-organizing <a href="https://www.lambdup.io/">LambdUp</a> conference, F# workshops, public talks in Czech Republic, Slovakia, United Kingdom and Germany or organizing another year of my beloved <a href="http://fsharping.com/">FSharping meetups</a> in Prague.</p><p>But still, most of the things were connected with this year’s major topic: Event Sourcing in F#. I learnt a lot and now feel this article could be great way how to summarize it and also leave it for a while. I mean… not leave as stop with Event Sourcing (God, no way! :)), but more likely to move on to more advanced topics like Process managers, Sagas, queues, compensating events, etc…</p><h3>[Roman; Roman] |&gt; Async.Parallel</h3><p>Before we start, there is one more thing I need to mention. On <a href="https://fable.io/fableconf/">FableConf 2018</a> / RemmiDemmi (frankly, I still don’t know how I got there, but thanks Alfonso, Steffen and others for lack of sound judgement to invite me) I met very pleasant and friendly Roman Sachse a.k.a. <a href="https://twitter.com/R0MMSEN">R0mmsen</a> who’s talk was focused on the same topic. We found another funny similarities (except first name, obviously) like having two daughters, but back to my point: There is another F# developer doing the same thing, which is absolutely great! We can share/compare our approaches to the same problems and learn from each other. His FableConf talk was amazing (waaaayyy better than mine) and I’m truly looking forward for Roman’s #fsadvent contribution. It should be out on 23rd of December so don’t miss it!</p><h3>Let’s start then, can we?</h3><p>Ok, no more intros, let’s start. So what really is <em>Event Sourcing</em>? Before we got to the famous one-sentence explanation, we need to define what <em>Event</em> is.</p><h4>Event</h4><p>If you expect something difficult and complex, I have a bad news for you. The definition of Event is straightforward:</p><blockquote>Event is fact that happened in past.</blockquote><p>Yeap. That’s it. No rocket science, is it? Just thing that happened. Like you <em>sent an email</em>, <em>published article</em> or <em>locked door.</em> It is just done and cannot be changed. I mean, you can change it by doing another action (<em>unlocked door</em>), but cannot change the fact, that you locked them first. We have name for this. Yes, it is the famous, the one and only… drum rolls… <em>immutability!</em></p><p><strong>Protip</strong>: If you don’t believe me, try to fire my favorite Event called <em>SomethingInappropriateSaidToWife </em>and change it day after. Good luck &amp; have fun.</p><p>Ok, now we know what Events are, and that they are immutable, but how they come into existence?</p><h4>Command</h4><p>Whenever you say “Command”, somebody will raise hand and say: “But, but, now we are getting into CQRS!” Yes, you are right my meticulous friend. We are. I believe the <em>efficient </em>Event Sourcing is tightly connected with CQRS. You can probably avoid it, if you must, but I don’t see any point in doing this so I’ll happily mix terms Event Sourcing &amp; CQRS together.</p><p>So, what is <em>Command</em>? Again, no rocket science here:</p><blockquote>Command is an instruction to your system than can lead to new Events.</blockquote><p>Keeping the simple example of door, it can be: <em>LockDoor</em>, <em>UnlockDoor</em>, <em>OpenDoor </em>or <em>CloseDoor</em>. The reason why Commands exist is that you want something to happen, BUT!, there is no guarantee it will succeed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Nls1O2kBVr2u-rtW.jpg" /><figcaption>There is no door, Neo.</figcaption></figure><p>You can try to fire Command <em>CloseDoor</em> here, but instead of <em>DoorClosed </em>event you would probably get something like <em>ThereIsNoDoorException</em>.</p><p>Commands mean <em>intention. </em>Intention without guarantee of success. If you are lucky and your system is in correct shape, you’ll get new Events. If not, you’ll get an error.</p><h4>Events without Commands</h4><p>Commands are not the only way, how Events come into existence. Sometimes you don’t want to validate or even create Commands, because it doesn’t make sense to do so. From technical or business perspective. For example storing Events from IoT temperature sensor will go without Commands. Mother nature doesn’t ask us: “Hey, I see you are wearing only t-shirt so I’d like to set outside temperature to -25°C, can I?” You cannot reject that temperature has already changed.</p><p>The same goes with business reasons. If you implement some kind of e-shop, you don’t want to stop business only because you don’t have something on stock. You can sell it now and figure out the delivery later. You can always return money to the customer. It sounds strange, but go on some well known e-shop website and try to actively not buy something. Business must go on!</p><h4>Back to Event Sourcing…</h4><p>So, we have Commands and Events, now it is finally time for the famous one-liner you have been desperately waiting for:</p><blockquote>Event Sourcing is storing the system changes itself instead of result of such changes.</blockquote><p>Again, easy as taking lollipop from small kid (please don’t do it, you ruin their childhood, ok?!). Instead of writing UPDATE SQL on database layer, you just store the change (Event) and do nothing. I promise, you’ll get to your ORMs /Entity Frameworks /other cute DB things you love so much later but for now just store all the event data. But where to store them?</p><h4>Event Store</h4><p>Event store is the answer. Special, append only database designed for storing (appending) Events. Data stored there are not organized in tables like in SQL databases, or collections like in document databases, but in something called <em>Streams.</em> Imagine Stream as drawer where you put all related Events one-by-one as they occurred. You probably already realized, but just to be sure — you cannot delete Events from Event Store. Once you store your Event, you have to live with it. You can migrate them to different Stream later, but migration/versioning of Event Sourcing systems is so complex topic, even <a href="https://leanpub.com/esversioning">Greg Young hasn’t finished his book yet</a>, so we will skip it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/342/1*a39tgNPEc0A21ObE3B6cbg.png" /></figure><p><em>&lt;self-promo&gt;<br>If you need Event Store on Azure Cosmos DB or Azure Table Storage, give a shot mine implementation called CosmoStore. You can find it on </em><a href="https://github.com/Dzoukr/CosmoStore"><em>https://github.com/Dzoukr/CosmoStore</em></a><em><br>&lt;/self-promo&gt;</em></p><p>Once you have Event Store we can start coding, because we have everything we nee… oh wait!</p><h4>State</h4><p>Observant readers already realized in Commands sections, that I missed something important there. Yes, in the Command validation part. I intentionally missed how and against what we validate our Commands, because first we needed go through all previous chapters.</p><p>The last missing part of all of this Event-sourcing-monster-parade is called <em>State </em>or <em>Projection.</em></p><blockquote>State/Projection is structural view of impact of Events.</blockquote><p>Sounds fancy, but what is it really? Going back to simple-stupid example of opening/closing door, the State here is the door. In other words in what “condition” is door after all Events? Locked, opened, closed, broken? That is the <em>State</em>. And that is the thing we use as internal representation of result of Events used in Commands validation.</p><p>Ok, enough talk and theory, let’s go write some code!</p><p>But before that, take 47 seconds break…</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FKdxoPPuAdic%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DKdxoPPuAdic&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FKdxoPPuAdic%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/ee3072ddd15c806cdd7058d2753bb34b/href">https://medium.com/media/ee3072ddd15c806cdd7058d2753bb34b/href</a></iframe><h3>F# Example</h3><p>We are going to write simple <a href="http://todomvc.com/">TodoMVC</a> application. We will add tasks, remove tasks, mark them as completed and so on. We gonna use all the information gained from previous chapters (except Bob Fossil’s dance) to build nice little Event Sourcing based app.</p><h4>Commands</h4><p>We gonna start with commands. In F# we have a union which is perfect data type for such modelling:</p><pre>type Command =     <br>    | AddTask of CmdArgs.AddTask    <br>    | RemoveTask of CmdArgs.RemoveTask    <br>    | ClearAllTasks    <br>    | CompleteTask of CmdArgs.CompleteTask    <br>    | ChangeTaskDueDate of CmdArgs.ChangeTaskDueDate</pre><p>Each case holds event-specific data so we need to define it in separate module:</p><pre>module CmdArgs =    <br>    type AddTask = {        <br>         Id : int        <br>         Name : string        <br>         DueDate : DateTime option    <br>    }     <br>    type RemoveTask = {        <br>         Id : int<br>    }     <br>    type CompleteTask = {        <br>         Id : int    <br>    }     <br>    type ChangeTaskDueDate = {        <br>         Id : int        <br>         DueDate : DateTime option    <br>    }</pre><p><strong>Tip: </strong><em>RemoveTask </em>and <em>CompleteTask</em> has the same structure, but keep them as separated types. The fact they look the same can change in future and your future refactoring-all-the-stuff-yourself will thank you later.</p><h4>Events</h4><p>As you can see, Events look almost the same as Commands, but are in <em>past tense.</em></p><pre>type Event =    <br>    | TaskAdded of CmdArgs.AddTask    <br>    | TaskRemoved of CmdArgs.RemoveTask    <br>    | AllTasksCleared    <br>    | TaskCompleted of CmdArgs.CompleteTask    <br>    | TaskDueDateChanged of CmdArgs.ChangeTaskDueDate</pre><p>The data connected to each case are exactly the same we have for Commands, but don’t take this as rule of thumb. Sometimes it makes sense to have slightly different values for Events, but it is easier to start like that and change it later, if really needed.</p><h4>State</h4><p>What is the State for TodoMVC apps? Yes, it is simply the list of tasks:</p><pre>type Task = {    <br>    Id : int    <br>    Name : string    <br>    DueDate : DateTime option    <br>    IsComplete : bool<br>} <br>type State = {    <br>    Tasks : Task list<br>}<br>    with static member Init = { Tasks = [] }</pre><p>We have basic domain of our application (State, Commands, Events), so now we add few more things and glue everything together.</p><p><strong>Tip for lazybones: </strong>Copy-paste from my <a href="https://github.com/Dzoukr/Talks/blob/master/event-sourcing-cosmosdb/examples/cosmostoreApp/Domain.fs">talk example app</a>.</p><h4>State Init (a.k.a Empty State)</h4><p>How does State look like when you start with no tasks? Yes, empty list of tasks. We will need it later when applying all the Events on state (you must start somewhere). Because I am incredibly lazy, I already did this on type as static member Init so all the work here is done.</p><h4>Execute function</h4><p>Execute function is the place where Events are created based on Commands. You already know that there is no guarantee it will succeed, so it’s the perfect place for validation. And yes, you guess right, we are validating against the latest State so this is why we need it as (the first) parameter.</p><p>The function signature is &#39;state -&gt; &#39;command -&gt; &#39;event list knowing that function itself can throw exception. If you are more into <em>ROP</em> (which I am a lot), you can change signature a little bit:</p><p>&#39;state -&gt; &#39;command -&gt; Result&lt;&#39;event list, YourDomainError&gt;</p><p>Here is the beauty:</p><pre>let execute state command =     <br>    let event = <br>        match command with    <br>        | AddTask args -&gt; <br>            args.Id <br>            |&gt; onlyIfTaskDoesNotAlreadyExist state <br>            |&gt; (fun _ -&gt; TaskAdded args)    <br>        | RemoveTask args -&gt; <br>            args.Id <br>            |&gt; onlyIfTaskExists state <br>            |&gt; (fun _ -&gt; TaskRemoved args)    <br>        | ClearAllTasks -&gt; AllTasksCleared    <br>        | CompleteTask args -&gt; <br>            args.Id <br>            |&gt; onlyIfTaskExists state <br>            |&gt; (fun _ -&gt; TaskCompleted args)    <br>        | ChangeTaskDueDate args -&gt; <br>            args.Id <br>            |&gt; (onlyIfTaskExists state &gt;&gt; onlyIfNotAlreadyFinished)<br>            |&gt; (fun _ -&gt; TaskDueDateChanged args)<br>    event |&gt; List.singleton //we must return list of events</pre><p>Add few more validation functions. To keep examples simple, I’ll stick with throwing exceptions, but in real-worlds apps we use custom domain error discriminated union:</p><pre>let onlyIfTaskDoesNotAlreadyExist (state:State) i =    <br>    match state.Tasks |&gt; List.tryFind (fun x -&gt; x.Id = i) with    <br>    | Some _ -&gt; failwith &quot;Task already exists&quot;    <br>    | None -&gt; state </pre><pre>let onlyIfTaskExists (state:State) i =    <br>    match state.Tasks |&gt; List.tryFind (fun x -&gt; x.Id = i) with<br>    | Some task -&gt; task    <br>    | None -&gt; failwith &quot;Task does not exist&quot; </pre><pre>let onlyIfNotAlreadyFinished (task:Task) =    <br>    match task.IsComplete with    <br>    | true -&gt; failwith &quot;Task already finished&quot;    <br>    | false -&gt; task</pre><p>And we have new Events created based on each Command including domain validation! <em>*silent high five*</em></p><h4>Apply function</h4><p>Apply function is the place where you affect you State (the list of task in this case) by <em>applying</em> each change on State. In other words: How does Event XYZ change your State.</p><p>The signature of Apply function is &#39;state -&gt; &#39;event -&gt; &#39;state and must <strong>never</strong> throw an exception.</p><pre>let apply state event =     <br>    match event with    <br>    | TaskAdded args -&gt;         <br>        let newTask = { <br>            Id = args.Id <br>            Name = args.Name <br>            DueDate = args.DueDate <br>            IsComplete = false<br>        }        <br>        { state with Tasks = newTask :: state.Tasks}    <br>    | TaskRemoved args -&gt; <br>        { state with Tasks = state.Tasks |&gt; List.filter (fun x -&gt; x.Id &lt;&gt; args.Id) }    <br>    | AllTasksCleared -&gt; { state with Tasks = [] }<br>    | TaskCompleted args -&gt;         <br>        let task = <br>            state.Tasks <br>            |&gt; List.find (fun x -&gt; x.Id = args.Id) <br>            |&gt; (fun t -&gt; { t with IsComplete = true })        <br>        let otherTasks = state.Tasks |&gt; List.filter (fun x -&gt; x.Id &lt;&gt; args.Id)        <br>        { state with Tasks = task :: otherTasks }    <br>    | TaskDueDateChanged args -&gt;         <br>        let task = <br>            state.Tasks <br>            |&gt; List.find (fun x -&gt; x.Id = args.Id) <br>            |&gt; (fun t -&gt; { t with DueDate = args.DueDate })<br>        let otherTasks = <br>            state.Tasks <br>            |&gt; List.filter (fun x -&gt; x.Id &lt;&gt; args.Id)        <br>        { state with Tasks = task :: otherTasks }</pre><p>Looking at all three functions (actually two plus one initial value), we can wrap it in universal generic type:</p><pre>type Aggregate&lt;&#39;state, &#39;command, &#39;event&gt; = {    <br>    Init : &#39;state    <br>    Apply: &#39;state -&gt; &#39;event -&gt; &#39;state    <br>    Execute: &#39;state -&gt; &#39;command -&gt; &#39;event list<br>}</pre><p><strong>CopyPastaTip:</strong> Be lazy, <a href="https://github.com/Dzoukr/Talks/blob/master/event-sourcing-cosmosdb/examples/cosmostoreApp/Aggregate.fs">copy directly from another example.</a></p><h4>Before we continue…</h4><p>I think this is the great moment for little summary. So where we are?</p><p>We have:</p><ul><li>Domain (list of tasks)</li><li>Commands (way how to add/remove/complete tasks)</li><li>Events (results of our Commands)</li><li>Function for creating Events based on Commands (Execute) with basic built-in validation</li><li>Function for creating State based on previous Events (Apply)</li><li>Initial (empty) State we will start with</li><li>All wrapped in Aggregate type.</li></ul><pre>let tasksAggregate = {<br>    Init = State.Init<br>    Execute = execute<br>    Apply = apply<br>}</pre><p>Great time to finally involve Event Store.</p><h4>Event Store Command Handler</h4><p>From the F# signature perspective the Event Store Command Handler looks <em>almost</em> like Execute function, but it has few dependencies “baked-in” or partially applied as parameters:</p><ul><li>Event Store implementation</li><li>Aggregate type with Init, Execute and Apply functions</li></ul><p>The Command Handler flow is:</p><ol><li>Get the Command as parameter</li><li>Load all previous Events from Event Store <em>Stream</em> ordered by time they occurred</li><li>Use <em>Apply</em> function to affect <em>Init</em> State, one by one. Just a typical fold function.</li><li>Use the latest (current) State (result of folding/applying Events from previous step) as parameter for <em>Execute</em> function + use Command we got as parameter</li><li>In case we got error, we end here and return/throw error</li><li>In case Execute went ok, we now have new Events</li><li>Save (append) those new Events back to Event Store</li><li>Return new successfully created and stored Events</li></ol><p>Looking at <a href="https://github.com/Dzoukr/Talks/blob/master/event-sourcing-cosmosdb/examples/cosmostoreApp/CommandHandler.fs">another example file</a>, the quick-and-dirty sync version can be written like this:</p><pre>// create new Event Store<br>let store = CosmoStore.CosmosDb.EventStore.getEventStore myConfig</pre><pre>// get current state from Tasks stream<br>// note the use of tasksAggregate record<br>let getCurrentState () =        <br>    store.GetEvents &quot;Tasks&quot; EventsReadRange.AllEvents        <br>    |&gt; Async.AwaitTask        <br>    |&gt; Async.RunSynchronously        <br>    |&gt; List.map (fun x -&gt; Mapping.toDomainEvent (x.Name, x.Data))<br>    |&gt; List.fold tasksAggregate.Apply tasksAggregate.Init</pre><pre>// append new events to Tasks stream<br>let append events =        <br>    events         <br>    |&gt; List.map Mapping.toStoredEvent        <br>    |&gt; List.map (fun (name,data) -&gt; { Id = Guid.NewGuid(); CorrelationId = Guid.NewGuid(); Name = name; Data = data; Metadata = None })        <br>    |&gt; store.AppendEvents &quot;Tasks&quot; ExpectedPosition.Any        <br>    |&gt; Async.AwaitTask        <br>    |&gt; Async.RunSynchronously        <br>    |&gt; ignore</pre><pre>let handleCommand command =     <br>    // get the latest state from store    <br>    let currentState = getCurrentState()    <br>    // execute command to get new events    <br>    let newEvents = command |&gt; tasksAggregate.Execute currentState    <br>    // store events to event store    <br>    newEvents |&gt; append    <br>    // return events    <br>    newEvents</pre><p><strong>Note: </strong>Please check the example file for boring parts like transforming JSON payload to Events and back.</p><p>Congrats! You have fully working Event Store Command Handler! You can send Commands and get back new Events, which are stored in Event Store so your internal State is actually really changing! <em>*loud high five*</em></p><p>But what about if we want to check current state? Do we have to go to Event Store, replay all Events, and create latest state to see the list of tasks? Well, we can but we will do something different.</p><h4>Read (query) side</h4><p>Do you remember me promising you’ll get to your fancy database stuff like Entity Framework, Dapper, SQLProvider, whatever…? So here it comes.</p><p>The read (also known as query) side is the thing you’ll use for reading data in “traditional way” — from relational database. Technically it is another projection you build as reaction on Events in you system and you build it with your favorite database library/framework. It’s like <em>Apply</em> function but on different— database — layer. This is the place for making CREATE, UPDATE, DELETE SQLs and other familiar stuff.</p><p>Just have one and the only concern in mind: “It must be easily readable/queryable”. Nothing else. That is the only reason for existence of Read side. And don’t get too attached to it. You gonna destroy/rebuild it many times, because once you are in Event Sourcing, you can always replay old Events, drop old database and create brand new projection stored somewhere else, in different structure, database, file… you name it.</p><p>In our system we usually built projections with function called *<em>Event Handler</em> and we have many of those. DatabaseEventHandler, EmailEventHandler, FileEventHandler, … Signature of such handler is (again…?) pretty easy: &#39;event -&gt; unit</p><p>Need to print Events to console?</p><pre>let handleEventToConsole event = <br>    match event with<br>    | TaskAdded args -&gt; printfn &quot;Console handler says: Hurrayyyy, we have a task %s!&quot; args.Name    <br>    | TaskCompleted args -&gt; printfn &quot;Console handler says: Task with ID %A is completed&quot; args.Id    <br>    | AllTasksCleared -&gt; printfn &quot;Console handler says: ...and now they are all gone&quot;    <br>    | _ -&gt; ()</pre><p>Need to work with SQL database?</p><pre>let handleEventToSql = <br>    match event with<br>    | TaskAdded args -&gt; args |&gt; sqlInsert    <br>    | TaskCompleted args -&gt; args |&gt; sqlUpdate    <br>    | AllTasksCleared -&gt; sqlDeleteAll()    <br>    | _ -&gt; ()</pre><p>And glue them together to one handle function:</p><pre>let handle evn =    <br>    evn |&gt; handleEventToConsole    <br>    evn |&gt; handleEventToSql</pre><p><strong>AnotherAmazingTip: </strong>CTRL+C, CTRL+V from <a href="https://github.com/Dzoukr/Talks/blob/master/event-sourcing-cosmosdb/examples/cosmostoreApp/ReadSide.fs">just another example from still the same talk I am referencing to.</a></p><h4>Final pipeline</h4><p>It’s the final pipelineeeeeeee, 🎵🎵, tududuuuu, dudu, <em>*air guitar*</em><br>…ok where was I?</p><p>Final pipeline is the function you’ll use in your Console/Giraffe/Suave/Saturn application as composition of Event Store Command Handler and Event Handler(s).</p><pre>// simple function composing command handler + event handlers<br>let pipeline cmd =    <br>    cmd <br>    |&gt; CommandHandler.handle<br>    |&gt; List.iter ReadSide.handle</pre><p>So that’s all kids. Really, there is nothing else. Go home now. Thanks for attention and see you next time. Questions?</p><p>…Ufffff, ok. You, girl in brown sweater.</p><h4>Q: Why should you even think about writing apps this way?</h4><p>A: There are many advantages of such approach:</p><ul><li>You never lose any data. You just store all the data you have about Events and decide later (can be 1ms after, but 1 year as well) what kind of information you are interested in.</li><li>Absolutely DDD friendly. Design your domain the way you think it should be and define Events around.</li><li>Thinking and talking in Events makes communication with customer much easier. They don’t understand models, relations, constraints or foreign keys, but they will tell you after <em>OrderReceived </em>there should be <em>EmailSent</em>. You are now talking in same language.</li><li>You get fully trustworthy audit log by design.</li><li>You can replay old Event and get new information from them. For marketing, security or whatever reason (somebody said “bugfixing”?), you can go through all the Events from the very beginning and create new projections.</li></ul><p>…Great, another one. You, little boy with Java is GR8 t-shirt.</p><h4>Q: Can we rename Command Handler to IBusinessDomainEventFactoryProxyImplProvider?</h4><p>A: Awesome question, thanks for that! Absolutely not.</p><p>…next?</p><h4>Q: Why you shouldn’t do Event Sourcing?</h4><p>A: There are many reasons why to avoid this approach:</p><ul><li>Like it or not, the complexity of application is much higher than simple CRUD against SQL table.</li><li>Restoring State from stored Events can be expensive. Speaking about thousands of Events in single Stream, it can take some time. If your application is performance-first + invalidating State every few milliseconds (gaming apps?), Events Sourcing is not for you.</li><li>Until you get all your read side data from Event Store (which you still can, but can be ineffective), you are in the world of <em>eventual consistency.</em></li><li>Events migrations / versioning is not piece of cake.</li><li>Correct splitting domain into aggregation roots and storing in Streams is probably the most difficult part I can think of.</li></ul><p>…last one? Really, guys, I need to go trolling NuGet team about reinventing lock file, so time for the last question.</p><h4>Q: You’ve sold me Event Sourcing, where should I go next?</h4><p>A: If you need book, the great one is <a href="https://pragprog.com/book/swdddf/domain-modeling-made-functional">Domain Modeling Made Functional</a> by Scott Wlaschin. Once you get deeper you really appreciate (not completed yet, sic) <a href="https://leanpub.com/esversioning">Versioning in Event Sourced systems</a> by Greg Young who also gives <a href="https://www.youtube.com/watch?v=LDW0QWie21s">great talks about CQRS &amp; Event Sourcing</a>. In F# community there is amazing <a href="https://www.youtube.com/watch?v=bW0ZQAofro8">Roman Sachse’s talk from FableConf 2018 RemmiDemmi track</a>. And if you are in (or close to) Czech Republic we will be happy to welcome you at our <a href="https://fsharping.com/">F# meetups called FSharping</a> where we can discuss further.</p><p>Thank you for reading and Marry Christmas to all of you! See ya in 2019!</p><p><em>*running frightened to car and drifting away*</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=be808aa0ca18" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[F# in 2018?]]></title>
            <link>https://medium.com/blueberry/f-in-2018-42f8dc5c5d7b?source=rss-43a58c6c8a64------2</link>
            <guid isPermaLink="false">https://medium.com/p/42f8dc5c5d7b</guid>
            <category><![CDATA[lambdup]]></category>
            <category><![CDATA[fsharp]]></category>
            <dc:creator><![CDATA[Roman Provazník]]></dc:creator>
            <pubDate>Mon, 16 Jul 2018 05:55:12 GMT</pubDate>
            <atom:updated>2018-07-16T12:38:46.501Z</atom:updated>
            <content:encoded><![CDATA[<p>Somebody recently asked me, “Why should I bother with a .NET language like F# in 2018, when I have tons of other possibilites?” Good question! Since lists are so popular that even <a href="https://youtu.be/sqA577_IoBk?t=1m17s">Liam Neeson makes them</a>, here is mine. Take it as a “just off my head” list with no particular order. It’s more like an elevator pitch in really huuuuge building, like Burj Khalifa in Dubai:</p><h4>.NET Core</h4><p>It might seem strange to start a list of language features with something not tightly connected to language itself, but .NET Core is really a major leap from “traditional” big (legacy?) .NET framework. And not only because it is brand new (from an implementation point of view, of course - BCL APIs legacy is quite hard to break). Its aim for multi-platform development &amp; <a href="https://blogs.msdn.microsoft.com/dotnet/2018/04/18/performance-improvements-in-net-core-2-1/">performance</a> makes .NET Core a great choice for a wide area of applications. Web, desktop, running in Docker or Cloud, you name it.</p><p>Microsoft has been investing in .NET Core a lot and considers it to be the future of .NET development. And it will succeed, like it or not. It is a strong platform already, but using it with a highly-productive, multi-paradigm language like F# takes it to the next level.</p><h4>REPL</h4><p>Also known as Read-Evaluate-Print-Loop. What does it mean? You simply highlight your code in IDE, press ALT+Enter, and see the result immediately. No waiting for compiling, attaching a debugger and other endless instrumentation. Just one keystroke and you know whether your F# code works or not. It has been years since I found this feature and I still love it like the first day. Once you get used to it, REPL will simply become an essential part of development.</p><h4>Ionide</h4><p>.NET development has been always connected with “big” Visual Studio IDE. It is not bad IDE at all, but it has its own issues and again… legacy plays its part as well. But we are in multi-platform world, right? We have other possibilities. One of the greatest is the open source VS Code editor (VS means Visual Studio here, but this shortcut is frankly the only thing they have in common). An electron-based editor with (hundreds of?) thousands of extensions ready to make it your new favorite editor. And speaking of extensions… the one you can’t miss is called <a href="http://ionide.io/">Ionide</a> — an open source F# plugin for intellisense, error checking, tooltip, REPL and many more. Also with support for other widely used F# libraries like FAKE or Paket, it’s a must-have for F# in VS Code!</p><h4>Fable</h4><p>If you ever heard about .NET you probably know that you can develop web applications, cloud solutions and traditional desktop clients. This is what .NET has been about for years. But what about the language that rules them all (a.k.a. JavaScript)? Well, that’s why <a href="https://www.fable.io/">Fable </a>was created. Fable is an F# to JavaScript compiler, powered by <a href="https://babeljs.io/">Babel</a>, designed to produce readable and standard code. If you check the Fable homepage you will find title:</p><blockquote>The compiler that emits JavaScript you can be proud of!</blockquote><p>And based on what other JavaScript developers say about Fable (I am not able to distinguish between nice and terrible code in JavaScript, so my opinion doesn’t matter :)), it does it quite well.</p><p>Did you know Fable is so popular that <a href="http://fable.io/fableconf">it has its own conference?</a></p><h4>OSS libraries</h4><p>What would an ecosystem be without good (free) libraries? Fortunately, F# has an active community producing great libraries for various types of applications. Do you like functional web development? Checkout <a href="https://github.com/giraffe-fsharp/Giraffe">Giraffe</a>, <a href="https://freya.io/">Freya</a>, <a href="https://suave.io/">Suave</a>, or <a href="https://saturnframework.github.io/docs/">Saturn</a>. Want to work with databases in a safe manner? Be my guest! <a href="http://fsprojects.github.io/SQLProvider/">SQLProvider</a> is here for you. Working with JSON, XML, CSV files? Grab one of the most famous type providers, <a href="http://fsharp.github.io/FSharp.Data/">FSharp.Data</a>. I could write pages and pages about great open source F# libraries, but I’ll keep exploring them for you instead. A great place to start is <a href="http://fsprojects.github.io/">fsprojects.github.io</a>, where you can choose whatever you need.</p><h4>Community</h4><p>Although this isn’t a technical point, it’s the most important one. You can have the best language in the world, but it would be useless without an active community. As mentioned in the previous point, F# has an active community creating great libraries, but it is still not the most important part. The F# community is the friendliest one I have ever seen. Always ready to help, welcoming to newcomers, supporting speakers (also financially) to give talks around the world, and a sense of (black) humour, and silly jokes. Check Twitter with the #fsharp hashtag and you’ll see. ;)</p><p>Oh! I forgot to mention, we have also Czech community called <a href="http://www.fsharping.com/">FSharping</a>. The same characteristics apply, but maybe with little more black humor. Do not hesitate to look for the next meetup date and come visit us. You’re gonna love it, I promise!</p><h3>Summary</h3><p>So now you know why F# is great choice for your next .NET Core project. I could probably write a list three times as long, name all the cool libraries, and show some snippets, but sorry… I have VS Code opened, and need to write some cool F# code. It is so addictive!</p><p>I hope you like it and if you want to see the creator of Fable live (you should!!!), get some tickets for an amazing conference I am personally involved in:</p><p><a href="http://lambdup.io/"><strong>LambdUp 2018</strong></a><strong> in Prague, Czech Republic.</strong></p><p>See you there!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=42f8dc5c5d7b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/blueberry/f-in-2018-42f8dc5c5d7b">F# in 2018?</a> was originally published in <a href="https://medium.com/blueberry">Blueberry</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why FP matters even for OOP developer?]]></title>
            <link>https://medium.com/blueberry/why-fp-matters-even-for-oop-developer-7cb05b4a9856?source=rss-43a58c6c8a64------2</link>
            <guid isPermaLink="false">https://medium.com/p/7cb05b4a9856</guid>
            <category><![CDATA[fsharp]]></category>
            <category><![CDATA[lambdup]]></category>
            <category><![CDATA[oop]]></category>
            <category><![CDATA[functional-programming]]></category>
            <dc:creator><![CDATA[Roman Provazník]]></dc:creator>
            <pubDate>Tue, 28 Nov 2017 07:23:32 GMT</pubDate>
            <atom:updated>2017-12-01T15:40:14.556Z</atom:updated>
            <content:encoded><![CDATA[<p>I was asked by my friends (and co-organizers of the <a href="http://lambdup.io/">LambdUp </a>conference) to give my personal view on functional programming from an object–oriented perspective. I was even forced to create Medium account :) but I`ll do much as I can to help promote this great micro-conference. And as an ex-OOP developer and current one-day-maybe-I-gonna-make-it-to-proper-FP-developer, I think I actually have a few words to share:</p><h3>Welcome traveler</h3><p>If you haven&#39;t spent the last sixty years on different planet (if so, then welcome back fellow traveler!), you probably heard about functional programming. If you watch trends in the software industry, you hear phrases like &#39;functional programming&#39;, &#39;immutability&#39;, &#39;pure functions&#39;, and composition&#39; on a daily base. Everything sounds cool, amazing and clear until you realize, &#39;Hey! I am an OOP developer and cannot (or not willing to) move to different paradigm. What can functional programming offer to me? Why should I care?&#39; Well, as a functional developer/enthusiast coming mostly from OOP world, I am happy to share some things I wish somebody told me many years ago. We could talk about it for hours, so let’s choose at least three most important.</p><h3>Immutability</h3><p>The “traditional” benefit of FP is a word that occupies at least two slides on each presentation about functional programming. The silver bullet of FP, right? Well… No. Even though this word is heavily used mostly by functional programmers, it is not exclusive for FP. You, as an OOP developer, can achieve (almost) the same level of immutability as an FP developer. Actually, you can achieve it quite easily — just change the way how you look at your objects and collections. Think about change as something that does not change the origin, but instead creates a new version. Did you add an item to the collection? Great! You did not change the original one, but instead you got a brand new collection containing the added item. Did you change object`s property? Cool! Then you got a brand new object with a changed property.</p><p>I know, I know — it sounds strange. But this little mind-switch will give you the longer, calmer sleep at night. Once you know that your objects cannot be changed (only copied), you know that there is nobody in your team able to reset it somewhere else. It is like lending your favorite, ancient Pink Floyd audiotape without the fear that you`ll get it back replaced with Justin Bieber. And as a bonus, your code base will have fully trackable methods where real change happens (where the new objects are created based on original ones). And I almost forgot — if you are a C# or Java developer, you already use them calling methods like “ToLower()”, “Trim()” on strings, which are immutable by default. So actually it&#39;s nothing new for you.</p><h3>Pure functions</h3><p>Another fancy phrase wrongly considered to be FP only. What is &#39;pure function&#39;? Simply put, pure function is a function that returns the same output for the same input, without any connection to the “outer world” (IO operations, shared state, etc…) a.k.a. &#39;side effects&#39;. The typical examples for these kind of functions are getting a length of string (you probably won&#39;t call database for counting chars in string, right?), calculation of sine for integer, and so on. What is the benefit of an OOP world? Just the same as for FP. Once you work with pure functions (or methods), you know what result you&#39;ll get for each input. And if your code does not depend on any hidden state, it is so easy to test, that it won&#39;t even bother you to write a unit test. We all know that without interaction with outer world, our software would be useless, but there is a significant difference in having pure core (built on pure-only functions/methods) with IO on the edge of the system or having a system where each method depends on the internal state triggered by recalling other methods.</p><p>Once again, a little mind-switch of thinking about input and output of your methods will give you all the benefits of FP plus your testing will be so easy, that you&#39;ll start to actually enjoy it.</p><h3>Declarative vs Imperative</h3><p>We already changed how we look at our code — we can write safer (immutable) and testable (pure) code. Now is an excellent time to push ourselves a little bit further and change the way how we define what our software should do. What is the more significant here between OOP and FP? In functional world, we are used to defining what should happen instead of how it should happen. Of course, there must be still the part of program that does that particular operation, but the trick is to focus on expressions instead of statements. And that is something you can do in your favorite OOP language.</p><p>Again, if you are familiar with things like LINQ (from C#), you already know the benefits by using query expressions where you can read your code after yourself and say, &#39;Oh, here I take last 10 items from collection, sort them alphabetically and use them as a parameter for this particular method.&#39; You&#39;ve probably read thousands of similar LINQ expressions without needing to think what is actually happening behind the scenes. A that&#39;s the whole point: focus on what really matters.</p><h3>Summary</h3><p>I think I&#39;ll stop writing for now. I don&#39;t want to end up with selling FP as a silver bullet. World is not just black and white. The truth is that for me FP is incredibly hard. Almost as hard as writing OOP correctly. But it&#39;s definitely worth trying. From my point of view OOP vs FP is mostly about how I think about code and its structure. How do I think about dependencies, side effects, whole IO universe and testing. If you could take single thought from this short article, let it be: “Functional approach can help you no matter the language, domain, platform.”</p><p>Ok, uff, I did it. Thanks to people from <a href="https://www.blueberry.io/">Blueberry</a>, my home company <a href="http://www.cngroup.dk/">CN Group</a> and other partners for organizing great <a href="http://lambdup.io/">LambdUp </a>conference! You&#39;ll find me there playing PS4 &amp; talking about how great is <a href="http://fsharp.org/">F# language</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7cb05b4a9856" width="1" height="1" alt=""><hr><p><a href="https://medium.com/blueberry/why-fp-matters-even-for-oop-developer-7cb05b4a9856">Why FP matters even for OOP developer?</a> was originally published in <a href="https://medium.com/blueberry">Blueberry</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>