<?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 Tristian Barrett on Medium]]></title>
        <description><![CDATA[Stories by Tristian Barrett on Medium]]></description>
        <link>https://medium.com/@trbarrett_10189?source=rss-946d9a2a4ce0------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*dmbNkD5D-u45r44go_cf0g.png</url>
            <title>Stories by Tristian Barrett on Medium</title>
            <link>https://medium.com/@trbarrett_10189?source=rss-946d9a2a4ce0------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 23:58:26 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@trbarrett_10189/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[A poor mans dependency injection]]></title>
            <link>https://medium.com/@trbarrett_10189/a-poor-mans-f-dependency-injection-3c981f767242?source=rss-946d9a2a4ce0------2</link>
            <guid isPermaLink="false">https://medium.com/p/3c981f767242</guid>
            <dc:creator><![CDATA[Tristian Barrett]]></dc:creator>
            <pubDate>Mon, 09 Dec 2024 10:08:17 GMT</pubDate>
            <atom:updated>2024-12-09T12:13:50.362Z</atom:updated>
            <content:encoded><![CDATA[<h4>for F# and AWS Lambda</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*lfswTxi6o9keD23QPrp0sw.png" /></figure><p><em>Big thanks to Sergey Tihon for his weekly F# newsletters and organising the </em><a href="https://sergeytihon.com/2024/10/26/f-advent-calendar-in-english-2024/"><em>F# Advent Calendar</em></a><em>.</em></p><p>Originally this blog post was going to be titled “Functional Core, Functional Shell”. I’ve heard the term “Functional Core, Imperative Shell” so many times that I had wanted to go through the many ways we make a fully Functional Shell work at <a href="https://www.totallymoney.com/">TotallyMoney</a> using AWS Lambda and microservices.</p><p>That turned out far too big for a single blog post though, and even this is stretching the limits. So I’ve limited this to just focusing on the configuration and dependency setup side of our apps.</p><p>We have a fair bit of variability in our services at TotallyMoney as we‘ve continued to look for better ways to do things over the last half a decade, but this is quite representative of how our F# lambdas deal with setup and configuration. It‘s not the fanciest system by any means, but for our IO dominant workloads it‘s proven to be very resilient and easy to work with.</p><p>You’ll find the examples I use are probably a bit heftier and uglier than most tutorials, but I wanted to show you what F# code close to production would look like.</p><h4>AWS Lambda</h4><p>First for those that are unfamiliar with AWS Lambda and similar FaaS (functions as a service) offerings, let me give you a little rundown of the relevant parts for this article.</p><p>For every request that hits your lambda, AWS will dedicate an instance to handling that request, and only that request. It will allocate the CPU and RAM that you’ve asked for, setup the environment to run your code, and call into a handler function that you’ve supplied with the request details it has received.</p><p>The major difference between a Lambda and a traditional web server solution is that you’re only handling <strong>one single request</strong> per instance. With a traditional web server, like <a href="https://github.com/giraffe-fsharp/Giraffe">Giraffe</a> or <a href="https://suave.io/">Suave</a>, it could be handling thousands of requests at the same time. Spinning up processes and threads, and re-entering them with .net async. With lambda you have one request and only one request at a time.</p><p>Now in practice lambda won’t create a whole new instance of your application for every request. If your instance has just finished handling a request and a new one comes in it will reuse the same instance again. What holds true regardless, is that your application will only ever be handling one request at a time per instance.</p><p>For our purpose that’s important, because we can never assume we have our configuration and infrastructure available to be used when a request hits. With a traditional web service we would set up logging, db connection pools, etc before accepting a request. With lambda that’s inverted. We’ve accepted a request and there’s a good chance there’s nothing setup. And that’s going to make things look a bit different from how you handle a normal request.</p><p>On the opposite side, once you return a response from your handler AWS will stop the world on your service. If another thread is half way through sending data to a db, too bad. AWS will kill that running service. That’s generally useful knowledge when working with lambdas, but for our case it means that even with a reused lambda instance there’s a lot of infrastructure things that we should avoid reusing. Unless you know under the hood your db or message broker library is completely stateless (and isn’t trying to keep alive a connection or do some buffering) it’s best to start from scratch each time you get a new request.</p><p>One possibly obvious thing worth mentioning for those not familiar with lambdas: most codebases will have the code for more than one lambda. Yes there are a few microservices out there which do exactly one thing (e.g. convert text to pdf), but most services — even micro ones — will need multiple endpoints. So you will regularly have the same codebase running in different lambdas, taking very different code paths.</p><h4>From the bottom — A database request</h4><p>So that’s all of the background, on with the show!</p><p>Let’s start bottom up. We’re going to have services that will need configuration, logging, ways of initiating a connection etc.</p><p>We could pass all that information through each function in our call stack, down down down to where it’s needed, but that’s going to be a lot of parameters that are useless for most functions. So we’re going to use partial application to set them up.</p><p>Here’s a simple, though rather boring, function to write a customer id and name to a AWS DynamoDB table:</p><pre>module DataAccess<br><br>open System.Diagnostics<br>open Amazon<br>open Amazon.DynamoDBv2<br>open Amazon.DynamoDBv2.Model<br>open Serilog<br><br>let getClient connectionConfig =<br>    AmazonDynamoDBConfig(RegionEndpoint = connectionConfig.Region,<br>                         Timeout = Nullable (TimeSpan.FromSeconds 2.))<br>    |&gt; new AmazonDynamoDBClient<br><br>let addCustomerName config<br>                    (logger : ILogger)<br>                    (customerId : Guid)<br>                    (name : string) =<br>    let tableName = config.CustomerTableName<br>    let sw = Stopwatch.StartNew()<br>    try<br>        use client = getClient config<br>        let data =<br>            [ (&quot;CustomerId&quot;, AttributeValue(S = customerId.ToString()))<br>              (&quot;Name&quot;, AttributeValue(S = customerName)) ]<br>            |&gt; Seq.toDictionary<br><br>        client.PutItemAsync(PutItemRequest(tableName, data))<br>        |&gt; Async.AwaitTask<br>        |&gt; Async.RunSynchronously<br>        |&gt; ignore<br><br>        logger.Information(<br>            &quot;Completed &#39;{DataAccessEvent}&#39; for customer: {CustomerId}, on table: {TableName}, in {Elapsed} ms&quot;,<br>            &quot;Put Customer&quot;, customerId, tableName, sw.ElapsedMilliseconds)<br>        Ok ()<br>    with<br>    | ex -&gt;<br>        logger.Error(<br>            ex, &quot;Error performing &#39;{DataAccessEvent}&#39; for customer: {CustomerId}, on table: {TableName}, in {Elapsed} ms&quot;,<br>            &quot;Put Customer&quot;, customerId, tableName, sw.ElapsedMilliseconds)<br>        Error (DataAccessError (msg, Some ex))</pre><p>There’s a lot going on here. I’ll skip over the AWS Dynamo stuff since that’s not the point of the article, thought there’s a few things mentioning:</p><ul><li>We’re ignoring the async nature of <strong><em>PutItemAsync</em></strong>, and just blocking on it. Since Lambdas are only running a single request at a time we lose out on a lot of the advantages of async and how it helps web servers get higher throughput. For many situations the extra complexity carrying around an Async type all over the codebase really isn’t worth it.</li><li>We’re ensuring we always return a <strong><em>Result</em></strong> type. I’m not going to go into the details in this article, but generally we find it’s best not to mix and match error handling types, and we stick with F# Results throughout our stacks.</li></ul><p>But for an article about dependency injection the main thing worth pointing out are our first 2 arguments are just config and logging.</p><pre>let addCustomerName config<br>                    (logger : Logger)<br>                    (customerId : Guid)<br>                    (name : string) =</pre><p>Now most callers of this function don’t really care for the config and logging details. They just want to store some data. They certainly don’t want to have to carry around those parameters simply so they can call this function.</p><p>So let’s handle that during setup. We’ll create a <em>configure</em> function on our data access module which returns a partially applied function to use later.</p><pre>let configureDataAccess dataAccessConfig (logger : Logger) =<br>    logger.Debug(&quot;Configuring Dynamo db access with config: {DataAccessConfig}&quot;,<br>                 sprintf &quot;(%A)&quot; dataAccessConfig)<br><br>    addCustomerName dataAccessConfig logger</pre><p>Now we can call <strong><em>configureDataAccess</em></strong> during setup and we will have a <strong><em>addCustomerName</em></strong> function we can pass around, without the need to pass the config or logging.</p><h4>Dependency Injection Baby Steps</h4><p>Right, but in practice we’re going to have more than one function for our data access. Most database tables will have at least 3 functions: <em>get</em>, <em>put</em> and <em>delete,</em> with many more possible. While we could have a separate configure steps for each, and pass each individual one around that’s going to get messy fast.</p><p>What we tend to do at TotallyMoney is the <a href="https://grugbrain.dev/">dumbest thing possible</a>: Whack them all in an F# record:</p><pre>type DataAccess =<br>    { AddCustomerName : System.Guid -&gt; string -&gt; Result&lt;unit, ApplicationError&gt;<br>      GetCustomerName : System.Guid -&gt; Result&lt;string option, ApplicationError&gt;<br>      DeleteCustomerName : System.Guid -&gt; Result&lt;unit, ApplicationError&gt; }<br><br>let configureDataAccess dataAccessConfig (logger : Logger) =<br>    logger.Debug(&quot;Configuring Dynamo db access with config: {DataAccessConfig}&quot;,<br>                 sprintf &quot;(%A)&quot; dataAccessConfig)<br><br>    { AddCustomerName = addCustomerName dataAccessConfig logger<br>      GetCustomerName = getCustomerName dataAccessConfig logger<br>      DeleteCustomerName = deleteCustomerName dataAccessConfig logger }</pre><p>Now many people will tell you to <a href="https://stackoverflow.com/questions/34011895/f-how-to-pass-equivalent-of-interface/34028711#34028711">use interfaces instead</a>. They’re perfectly correct. Listen to them. But come closer and I’ll let you into a secret: for real world code, functions on records are <a href="https://medium.com/@dogwith1eye/prefer-records-of-functions-to-interfaces-d6413af4d2c3">really simple</a> and work really nicely… but if you want the purity at a cost of a little extra complexity there are <a href="https://medium.com/@lanayx/dependency-injection-in-f-the-missing-manual-d376e9cafd0f">great examples of using interfaces</a> out there.</p><p>Other people may tell you that bundles of functions are a poor design. They’re right too. Listen to them. Then when you have 20 different partially applied functions being passed down your call stack for: authentication, encryption, 2 databases, cache service, messages bus and 3 external apis, you’ll find you probably want to bundle them somehow (and goodness help you if you simply want to right click and go to the implementation).</p><h4>Don’t do dependencies per Handler</h4><p>Now remember how I mentioned you can have different lambdas running the same codebase? Well you’re probably thinking that you won’t need all of those infrastructure functions for each different lambda, and each <em>handler</em> should just have the one’s it needs to do the job at hand.</p><p>Let’s create an example of what that might look like. Here’s a <em>workflow</em> function that will do a bunch of the impure nastiness we need:</p><pre>let mySeriousWorkflow<br>    encryptionFn<br>    sendMessage<br>    queryDatabase<br>    getDataFromApi<br>    callOtherApi<br>    requestData<br>    =<br><br>    requestData<br>    |&gt; getDataFromApi <br>    |&gt; queryDatabase<br>    |&gt; callOtherApi<br>    |&gt; DomainModule.doDomainStuff<br>    |&gt; encryptionFn<br>    |&gt; sendMessage<br>    </pre><p><a href="https://pragprog.com/titles/swdddf/domain-modeling-made-functional/">Textbook stuff.</a></p><p>And lets say you have 3 lambdas.</p><ul><li>Lambda A will have a <em>handler</em> calling the <em>workflow</em> function above.</li><li>Lambda B’s <em>handler</em> will call another <em>workflow</em> function. It doesn’t need <strong><em>encryptionFn </em></strong>or <strong><em>getDataFromApi</em></strong>. But it does need <strong><em>getDataFromApi2</em></strong>.</li><li>Lambda C’s <em>handler</em> will call yet another <em>workflow</em> function. It needs <strong><em>putInDatabase</em></strong>, <strong><em>removeFromDatabase</em></strong>, but not <strong><em>callOtherApi</em></strong>, <strong><em>encryptionFn</em></strong> or <strong><em>getDataFromApi</em></strong>.</li></ul><p>Now you’ll need to configure each of those lambda handlers separately. Since they each use different functionality the setup for each will need to be different. This is what Lambda A’s <em>handler</em> might look like:</p><pre>[&lt;LambdaSerializer(typeof&lt;DefaultLambdaJsonSerializer&gt;)&gt;]<br>let lambdaA requestData (lambdaContext : ILambdaContext) = <br>    let logging = setupLogging lambdaContext<br>    let config = getConfig lambdaContext<br>    let encryptionFn = setupEncryption config logging<br>    let sendMessage = configureSendMessage config logging<br>    let queryDatabase = configureQueryDatabase config logging<br>    let getDataFromApi = configureGetDataFromApi config logging<br>    let callOtherApi = configureCallOtherApi config logging<br><br>    mySeriousWorkflow<br>        encryptionFn<br>        sendMessage<br>        queryDatabase<br>        getDataFromApi<br>        callOtherApi<br>        requestData</pre><p>I’ll leave B (which doesn’t need <strong><em>encryptionFn</em></strong> or <strong><em>getDataFromApi</em></strong><em> </em>but does need <strong><em>getDataFromApi2</em></strong>) and C as homework.</p><p>So yes you can absolutely do that, and we have in the past, but we’ve found that it creates a great deal of busy-work and boiler plate doing them all separately:</p><ul><li>It’s a lot of duplicate code on each <em>handler</em></li><li>It’s a lot of duplicate code in unit and integration tests</li><li>It’s brittle - small dependency changes can cause a cascade of changes all over the codebase.</li><li>It’s a lot of text that gets in the way of understanding the core aspect of what code is actually trying to do</li><li>It makes PRs and commits a great deal heavier</li></ul><p>So while bundling dependencies may be considered by some to be the “wrong” way to do things, from a pragmatic point of view we find it really helpful.</p><p>Note: I’ve left something unsaid in all of this which is that we strive to keep our <em>handler</em> code seperate from our <em>workflow</em> code. As much as possible we want to keep the AWS Lambda related code decoupled from the line-of-business specific code. In theory the <em>workflow</em> code could be used by a command line or another environment. And from the other side we might want to change the <em>handler</em> to be triggered from an API Gateway, or SNS, or SQS, or one of a myriad of ways you can call into a lambda from AWS.</p><h4>We have Dependency Injection at home</h4><p>That leads us to our next section. The app context.</p><p>When we have several of these different partially applied services like the <strong><em>DataAccess</em></strong> one above we want to bundle them up to configure them all in one go and pass them around as a single item.</p><p>That single item, we generally call the AppContext. It’s there to hold any contextual information the application may need outside of what’s in the request. So databases and other services, yes, but also things like feature flags, or specific configuration items.</p><p>Here’s how that <em>AppContext</em> might look:</p><pre>type AppContext =<br>    { DataAccess : CustomerDataAccess<br>      DataCollection : DataCollection<br>      Encryption : EncrpytionHelper<br>      ThirdParty : ThirdPartyApiClient<br>      InternalService : InternalServiceApiClient<br>      SNSClient : SNSClient<br>      MyFeatureFlag : bool<br>      Logger : Logger<br>      Now : unit -&gt; DateTimeOffset }<br><br>module AppContext =<br>    type TimeProvider = unit -&gt; DateTimeOffset<br><br>    let configure dataAccessConfig<br>                  dataCollectionConfig<br>                  thirdPartyConfig<br>                  internalServiceConfig<br>                  snsConfig<br>                  lambdaContext<br>                  myFeatureFlag<br>                  logger<br>                  (timeProvider : TimeProvider) =<br>        let dataAccess =<br>            DataAccess.configureDataAccess dataAccessConfig logger<br>        let dataCollection =<br>            DataCollection.configureDataCollection dataCollectionConfig logger<br>        let thirdPartyClient =<br>            ThirdParty.configureClient thirdPartyConfig logger<br>        let internalServiceClient =<br>            InternalService.configureClient internalServiceConfig logger<br>        let encryption =<br>            EncriptionHelper.configure lambdaContext<br>        let snsClient =<br>            configureSNSClient snsConfig<br>        { DataAccess = dataAccess<br>          DataCollection = dataCollection<br>          Encryption = encryption<br>          ThirdParty = thirdPartyClient<br>          InternalService = internalServiceClient<br>          SNSClient = snsClient<br>          Logger = logger<br>          Now = timeProvider }</pre><p>There’s nothing fancy going on the there. It’s just a poor mans dependency injection where we’re doing all the wiring up ourselves, but here’s how it looks in practice using the example above:</p><pre>let mySeriousWorkflow ctx requestData =<br>    requestData<br>    |&gt; ctx.ThirdParty.GetDataFromApi <br>    |&gt; ctx.DataAcecss.QueryDatabase<br>    |&gt; ctx.InternalService.CallOtherApi<br>    |&gt; DomainModule.doDomainStuff<br>    |&gt; ctx.Encryption.Encrypt<br>    |&gt; ctx.SNSClient.SendMessage<br><br>[&lt;LambdaSerializer(typeof&lt;DefaultLambdaJsonSerializer&gt;)&gt;]<br>let lambdaA requestData (lambdaContext : ILambdaContext) = <br>    let logging = setupLogging lambdaContext<br>    let ctx = AppContext.configure .. // I&#39;ll describe config setup later<br>    mySeriousWorkflow ctx requestData</pre><p>Yes each line in the <em>workflow</em> is a bit more convoluted, but it does add quite a bit of context to what each line is doing (more so when you’re not dealing with toy examples).</p><p>Importantly it:</p><ul><li>Gets rid of all the duplication in the parameters</li><li>Gets rid of all the setup duplication in the <em>handlers</em></li><li>It means changes to services and their functions don’t ripple through your system and tests.</li><li>Makes it easy to get to the implementation of the code. A right-click go to implementation will land you within a few 10s of lines of where the function is defined.</li><li>Makes testing a lot easier.</li></ul><p>On that last point of making testing a lot easier it obviously simplifies the functions calls, but it also means you can have a simple setup function (for unit, or integration tests) which you can reuse for 90% of tests. In our example it might look something like this:</p><pre>let testAppContext now =<br>    { DataAccess = dockerDataAccessClient<br>      DataCollection = dockerDataCollectionClient<br>      Encryption = { Encrypt: id; Decrypt: id }<br>      ThirdParty = dockerThirdPartyMock<br>      InternalService = dockerInternalServiceMock<br>      SNSClient = stubSnsClient<br>      MyFeatureFlag = true<br>      Logger = Serilog.Logger.Log<br>      Now = fun () -&gt; now }</pre><p>Then you can modify that where tests that need something unusual:</p><pre>// arrange<br>let ctx =<br>    { testAppContext DateTimeOffset.Now with<br>        // in this specific test we&#39;ll see what happens during an error<br>        DataAccess.addCustomerName = fun _ -&gt; Error (ConnectionTimeout) }<br><br>// act<br>mySeriousWorkflow ctx testRequestData</pre><h4>Config</h4><p>Right we’ve got our AppContext module. Now we finally need to do the configuration.</p><p>Like all <a href="https://12factor.net/config">good applications</a>, our configuration lives in the environment. So let’s grab those config settings:</p><pre><br>open System<br>open Amazon<br>open Amazon.Lambda.Core<br><br>module Environment =<br>    let envVars = seq {<br>        let d = Environment.GetEnvironmentVariables()<br>        for key in d.Keys do yield (string key, string d.[key]) } |&gt; Map.ofSeq<br><br>    let tryItem key =<br>        envVars<br>        |&gt; Map.tryFind key<br>        |&gt; Result.ofOption (sprintf &quot;Env var `%s` not found&quot; key)<br><br>type Config =<br>    { Version : string<br>      Environment : string<br>      AwsRegion : RegionEndpoint<br>      DynamoCustomerNamesTable : string<br>      ThirdPartyApiUrl : string<br>      SnsTopicArn : string<br>      MyFeatureFlag : string }<br><br>module Config =<br><br>    let getConfig () : Result&lt;Config, ApplicationError&gt; =<br>        try<br>            result {<br>                let! version = Environment.tryItem &quot;VERSION&quot;<br>                let! environment = Environment.tryItem &quot;ENVIRONMENT&quot;<br>                let! awsRegion = Environment.tryItem &quot;AWS_REGION&quot;<br>                let! dynamoCustomerNamesTable =<br>                    Environment.tryItem &quot;DYNAMO_CUSTOMER_NAMES_TABLE&quot;<br>                let! thirdPartyApiUrl =<br>                    Environment.tryItem &quot;THIRD_PARTY_API_URL&quot;<br>                let! snsTopicArn =<br>                    Environment.tryItem &quot;SNS_TOPIC_ARN&quot;<br>                let! myFeatureFlag = <br>                    Environment.tryItem &quot;MY_FEATURE_FLAG_SETTING&quot;<br><br>                return<br>                    { Version = version<br>                      Environment = environment<br>                      AwsRegion = awsRegion |&gt; RegionEndpoint.GetBySystemName<br>                      DynamoCustomerNamesTable = dynamoCustomerNamesTable<br>                      ThirdPartyApiUrl = thirdPartyApiUrl<br>                      SnsTopicArn = snsTopicArn<br>                      MyFeatureFlag = myFeatureFlag}<br>            }<br>            |&gt; Result.mapError ConfigurationError<br>        with ex -&gt;<br>            Error (ConfigurationError (ex.ToString()))</pre><p>And use them to setup our app config:</p><pre>    let setupAppConfig lambdaContext cfg logger =<br>        let dataAccessConfig =<br>            { Region = cfg.AwsRegion<br>              CustomerTableName = cfg.DynamoCustomerNamesTable }<br><br>        ...<br><br>        let snsConfig : SNS.SNSConfig =<br>            { Publish = SNS.publish logger<br>              TopicArn = cfg.SnsTopicArn }<br><br>        AppContext.configure dataAccessConfig<br>                             dataCollectionConfig<br>                             thirdPartyConfig<br>                             internalServiceConfig<br>                             snsConfig<br>                             myFeatureFlag<br>                             lambdaContext<br>                             logger<br>                             (fun () -&gt; DateTimeOffset.Now)</pre><p>Very close now. Let’s tie that all together with some logging and we’re done:</p><pre>    let setupAndCreateAppContext lambdaContext =<br>        try<br>            match getConfig () with<br>            | Error err -&gt;<br>                writeToStdErrAsStructuredJson $&quot;Configuration Error: %A{error}&quot;<br>                Error err<br><br>            | Ok cfg -&gt;<br>                match configureLogging cfg lambdaContext with<br>                | Error err -&gt;<br>                    writeToStdErrAsStructuredJson $&quot;Logging Setup Error: %A{error}&quot;<br>                    Error err<br><br>                | Ok logger -&gt;<br>                    setupAppConfig lambdaContext cfg logger<br>        with ex -&gt;<br>            writeToStdErrAsStructuredJson $&quot;Unexpected Configuration Exception: {ex.ToString()}&quot;<br>            reraise ()</pre><p>Oh, “what’s that <strong><em>writeToStdErrAsStructuredJson</em></strong>&quot; you say?</p><p>Ah. So at this stage we haven’t loaded any config yet or configured our logger, but if something failed we still want to handle that as best we can.</p><p>At TotallyMoney we always use <a href="https://stackify.com/what-is-structured-logging-and-why-developers-need-it/">structured logging</a> to get the best from our logs, so even when we don’t have a logger, we’ll do the best we can to create something that can be easily parsed in CloudWatch, DataDog, or observability system de jour. It might be a bit obsessive, but that’s one of the reasons we chose F# in the first place - because we care about handling the edge cases.</p><pre>open System<br>open System.Text.Json<br>open System.Text.Json.Serialization<br><br>type RawLoggingError =<br>    { Level: string<br>      Environment : string<br>      ErrorMessage : string }<br><br>let inline trySerialize obj =<br>    try<br>        JsonSerializer.Serialize(obj) |&gt; Ok<br>    with ex -&gt;<br>        Error (SerializationError ex)<br><br>let writeToStdErrAsStructuredJson errorMessage =<br>    let environment =<br>        match Environment.tryItem &quot;ENVIRONMENT&quot; with<br>        | Ok env -&gt; env<br>        | Error _ -&gt; &quot;Unknown&quot;<br><br>    { Level = &quot;Error&quot;<br>      Environment = environment<br>      ErrorMessage = errorMessage }<br>    |&gt; trySerialize<br>    |&gt; function<br>        | Ok msgJson -&gt; eprintfn $&quot;{msgJson}&quot;<br>        | Error err -&gt; eprintfn $&quot;%A{err}&quot;</pre><p>And with that we have a full set of services ready to go and our lambdas could look something like this:</p><pre><br>[&lt;LambdaSerializer(typeof&lt;DefaultLambdaJsonSerializer&gt;)&gt;]<br>let mySeriousLambda requestData (lambdaContext : ILambdaContext) = <br>    match Config.setupAndCreateAppContext lambdaContext with<br>    | Error -&gt; mySomethingHasGoneWrongErrorResponse<br>    | Ok ctx -&gt;<br>        mySeriousWorkflow ctx requestData<br>        |&gt; tee (ctx.Logger.Flush())</pre><p>Depending on how you have done your setup, at the point when <strong><em>setupAndCreateAppContext</em></strong> runs it quite likely hasn’t done very much of anything at all. For our example with the <strong><em>DataAccess.configure</em></strong> function all we’ve done is partially applied some functions. We haven’t created any dynamo db clients or opened any connections.</p><p>The benefit of just doing this partial application is two fold:</p><ul><li>The setup is super fast, and</li><li>We don’t do any work that a lambda won’t actually use.</li></ul><p>In effect we’re applying the <a href="https://justgokus.medium.com/what-is-the-lazy-initialization-design-pattern-99fa0024ce5b#:~:text=The%20lazy%20initialization%20design%20pattern%20is%20a%20design%20pattern%20in,save%20resources%20and%20improve%20performance.">lazy initialization pattern</a>.</p><p>For more standard web servers like Giraffe this is possibly the opposite of what you want to do. In that case you want to get everything setup before the first requests start hitting so you know everything is working, then you can respond as quickly as possible.</p><p>But for Lambda’s none of that applies. The request is already here, when we do the setup doesn’t mater, and we don’t want to waste time checking everything is working. In fact if you’re using microservices you should assume that everything is not working! It’s a core tenant of service design that you‘ll need to handle issues gracefully.</p><h4>Wrapping it up</h4><p>There are many things I haven’t dealt with yet to make a working functional shell. DTOs are a big one; serialization of said DTOs of course; then there is error handling. Plus we’ll want a few helper functions to manage all that.</p><p>But hopefully this article gives you a view into what a production level F# system runing on AWS Lambda has to deal with, and one very simple way of setting that up.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3c981f767242" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Growing code: It’s all about cohesion]]></title>
            <link>https://medium.com/creating-totallymoney/growing-code-its-all-about-cohesion-ddc3c45406ce?source=rss-946d9a2a4ce0------2</link>
            <guid isPermaLink="false">https://medium.com/p/ddc3c45406ce</guid>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Tristian Barrett]]></dc:creator>
            <pubDate>Fri, 23 Jun 2023 09:32:51 GMT</pubDate>
            <atom:updated>2023-06-23T09:32:51.689Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Abstract art with circles and shading and connecting lines" src="https://cdn-images-1.medium.com/max/406/1*fNUhOOjvgTmBvMbbpEdIjQ.png" /></figure><p>At first there was GOTO, and everything was good.</p><p>But then codebases became larger. The code became a jumble. There was a need for more cohesion.</p><p>So smart people sat around and invented the idea of functions! (or <a href="http://www.laputan.org/pub/papers/wheeler.pdf">sub-routines</a> as they were called back then)</p><p>And everything was good once again. People could reason about how programs worked. Functions kept things cohesive and reduced coupling.</p><p>But people kept using GOTO, and so everything was not good.</p><p>And so smart people said: “<a href="https://homepages.cwi.nl/~storm/teaching/reader/Dijkstra68.pdf">Go To statement considered harmful</a>” and they invented <a href="https://en.wikipedia.org/wiki/Structured_programming">structured programming</a>, and we had <a href="https://en.wikipedia.org/wiki/Structured_program_theorem">systems</a> for using <em>while</em> loops, and <em>if</em> statements and lots of other fun tools.</p><p>And everything was good once again. People could reason about how programs worked. Structured Programming kept things cohesive and reduced coupling.</p><p>…</p><p>But programs continued to get larger and larger and even functions reached their limits. Programs were doing so much it became hard to collaborate with other people and reason about what each part was doing.</p><p>And so smart people found a solution. <a href="https://en.wikipedia.org/wiki/Modular_programming">Modules</a>. If we wanted to operate with files, we’d find our function in the File module. If we wanted to create a graphics function, we’d add it to the Graphics module.</p><p>And everything was good once again. Related things were together, and unrelated things were separated. There was higher cohesion and lower coupling.</p><p>But programs continued to get larger and larger, and modules could only help so much with the data that was being passed around willy-nilly from one part of the program to another. It became hard to reason about what parts of a program were responsible for what data.</p><p>And once again smart people found a solution. They saw what other smart people had created for developing simulations and figured that it would be a great fit for the problems they were facing, and Object-Oriented programming entered the mainstream. Data structures and the functions that operated on them were kept together in objects.</p><p>And everything was good once again. We could now reason about what code was responsible for what data and vice-versa. There was higher cohesion and lower coupling.</p><p>But programs continued to get larger and larger and object oriented programs had their own problems, such as Ravioli Code. It became hard to reason about how all the objects were interconnected to each other, and what was changing what.</p><p>So once again smart people got together and came up with N-Tiered architecture. The presentation layer got separated from the business layer, which in turn got separated from the data layer.</p><p>And everything was good once again. We could now reason about what caused the UI to change, and what caused the data in the DB to change. There was higher cohesion and lower coupling. And we now had specialization — Front-End and Back-End developers (though it would take a few years for those terms to appear).</p><p>But programs continued to get larger and larger and separating OO programs into tiers only did so much to fix things. Within each tier It became hard to reason about how all the objects were interconnected to each other.</p><p>And once again a smart person (Eric Evans) came up with a solution. Domain Driven Design. Aggregate roots bundled several objects together, and Bounded contexts bundled aggregate roots together. Then other patterns such as repositories and services helped by knowing where to put things.</p><p>And everything was good once again. We could now reason about what parts of the system were responsible for what parts of the business. There was higher cohesion and lower coupling.</p><p>But while DDD was doing wonders for the domain and data layers, it did nothing to help with the presentation layer, which was becoming larger and more complex and undergoing constant change.</p><p>And once again smart people came up with React and Redux and similar technologies. User actions became separate from state changes which were separated from rendering.</p><p>And everything was good once again. We could now reason about state, actions, and rendering independently. There was higher cohesion and lower coupling.</p><p><em>Note: all the above didn’t happen in a strict chronological order. A lot of these advancements were being made at the same time, and being shared unevenly amongst the community. There’s also a lot more things I could have added, but I think you get the drift.</em></p><p>I don’t know what innovations will happen next in the world of software development, but I’m sure one of them will involve improving cohesion &amp; reducing coupling. Complexity is a beast, and it’s not going to go away. It’s going to continue to grow and create new and wonderful problems.</p><p>Our systems keep getting bigger and more complex, but our brains aren’t getting smarter.</p><p>Our organisations keep getting larger, but our communication isn’t happening much more effectively.</p><p>Yes, we try to remove complexity and make things simpler, but there’s an essential complexity to the problems we solve that can’t simply be swept under the carpet. When it comes to dealing with that essential complexity, finding ways to improve the cohesion of our code is the solution that’s stood the test of time.</p><p>I’ll finish with a link to one video that I feel does a wonderful job of demonstrating how to take highly coupled code and go through a process of getting to highly cohesive code: <a href="https://www.youtube.com/watch?v=8bZh5LMaSmE">Sandi Metz’s, “All the Little Things”</a> presentation. It’s well worth a watch if you’re interested in refactoring, OO code, or just making code better in general.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ddc3c45406ce" width="1" height="1" alt=""><hr><p><a href="https://medium.com/creating-totallymoney/growing-code-its-all-about-cohesion-ddc3c45406ce">Growing code: It’s all about cohesion</a> was originally published in <a href="https://medium.com/creating-totallymoney">Creating TotallyMoney</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>