ploeh blog https://blog.ploeh.dk danish software design en-us Mark Seemann Thu, 03 Dec 2026 07:21:32 UTC Thu, 03 Dec 2026 07:21:32 UTC A sandwich with extra data https://blog.ploeh.dk/2026/11/30/a-sandwich-with-extra-data/ Mon, 30 Nov 2026 06:50:00 UTC <div id="post"> <p> <em>Weighing unnecessary network calls against simplicity and expected cost.</em> </p> <p> Ever since I first started talking about <a href="/2020/03/02/impureim-sandwich">Impueriem Sandwiches</a>, and later <a href="/2025/01/13/recawr-sandwich">Recawr Sandwiches</a>, the most common question has been: <em>What if I need to fetch some data, make a decision based on that data, and so on?</em> </p> <p> I've already responded to such questions a few times: </p> <ul> <li><a href="/2022/02/14/a-conditional-sandwich-example">A conditional sandwich example</a></li> <li><a href="/2025/04/28/song-recommendations-as-an-impureim-sandwich">Song recommendations as an Impureim Sandwich</a></li> </ul> <p> As I have also stated, the problem with selling this design pattern is exactly that it's not a general-purpose architecture. No design pattern is. I am, therefore, always happy when I receive particular questions about it, because I believe that the more examples I give, the easier it is to see the value. </p> <h3 id="9b739ce5469140c48d7e6e9ef0b88c11"> A letter from a reader <a href="#9b739ce5469140c48d7e6e9ef0b88c11">#</a> </h3> <p> <a href="https://github.com/samfrances">Sam Frances</a> recently wrote to me: </p> <blockquote> <p> "Lets say you have a pure function like the following: </p> <p> <pre><span style="color:blue;">def</span>&nbsp;<span style="color:#2b91af;">choose_command</span>(config,&nbsp;permissions): &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">if</span>&nbsp;<span style="color:#a31515;">&quot;my_feature_flag&quot;</span>&nbsp;in&nbsp;config&nbsp;and&nbsp;<span style="color:#a31515;">&quot;my_perm&quot;</span>&nbsp;in&nbsp;permissions: &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;FooCommand() &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;BarCommand()</pre> </p> <p> "This is nice and pure, easily testable etc. My real example is more complex, of course, but I'm not free to share that. </p> <p> "I'm envisaging a impureim sandwich: </p> <p> <pre><span style="color:green;">#&nbsp;config&nbsp;already&nbsp;in&nbsp;scope</span> permissions&nbsp;=&nbsp;fetch_permissions()&nbsp;&nbsp;<span style="color:green;">#&nbsp;impure</span> command&nbsp;=&nbsp;choose_command(config,&nbsp;permissions)&nbsp;&nbsp;<span style="color:green;">#&nbsp;pure</span> command.execute()&nbsp;&nbsp;<span style="color:green;">#&nbsp;impure</span></pre> </p> <p> "However, you can probably already see an inefficiency there. Say permissions requires a network call, which you don't want to make unless needed. I.e. if the feature flag isnt there, you didn't need to fetch permissions. But if you fetch permissions from within choose_command(), you lose functionality purity, have to mock to test it, etc. </p> <p> <pre><span style="color:blue;">def</span>&nbsp;<span style="color:#2b91af;">choose_command</span>(config): &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">if</span>&nbsp;<span style="color:#a31515;">&quot;my_feature_flag&quot;</span>&nbsp;in&nbsp;config&nbsp;and&nbsp;<span style="color:#a31515;">&quot;my_perm&quot;</span>&nbsp;in&nbsp;fetch_permissions(): &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;FooCommand() &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;BarCommand()</pre> </p> <p> "Is there a functional way to address cases like this? Or do we just swallow a slight inefficiency in return for functional purity?" </p> </blockquote> <p> The short answer is that the easiest solution is indeed to swallow a slight inefficiency, but I still find it important to elaborate. </p> <h3 id="5f06b5ec3ef24c24b7e0d38036f4fd06"> Optimize for the common path <a href="#5f06b5ec3ef24c24b7e0d38036f4fd06">#</a> </h3> <p> Software architecture is often a question of trade-offs. Lose something to gain something. I'm often ready to sacrifice small inefficiencies if I can thereby keep things simpler. A good rule of thumb is to optimize for the common scenario. I have previously <a href="/2022/12/12/when-do-tests-fail">discussed this in relation to test failures</a>. I think a similar mindset is often useful when it comes to discussions about Recawr Sandwiches. </p> <p> People are often, like Sam Frances, concerned about making a network call if there's a risk that the data goes unused. This may be a rational concern, and is certainly worth considering. When, however, analyzing a situation like this one, you should also ask additional questions: How expensive is the network call? How likely is it that the call is wasted? Can the result be cached? What consequences are associated with a wasted network call? </p> <p> Such questions may have varied answers. Consider the consequences. In the above example, calling <code>fetch_permissions</code> imply a network roundtrip to retrieve a set of permissions. What are the consequences of calling <code>fetch_permissions</code> if we don't need the permissions because the feature flag is off? </p> <p> Is the problem that it takes a long time, and we are concerned that if we make the user wait too long, he or she will abandon our system in favour of a competitor? Or are we worried that we waste server resources? </p> <p> The solution we arrive at relate to answers to such questions. If we assume, as I hope is most realistic, that the <code>fetch_permissions</code> call itself is fairly inexpensive, the concern may be mostly related to wasted server resources. If so, however, analyze how much that waste amounts to. Particularly when it comes to feature flags, there ought to be two outcomes: </p> <ul> <li> Either the feature becomes permanent, in which case we can eventually remove the feature-flag check altogether. This then implies that the <a href="/2011/07/28/CompositionRoot">Composition Root</a> needs to call <code>fetch_permissions</code> unconditionally. In this outcome, there are no wasted network calls. </li> <li> The other alternative is that after a period of testing, the feature is turned off again. In that case, the associated code should be deleted. If the call to <code>fetch_permissions</code> was contingent on the flag, that call can be deleted too. </li> </ul> <p> In both cases, the potential inefficiency is temporary. </p> <p> This analysis may, however, be disingeneous. After all, Sam Frances' example code is a stand-in for something more complicated. Perhaps it's not even related to feature flags. In a more general case, the inefficiency may be permanent: If you choose to always make a network call, even in the cases where you don't need to, you waste some compute and network resources. The question remains: Can you live with such 'waste'? As I discussed in <a href="/2025/04/28/song-recommendations-as-an-impureim-sandwich">Song recommendations as an Impureim Sandwich</a>, it may be more efficient to add an extra server, or an extra network card, than to make the architecture more efficient but more complicated. </p> <p> <img src="/content/binary/optimizing-command-choice-for-common-scenario.png" alt="A fat arrow pointing to foo, with two much smaller arrows branching off pointing to bar."> </p> <p> In many cases, if the common scenario (e.g. when the feature flag is raised <em>and</em> the permission is granted) dominates the alternatives (when you may perform the network operation in vain), then it makes sense to accept the slight inefficiency. </p> <h3 id="6d48019814d34359b19f423a898fde9b"> Caching <a href="#6d48019814d34359b19f423a898fde9b">#</a> </h3> <p> Another way to deal with an apparent inefficiency related to making a network call is to decrease its cost. Can you cache the data? If so, it may not matter that you call <code>fetch_permissions</code> in vain, because it's essentially only a memory lookup. </p> <p> It's often surprising what you can cache, particularly if you adopt an eventual-consistency mindset. Even so, you may think: <em>Surely, when it comes to security, caching is unsafe</em>. </p> <p> You'll be surprised. Most IT security infrastructure relies on caching. <a href="https://en.wikipedia.org/wiki/X.509">X.509</a> certificates come with an expiry date, until which they are considered valid. In order to deal with certificates that shouldn't have been issued, there's typically also a certificate revocation list that you're supposed to consult, but many don't do that, or at the very least cache the list. There's a reason why various institutions are working on making domain certificates more ephemeral. Even so, a certificate is effectively a cache document, complete with an expiry policy. </p> <p> If you use <a href="https://en.wikipedia.org/wiki/OAuth">OAuth</a>, <em>claims</em> about the security actor are embedded in security tokens. Systems use those claims to make security decisions. How long does an OAuth token live? Usually the lifetime is measured in minutes, and may be as much as an hour. </p> <p> Back when I worked with <a href="https://en.wikipedia.org/wiki/WS-Federation">WS-Federation</a> and <a href="https://en.wikipedia.org/wiki/SAML">SAML</a> it was the same story. </p> <p> And back when I worked as an IT pro and sysadmin with an international Windows network, I learned that <a href="https://en.wikipedia.org/wiki/Kerberos_(protocol)">Kerberos</a> worked essentially the same: All your group memberships would be attached to a security token issued to your session when you logged into Windows. This was nothing but an array of GUIDs, and it would last until you logged out. If a sysadmin made changes to your group memberships, they wouldn't take effect until you logged out and in again. This included membership revocation. </p> <p> This all sounds dangerous. After all, if you discover that a user is misusing privileges, you can't immediately revoke them. As I understand it, this is a calculated risk in the design, and reflects what I meant by an eventual-consistency mindset. Instead of 'right now', you may have discovered the user's abuse an hour later. In the end, exactly <em>when</em> events happen is random. </p> <p> This all does sugest, however, that you can aggresively cache credentials. Sam Frances doesn't quite write what <code>fetch_permissions</code> does, but I can only imagine two scenarios. </p> <ul> <li> If <code>fetch_permissions</code> retrieves group memmberships or claims related to role-based security, you may already have those as part of a Kerberos, SAML, or OAuth token. In this case, no network hop is involved. </li> <li> Alternatively, <code>fetch_permissions</code> may query for permissions on a particular resource; that is, some Access Control List (ACL) is involved. Again, you may consider how often such ACLs change. If they only change infrequently, then caching may be appropriate. </li> </ul> <p> In the latter case, for a sufficiently small system, all ACLs might actually fit in RAM, in which case you might consider just loading all of them and refreshing the cache periodically. </p> <p> As usual, when caching is involved, you need to consider how to deal with systems running on more than one server. </p> <p> I always consider caching an advanced optional architecture that I'd do much to avoid. The good thing about it, though, is that it's a <a href="https://en.wikipedia.org/wiki/Cross-cutting_concern">cross-cutting concern</a>, so you should be able to add it to an existing system architecture with only moderate effort. </p> <h3 id="7bcb2661370945d4ab353d6cc1d440b1"> Combinators <a href="#7bcb2661370945d4ab353d6cc1d440b1">#</a> </h3> <p> Another option is to surface the decision to make the network call in such a way that you can make the call conditional in the Composition Root. Although 'we' frown upon introducing branching or looping constructs into the Composition Root, we can sometimes hide them behind a 'combinator'. My article <a href="/2019/12/02/refactoring-registration-flow-to-functional-architecture">Refactoring registration flow to functional architecture</a> has many examples of those. In the present <code>choose_command</code> example, the combinator is less compelling, but I'll cover it for completeness. </p> <p> Image refactoring <code>choose_command</code> so that the first conditional is promoted to a separate function: </p> <p> <pre><span style="color:blue;">def</span>&nbsp;<span style="color:#2b91af;">has_feature</span>(config): &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;<span style="color:#a31515;">&quot;my_feature_flag&quot;</span>&nbsp;in&nbsp;config <span style="color:blue;">def</span>&nbsp;<span style="color:#2b91af;">choose_command</span>(config,&nbsp;permissions): &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">if</span>&nbsp;has_feature(config)&nbsp;and&nbsp;<span style="color:#a31515;">&quot;my_perm&quot;</span>&nbsp;in&nbsp;permissions: &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;FooCommand() &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;BarCommand()</pre> </p> <p> This means that the Composition Root can now make the call conditional on that function: </p> <p> <pre><span style="color:green;">#&nbsp;config&nbsp;already&nbsp;in&nbsp;scope</span> permissions&nbsp;=&nbsp;<span style="color:blue;">await</span>&nbsp;fetch_permissions()&nbsp;<span style="color:blue;">if</span>&nbsp;has_feature(config)&nbsp;<span style="color:blue;">else</span>&nbsp;<span style="color:#2b91af;">set</span>()&nbsp;&nbsp;<span style="color:green;">#&nbsp;impure</span> command&nbsp;=&nbsp;choose_command(config,&nbsp;permissions)&nbsp;&nbsp;<span style="color:green;">#&nbsp;pure</span> command.execute()&nbsp;&nbsp;<span style="color:green;">#&nbsp;impure</span></pre> </p> <p> Of course this introduces branching into the Composition Root. Is this permitted? </p> <p> In software architecture, there are no hard rules, so whether this should be considered legal is always up for debate. That said, if you wish to use <a href="/2020/04/13/curb-code-rot-with-thresholds">thresholds as heuristics</a>, some limit values work better than others. Just like <a href="/2023/01/23/agilean">the correct number of compiler warnings is zero</a>, the most appropriate boundary value for <a href="/2019/12/09/put-cyclomatic-complexity-to-good-use">cyclomatic complexity</a> in the Composition Root is <em>1</em> (the lowest possible number). This may seem unnecessarily strict and ideal, but is really based on pragmatism: If you allow any other cutoff, then why not one more? If you allow cyclomatic complexity of 2, then why not 3? If 3, why not 4? At least 1, being the minimum, comes with a mathematical property in its defence. </p> <p> If we adopt this attitude, then the above Composition Root with an <code>if</code>/<code>else</code> expression is illegal. Can we fix it somehow? </p> <p> This is where my knowledge of <a href="https://www.python.org/">Python</a> is too shallow, so I ported the example to <a href="https://www.haskell.org/">Haskell</a>, which I still use as the gold standard for <a href="/2018/11/19/functional-architecture-a-definition">functional architecture</a>. </p> <p> <pre>permissions&nbsp;&lt;-&nbsp;<span style="color:blue;">if</span>&nbsp;hasFeature&nbsp;config&nbsp;<span style="color:blue;">then</span>&nbsp;fetchPermissions&nbsp;<span style="color:blue;">else</span>&nbsp;pure&nbsp;Set.empty&nbsp;<span style="color:green;">--&nbsp;impure</span> <span style="color:blue;">let</span>&nbsp;command&nbsp;=&nbsp;chooseCommand&nbsp;config&nbsp;permissions&nbsp;<span style="color:green;">--&nbsp;pure</span> execute&nbsp;command&nbsp;<span style="color:green;">--&nbsp;impure</span></pre> </p> <p> This, at first glance, is no improvement. Like the Python example, this Composition Root has a cyclomatic complexity of 2. Is there some combinator that enables us to hide the complexity? Yes, we can use the <a href="https://hackage-content.haskell.org/package/base/docs/Data-Bool.html#v:bool">bool</a> case analysis: </p> <p> <pre>permissions&nbsp;&lt;-&nbsp;bool&nbsp;(pure&nbsp;Set.empty)&nbsp;fetchPermissions&nbsp;(hasFeature&nbsp;config)&nbsp;<span style="color:green;">--&nbsp;impure</span> <span style="color:blue;">let</span>&nbsp;command&nbsp;=&nbsp;chooseCommand&nbsp;config&nbsp;permissions&nbsp;<span style="color:green;">--&nbsp;pure</span> execute&nbsp;command&nbsp;<span style="color:green;">--&nbsp;impure</span></pre> </p> <p> You may think of <code>bool</code> as nothing but a glorified <a href="https://en.wikipedia.org/wiki/Ternary_conditional_operator">ternary conditional operator</a>, and that this is really cheating. I am sympathetic to such an objection. It does, however, formally reduce the cyclomatic complexity to 1, per the above discussion. </p> <p> I'm not aware that Python (or my other go-to languages <a href="https://fsharp.org/">F#</a> and C#, for that matter) comes with an equivalent <code>bool</code> function in its base library. Even so, you could always add it yourself (and cover it with unit tests). If you don't like the name <code>bool</code>, you may find inspiration in the knowledge that this function is the <a href="/2019/05/06/boolean-catamorphism">Boolean catamorphism</a>. Perhaps names like <code>cata_bool</code> or <code>fold_bool</code> work better for you? </p> <p> <pre><span style="color:green;">#&nbsp;config&nbsp;already&nbsp;in&nbsp;scope</span> permissions&nbsp;=&nbsp;<span style="color:blue;">await</span>&nbsp;fold_bool(has_feature(config),&nbsp;fetch_permissions,&nbsp;<span style="color:#2b91af;">set</span>())&nbsp;&nbsp;<span style="color:green;">#&nbsp;impure</span> command&nbsp;=&nbsp;choose_command(config,&nbsp;permissions)&nbsp;&nbsp;<span style="color:green;">#&nbsp;pure</span> command.execute()&nbsp;&nbsp;<span style="color:green;">#&nbsp;impure</span></pre> </p> <p> This is possible in Python, too, but less elegant. This is not a recommendation; only an exploration of options. </p> <h3 id="95137d41bd984dcd8f3182ca3a812cf5"> Relationship with algorithm analysis <a href="#95137d41bd984dcd8f3182ca3a812cf5">#</a> </h3> <p> The concern behind many questions related to the Sandwich patterns is one of efficiency. It seems wrong to make a network call (or other expensive calculation) if you don't need it. This is a reasonable concern, but first, the usual caveats apply: If you are concerned about perfomance, measure. Only address the inefficiency if you can measure a problem. I'm sure I don't need to quote <a href="https://en.wikipedia.org/wiki/Donald_Knuth" title="premature optimization is the root of all evil">Knuth</a> here. </p> <p> Assume that you have already measured the size of the problem, and it turns out that it is, in fact, one that should be addressed. My point about optimizing for the common path relates to algorithmic analysis of <em>expected</em> versus <em>worst-case</em> running time. If you can live with a few outliers, then opting for a good expected running time is the better solution. Only solve the problem if the expected running time is bad, or you can't live with the outliers (that is, the worst-case running time). </p> <p> Bringing caching into the mix is reminiscent of <a href="https://en.wikipedia.org/wiki/Amortized_analysis">ammortized analysis</a>. Every cache miss has a high cost, which is then ammortized over several cache hits. The more cache hits, the better the ammortization. </p> <h3 id="6d3ebd39c93c45f99008ee64770acbb6"> Conclusion <a href="#6d3ebd39c93c45f99008ee64770acbb6">#</a> </h3> <p> A design pattern is never universal. It's </p> <blockquote> <p> "a solution to a problem in a context." </p> <footer><cite><a href="/ref/dp">Design Patterns</a></cite>, Erich Gamma et al, Addison-Wesley, 1994, p. 3</footer> </blockquote> <p> Even so, a common question that arises from the Sandwich patterns is how to deal with conditional data fetches. The answer often lies in challenging the underlying assumption. Such questions usually imply that it's important that you only make a secondary query once you have the result of the first query. </p> <p> Suprisingly often it proves fruitful to examine that assumption. Once you start taking into consideration the actual cost of making the second query, it may turn out that it's not worth the trouble trying to avoid it. Particularly if algorithmic analysis shows that the expected or ammortized cost is low. </p> <p> This article is an example of such analysis. It demonstrates that simplification may be found if you combine analytical and pragmatic thinking. </p> <p> As I have previously asserted, </p> <blockquote> <p> "a surprisingly large proportion of problems can be rephrased and organised in such a way that the impureim sandwich architecture applies. Actually, I surmise that most problems can be addressed in that way." </p> <footer><cite><a href="/2022/02/14/a-conditional-sandwich-example">A conditional sandwich example</a></cite>, me, 2022</footer> </blockquote> <p> The problem is that so far, I see no way to <em>prove</em> that conjecture. Instead, I attempt to argue it case-by-case, because my own experience is that the pattern is much more applicable than people realize. This article, then, is one such argument. </p> <p> I welcome further examples, should you have some. </p> </div><hr> This blog is totally free, but if you like it, please consider <a href="https://blog.ploeh.dk/support">supporting it</a>. Mark Seemann https://blog.ploeh.dk/2026/11/30/a-sandwich-with-extra-data QuickCheck property: Monotonicity in items https://blog.ploeh.dk/2026/11/23/quickcheck-property-monotonicity-in-items/ Mon, 23 Nov 2026 07:53:00 UTC <div id="post"> <p> <em>A testing dead end that felt appropriate at the time.</em> </p> <p> This article is one of a series on <a href="/2026/10/19/properties-for-a-budgeting-exercise">finding properties for a budgeting kata</a>. I expect you to have read the previous articles in the series. </p> <p> As I often do <a href="/2020/01/13/on-doing-katas">when I do katas</a>, I imposed some constraints in addition to 'just' solving the problem. I wanted to do test-driven development (TDD) with <a href="https://hackage.haskell.org/package/QuickCheck">QuickCheck</a> properties taking the place of individual test cases. I also desired to identify 'mathematical' or computer-science-like properties instead of (which is much easier) 'examples on steroids'. All this made me add the next property although, should I had followed the <a href="https://blog.cleancoder.com/uncle-bob/2013/05/27/TheTransformationPriorityPremise.html">transformation priority premise</a>, I should have chosen a property that would have prompted a change to the System Under Test. </p> <p> This didn't happen here, but still I felt that it was worthwhile establishing this property as groundwork for the property I intended to add after this one. </p> <p> The code is <a href="https://github.com/ploeh/BudgetingHaskell">available on GitHub</a>, in the commit <code>1051c2d</code>. </p> <h3 id="68f1d0d02e5f4a609522b25bfa389f36"> An Arbitrary instance for Budget <a href="#68f1d0d02e5f4a609522b25bfa389f36">#</a> </h3> <p> So far, the properties I defined all constructed budgets from QuickCheck-generated bills. For this property, I wanted to be able to work with arbitrary budgets. As I also did with <code>Item</code>, I first <a href="/2019/09/02/naming-newtypes-for-quickcheck-arbitraries">added a newtype wrapper</a> for <code>Budget</code>: </p> <p> <pre><span style="color:blue;">newtype</span>&nbsp;AnyBudget&nbsp;a&nbsp;=&nbsp;AnyBudget&nbsp;{&nbsp;getBudget&nbsp;::&nbsp;Budget&nbsp;a&nbsp;}&nbsp;<span style="color:blue;">deriving</span>&nbsp;(<span style="color:#2b91af;">Show</span>,&nbsp;<span style="color:#2b91af;">Eq</span>)</pre> </p> <p> You can now give <code>AnyBudget</code> an <code>Arbitrary</code> instance. </p> <p> <pre><span style="color:blue;">instance</span>&nbsp;(<span style="color:blue;">Arbitrary</span>&nbsp;a,&nbsp;<span style="color:blue;">Ord</span>&nbsp;a)&nbsp;<span style="color:blue;">=&gt;</span>&nbsp;<span style="color:blue;">Arbitrary</span>&nbsp;(<span style="color:blue;">AnyBudget</span>&nbsp;a)&nbsp;<span style="color:blue;">where</span> &nbsp;&nbsp;arbitrary&nbsp;=&nbsp;<span style="color:blue;">do</span> &nbsp;&nbsp;&nbsp;&nbsp;Positive&nbsp;tl&nbsp;&lt;-&nbsp;arbitrary &nbsp;&nbsp;&nbsp;&nbsp;cls&nbsp;&lt;-&nbsp;<span style="color:blue;">fmap</span>&nbsp;getPositive&nbsp;.&nbsp;Map.fromList&nbsp;&lt;$&gt;&nbsp;arbitrary &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;$&nbsp;AnyBudget&nbsp;$&nbsp;Budget&nbsp;tl&nbsp;cls &nbsp;&nbsp;shrink&nbsp;(AnyBudget&nbsp;(Budget&nbsp;tl&nbsp;cls))&nbsp;= &nbsp;&nbsp;&nbsp;&nbsp;[&nbsp;AnyBudget&nbsp;$&nbsp;Budget&nbsp;tl&#39;&nbsp;(<span style="color:blue;">fmap</span>&nbsp;getPositive&nbsp;.&nbsp;Map.fromList&nbsp;$&nbsp;cls&#39;) &nbsp;&nbsp;&nbsp;&nbsp;|&nbsp;(Positive&nbsp;tl&#39;,&nbsp;cls&#39;)&nbsp;&lt;- &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;shrink&nbsp;(Positive&nbsp;tl,&nbsp;Map.toList&nbsp;(<span style="color:blue;">fmap</span>&nbsp;Positive&nbsp;cls)) &nbsp;&nbsp;&nbsp;&nbsp;]</pre> </p> <p> Although <a href="https://www.haskell.org/">Haskell</a> syntax can be dense, there's not a lot going on. Each category limit is generated from some identifier and a <a href="https://hackage-content.haskell.org/package/QuickCheck/docs/Test-QuickCheck.html#t:Positive">Positive</a> <code>Int</code>. The <code>shrink</code> method is similar to <a href="/2026/10/26/quickcheck-property-uncategorised-bill">AnyItem</a>: Wrap both the total limit (<code>tl</code>) and the category limits (<code>cls</code>) in <code>Positive</code>, then shrink that tuple, and unwrap the values again. </p> <h3 id="761a4e9e9a3c4b07a3ad24358fcf00c4"> Monotonicity in items <a href="#761a4e9e9a3c4b07a3ad24358fcf00c4">#</a> </h3> <p> A fundamental property of many functions is whether or not they are <a href="https://en.wikipedia.org/wiki/Monotonic_function">monotonic</a>. If you have a function that returns a complex object, such as a list of customers, the concept of monotonicity may not be meaningful, but when the return value is a simple value, it may. Even though the return type of <code>canAfford</code> is <code>Bool</code>, if we (as I think is intuitive) associate <code>False</code> with nought and <code>True</code> with one, we can meaningfully talk about monotonicity. </p> <p> Consider a fixed sequence of items and a budget. You may begin with an empty bill, which should always be affordable. Then you pick the first item from your given sequence and add it to the bill. Perhaps the bill is still affordable. Then you take the second item and add it to the bill. Perhaps it's <em>still</em> affordable. Depending on the budget and the sequence of items, there will come an item that, when you add it, causes the bill to become unaffordable. After that, no matter how many more items you add, the bill will remain unaffordable. </p> <p> <img src="/content/binary/budget-monotonicity-in-items.png" alt="Graph with items on the horizontal axis and nought and one on the vertical. A step function starts at one, but after twelve items drops to nought and stays there to the right of twelve items." width="600"> </p> <p> It may be that for a given budget and a sequence of items, only the empty bill is affordable, and adding even a single item immediately makes it unaffordable. Even so, for a given budget and sequence of items, the <code>canAfford</code> function is non-increasing in items. Or, as it turned out that I expressed the following property, <em>removing</em> an item can never make an affordable bill unaffordable. Removing an item means 'moving left' on the above graph. Once you're in the part of the graph where the bill is affordable, removing an item (i.e. going left) will never make the bill unaffordable. </p> <p> This suggests a property like this: </p> <p> <pre>testProperty&nbsp;<span style="color:#a31515;">&quot;Monotonocity:&nbsp;Removing&nbsp;item&nbsp;from&nbsp;affordable&nbsp;bill&nbsp;can&nbsp;never&nbsp;make&nbsp;it&nbsp;unaffordable&quot;</span>&nbsp;$&nbsp;\ &nbsp;&nbsp;(AnyBudget&nbsp;(budget&nbsp;::&nbsp;Budget&nbsp;String)) &nbsp;&nbsp;(<span style="color:blue;">fmap</span>&nbsp;getItem&nbsp;.&nbsp;getNonEmpty&nbsp;-&gt;&nbsp;bill&nbsp;::&nbsp;Bill&nbsp;String)&nbsp;-&gt; &nbsp;&nbsp;<span style="color:blue;">do</span> &nbsp;&nbsp;&nbsp;&nbsp;itemToRemove&nbsp;&lt;-&nbsp;elements&nbsp;bill &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">let</span>&nbsp;bill&#39;&nbsp;=&nbsp;<span style="color:blue;">filter</span>&nbsp;(/=&nbsp;itemToRemove)&nbsp;bill &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;actual&nbsp;=&nbsp;canAfford&nbsp;budget&nbsp;bill&#39; &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;$&nbsp;counterexample&nbsp;(<span style="color:#a31515;">&quot;Modified&nbsp;bill:&nbsp;&quot;</span>&nbsp;++&nbsp;<span style="color:blue;">show</span>&nbsp;bill&#39;)&nbsp;$ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">not</span>&nbsp;(canAfford&nbsp;budget&nbsp;bill)&nbsp;||&nbsp;actual</pre> </p> <p> Like previous properties this one also <a href="/2018/05/14/project-arbitraries-with-view-patterns">uses view patterns to pull the <code>bill</code> out of a list of <code>AnyItem</code> values</a>, but now this list is a <a href="https://hackage-content.haskell.org/package/QuickCheck/docs/Test-QuickCheck.html#t:NonEmptyList">NonEmptyList</a>. Likewise, pattern matching on <code>AnyBudget</code> makes <code>budget</code> a <code>Budget String</code>. The entire type for the lambda expression (everything after <code>$&nbsp;\</code> ) is </p> <p> <pre><span style="color:blue;">AnyBudget</span>&nbsp;<span style="color:#2b91af;">String</span>&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;<span style="color:blue;">NonEmptyList</span>&nbsp;(<span style="color:blue;">AnyItem</span>&nbsp;<span style="color:#2b91af;">String</span>)&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;<span style="color:blue;">Gen</span>&nbsp;<span style="color:blue;">Property</span></pre> </p> <p> Since <code>bill</code> is guaranteed to be non-empty, it's safe to pick one of the items to remove. In fact, now that I think about it, the <code>filter</code> expression might actually remove more than one item, but that would only correspond to moving more than one step to the left on the above graph, so that's not consequential. </p> <p> The assertion finally states that if the original <code>bill</code> was unaffordable, we can't really say anything, in which case the property automatically passes. If, on the other hand, that's not the case (i.e. the original <code>bill</code> was affordable), we also expect <code>actual</code> to be <code>True</code>. </p> <h3 id="f2371c2d126644699e0b45776b541b60"> Conclusion <a href="#f2371c2d126644699e0b45776b541b60">#</a> </h3> <p> This property seems redundant, since it immediately passes. The incarnation of <code>canAfford</code> that exists so far already has the desired monotonicity property. I don't quite remember what I had in mind when I added this one, but I think that I thought that this property would become an underlying assumption for a later property, so it felt safer to add this one explicitly. </p> <p> If nothing else, this introduced the concept of monotonicity, which the next property will also explore. </p> <p> <strong>Next:</strong> QuickCheck property: Monotonicity in categories. </p> </div><hr> This blog is totally free, but if you like it, please consider <a href="https://blog.ploeh.dk/support">supporting it</a>. Mark Seemann https://blog.ploeh.dk/2026/11/23/quickcheck-property-monotonicity-in-items Worse is better: async/await versus syntactic sugar for monadic composition https://blog.ploeh.dk/2026/11/16/worse-is-better-asyncawait-versus-syntactic-sugar-for-monadic-composition/ Mon, 16 Nov 2026 07:36:00 UTC <div id="post"> <p> <em>A missed opportunity masquerading as a killer feature.</em> </p> <p> This article is part of a series called <a href="/2026/06/29/worse-is-better">Worse is better</a>, in which I muse on technologies and techniques that became popular despite superior alternatives. Think <a href="https://en.wikipedia.org/wiki/Videotape_format_war">VHS versus Betamax</a>. </p> <p> In this article, I will argue that the celebrated <code>async</code>/<code>await</code> language feature <a href="https://en.wikipedia.org/wiki/Async/await">pioneered by C#</a> should rather be classified as a missed opportunity. <a href="https://fsharp.org/">F#</a> did async first, and better, but of course <a href="https://www.haskell.org/">Haskell</a> does <a href="/2022/03/28/monads">monads</a> even better. </p> <p> Since the introduction in C# the <code>async</code> and <code>await</code> keywords have been ported to multiple other languages, including <a href="https://en.wikipedia.org/wiki/C%2B%2B"><span class="no-break">C++</span></a>, <a href="https://www.python.org/">Python</a>, <a href="https://en.wikipedia.org/wiki/JavaScript">JavaScript</a>, and more. With such apparent success, it seems odd to complain that it's worse than alternatives. </p> <h3 id="a8019e8efded47589781223e8cba5911"> My Richard-Gabriel moment <a href="#a8019e8efded47589781223e8cba5911">#</a> </h3> <p> To be honest, <code>async</code>/<code>await</code> is perfectly cromulent. Pragmatically it solves real problems. What's the complaint? </p> <p> As examples go, this is perhaps the most direct counterpart to <a href="https://dreamsongs.com/WorseIsBetter.html">Gabriel's original lament about C++ and Lisp</a>. Gabriel considered <a href="https://en.wikipedia.org/wiki/Lisp_(programming_language)">Lisp</a> superior to <a href="https://en.wikipedia.org/wiki/C%2B%2B">C++</a> because Lisp was a coherent and elegant system. Still, the heterogeneous hacked-together nature of C++ enabled faster time to market, eventually outcompeting Lisp. </p> <p> Adding <code>async</code> and <code>await</code> keywords to a language is comparable to the C++ approach. Instead of solving a general problem, it only solves a particular problem, albeit a large one. </p> <h3 id="02131ee61f7c487aa2097490b109b8cc"> Computation expressions <a href="#02131ee61f7c487aa2097490b109b8cc">#</a> </h3> <p> What makes this so regrettable is that a general language-design solution already existed. As witnessed by language version history, <a href="https://en.wikipedia.org/wiki/Async/await">F# already had asynchronous workflows with syntactic sugar in 2007</a>. This language feature still exists today: </p> <p> <pre><span style="color:blue;">member</span>&nbsp;_.<span style="font-weight:bold;color:#74531f;">GetRecommendationsAsync</span>&nbsp;<span style="font-weight:bold;color:#1f377f;">userName</span>&nbsp;=&nbsp;<span style="color:blue;">task</span>&nbsp;{&nbsp;<span style="color:green;">//&nbsp;&lt;-&nbsp;async</span> &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:green;">//&nbsp;v&nbsp;await</span> &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">let!</span>&nbsp;<span style="font-weight:bold;color:#1f377f;">scrobbles</span>&nbsp;=&nbsp;<span style="font-weight:bold;color:#1f377f;">songService</span>.<span style="font-weight:bold;color:#74531f;">GetTopScrobblesAsync</span>&nbsp;<span style="font-weight:bold;color:#1f377f;">userName</span> &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:green;">//&nbsp;The&nbsp;rest&nbsp;of&nbsp;the&nbsp;code&nbsp;block&nbsp;follows...</span></pre> </p> <p> This example is from <a href="/2025/04/14/porting-song-recommendations-to-f">Porting song recommendations to F#</a>, although I've clipped the code and changed the comments for didactic reasons. </p> <p> The language feature is called <a href="https://learn.microsoft.com/dotnet/fsharp/language-reference/computation-expressions">computation expressions</a>, and while the base library comes with a few built-in computation expressions, it's a completely user-definable feature. My article <a href="/2025/08/25/song-recommendations-with-f-free-monads">Song recommendations with F# free monads</a> has a comprehensive example, but usually, <a href="/2016/04/11/async-as-surrogate-io">a few lines of code are enough</a>. </p> <p> The original 2007 computation expression was called <a href="https://learn.microsoft.com/dotnet/fsharp/language-reference/async-expressions">async</a>, and it's still around. Since it predated the .NET Task Parallel Library, it was based on its own implementation of <a href="https://fsharp.github.io/fsharp-core-docs/reference/fsharp-control-fsharpasync-1.html">Async&lt;'T&gt;</a>. </p> <p> Later, the F# core library also got <a href="https://learn.microsoft.com/dotnet/fsharp/language-reference/task-expressions">task expressions</a> to support the de-facto standard of using <a href="https://learn.microsoft.com/dotnet/api/system.threading.tasks.task-1">Task&lt;T&gt;</a> for asynchronous processing. No new language feature was required. </p> <p> In the above code example, <code>task</code> introduces the computation expression, roughly corresponding to the C# <code>async</code> keyword. Likewise, the exclamation point <code>!</code> in <code>let!</code> corresponds to <code>await</code>. The beauty of the F# language design is that while it perfectly supports asynchronous programming, it's by no means specialized to that task. </p> <h3 id="a14b288542d94119a1264bc25e1eeef2"> Short-circuiting workflows <a href="#a14b288542d94119a1264bc25e1eeef2">#</a> </h3> <p> Computation expressions can add syntactic sugar for any <a href="/2018/03/22/functors">functor</a>, <a href="/2018/10/01/applicative-functors">applicative functor</a>, or <a href="/2022/03/28/monads">monad</a>, although you get the most bang for your buck with the latter. </p> <p> For example, you can write short-circuiting workflows if you add a little computation expression builder for the <a href="https://learn.microsoft.com/dotnet/fsharp/language-reference/options">option</a> type. For instance, you could rewrite <code>Cpr.tryParse</code> from the article <a href="/2018/12/10/danish-cpr-numbers-in-f">Danish CPR numbers in F#</a> to something like this: </p> <p> <pre><span style="color:green;">//&nbsp;string&nbsp;-&gt;&nbsp;CprNumber&nbsp;option</span> <span style="color:blue;">let</span>&nbsp;<span style="color:#74531f;">tryParse</span>&nbsp;(<span style="font-weight:bold;color:#1f377f;">candidate</span>&nbsp;:&nbsp;<span style="color:#2b91af;">string</span>&nbsp;)&nbsp;= &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">let</span>&nbsp;<span style="font-weight:bold;color:#1f377f;">canonicalized</span>&nbsp;=&nbsp;<span style="font-weight:bold;color:#1f377f;">candidate</span>.<span style="font-weight:bold;color:#74531f;">Trim</span>().<span style="font-weight:bold;color:#74531f;">Replace</span>(<span style="color:#a31515;">&quot;-&quot;</span>,&nbsp;<span style="color:#a31515;">&quot;&quot;</span>) &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">option</span>&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">let!</span>&nbsp;<span style="font-weight:bold;color:#1f377f;">dayString</span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;=&nbsp;<span style="font-weight:bold;color:#1f377f;">canonicalized</span>&nbsp;|&gt;&nbsp;<span style="color:#2b91af;">String</span>.<span style="color:#74531f;">trySubstring</span>&nbsp;0&nbsp;2 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">let!</span>&nbsp;<span style="font-weight:bold;color:#1f377f;">dayCandidate</span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;=&nbsp;<span style="font-weight:bold;color:#1f377f;">dayString</span>&nbsp;|&gt;&nbsp;<span style="color:#2b91af;">Int</span>.<span style="color:#74531f;">tryParse</span> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">let!</span>&nbsp;<span style="font-weight:bold;color:#1f377f;">monthString</span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;=&nbsp;<span style="font-weight:bold;color:#1f377f;">canonicalized</span>&nbsp;|&gt;&nbsp;<span style="color:#2b91af;">String</span>.<span style="color:#74531f;">trySubstring</span>&nbsp;2&nbsp;2 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">let!</span>&nbsp;<span style="font-weight:bold;color:#1f377f;">monthCandidate</span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;=&nbsp;<span style="font-weight:bold;color:#1f377f;">monthString</span>&nbsp;|&gt;&nbsp;<span style="color:#2b91af;">Int</span>.<span style="color:#74531f;">tryParse</span> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">let!</span>&nbsp;<span style="font-weight:bold;color:#1f377f;">yearString</span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;=&nbsp;<span style="font-weight:bold;color:#1f377f;">canonicalized</span>&nbsp;|&gt;&nbsp;<span style="color:#2b91af;">String</span>.<span style="color:#74531f;">trySubstring</span>&nbsp;4&nbsp;2 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">let!</span>&nbsp;<span style="font-weight:bold;color:#1f377f;">yearCandidate</span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;=&nbsp;<span style="font-weight:bold;color:#1f377f;">yearString</span>&nbsp;|&gt;&nbsp;<span style="color:#2b91af;">Int</span>.<span style="color:#74531f;">tryParse</span> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">let!</span>&nbsp;<span style="font-weight:bold;color:#1f377f;">sequenceNumberString</span>&nbsp;&nbsp;&nbsp;&nbsp;=&nbsp;<span style="font-weight:bold;color:#1f377f;">canonicalized</span>&nbsp;|&gt;&nbsp;<span style="color:#2b91af;">String</span>.<span style="color:#74531f;">trySubstring</span>&nbsp;6&nbsp;4 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">let!</span>&nbsp;<span style="font-weight:bold;color:#1f377f;">sequenceNumberCandidate</span>&nbsp;=&nbsp;<span style="font-weight:bold;color:#1f377f;">sequenceNumberString</span>&nbsp;|&gt;&nbsp;<span style="color:#2b91af;">Int</span>.<span style="color:#74531f;">tryParse</span> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return!</span>&nbsp;<span style="color:#74531f;">tryCreate</span> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="font-weight:bold;color:#1f377f;">dayCandidate</span> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="font-weight:bold;color:#1f377f;">monthCandidate</span> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="font-weight:bold;color:#1f377f;">yearCandidate</span> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="font-weight:bold;color:#1f377f;">sequenceNumberCandidate</span> &nbsp;&nbsp;&nbsp;&nbsp;}</pre> </p> <p> This workflow may fail at every step marked by an exclamation point. If it does, it stops processing the rest and simply returns <code>None</code>. </p> <p> This behaviour didn't require a new keyword, or any new language feature, but instead relies on the general-purpose computation-expression language feature and, in this case, a little user-defined expression builder: </p> <p> <pre><span style="color:blue;">type</span>&nbsp;<span style="color:#2b91af;">OptionBuilder</span>&nbsp;()&nbsp;= &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">member</span>&nbsp;_.<span style="font-weight:bold;color:#74531f;">Bind</span>&nbsp;(<span style="font-weight:bold;color:#1f377f;">x</span>,&nbsp;<span style="color:#74531f;">f</span>)&nbsp;= &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">match</span>&nbsp;<span style="font-weight:bold;color:#1f377f;">x</span>&nbsp;<span style="color:blue;">with</span> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;|&nbsp;<span style="color:#2b91af;">Some</span>&nbsp;<span style="font-weight:bold;color:#1f377f;">v</span>&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;<span style="color:#74531f;">f</span>&nbsp;<span style="font-weight:bold;color:#1f377f;">v</span> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;|&nbsp;<span style="color:#2b91af;">None</span>&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;<span style="color:#2b91af;">None</span> &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">member</span>&nbsp;_.<span style="font-weight:bold;color:#74531f;">Return</span>&nbsp;<span style="font-weight:bold;color:#1f377f;">x</span>&nbsp;=&nbsp;<span style="color:#2b91af;">Some</span>&nbsp;<span style="font-weight:bold;color:#1f377f;">x</span> &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">member</span>&nbsp;_.<span style="font-weight:bold;color:#74531f;">ReturnFrom</span>&nbsp;<span style="font-weight:bold;color:#1f377f;">x</span>&nbsp;=&nbsp;<span style="font-weight:bold;color:#1f377f;">x</span> [&lt;<span style="color:#2b91af;">AutoOpen</span>&gt;] <span style="color:blue;">module</span>&nbsp;<span style="color:#2b91af;">OptionBuilder</span>&nbsp;= &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">let</span>&nbsp;option&nbsp;=&nbsp;<span style="color:#2b91af;">OptionBuilder</span>&nbsp;()</pre> </p> <p> While this is already quite elegant, it still requires a bit of (reusable) boilerplate for every functor you wish to support, such as option, <a href="https://learn.microsoft.com/dotnet/fsharp/language-reference/results">result</a>, task, etc. </p> <h3 id="09a4d817d9f549a3a27884a5699286c3"> Programmable semicolons <a href="#09a4d817d9f549a3a27884a5699286c3">#</a> </h3> <p> Haskell, with its more powerful type system, fully automates this process. Every <code>Monad</code> (or <code>Applicative</code> with the <a href="https://ghc.gitlab.haskell.org/ghc/doc/users_guide/exts/applicative_do.html">ApplicativeDo</a> extension) instance enables you to drop into <code>do</code> notation, which gives you nice syntactic sugar for the monad in question. </p> <p> Since <code>Maybe</code> is a <code>Monad</code> instance, you don't have to write any user-code equivalent to the above <code>OptionBuilder</code>. Just drop into <code>do</code> notation, and the compiler automatically handles the workflow for you. As an example, you could port the above <code>tryParse</code> function to Haskell like this: </p> <p> <pre><span style="color:#2b91af;">tryParse</span>&nbsp;<span style="color:blue;">::</span>&nbsp;<span style="color:#2b91af;">String</span>&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;<span style="color:#2b91af;">Maybe</span>&nbsp;<span style="color:blue;">CPRNumber</span> tryParse&nbsp;candidate&nbsp;= &nbsp;&nbsp;<span style="color:blue;">let</span>&nbsp;canonicalized&nbsp;=&nbsp;<span style="color:blue;">filter</span>&nbsp;(/=&nbsp;<span style="color:#a31515;">&#39;-&#39;</span>)&nbsp;$&nbsp;trim&nbsp;candidate &nbsp;&nbsp;<span style="color:blue;">in</span>&nbsp;<span style="color:blue;">do</span> &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">let</span>&nbsp;(dayStr,&nbsp;rest1)&nbsp;=&nbsp;<span style="color:blue;">splitAt</span>&nbsp;2&nbsp;canonicalized &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">let</span>&nbsp;(monthStr,&nbsp;rest2)&nbsp;=&nbsp;<span style="color:blue;">splitAt</span>&nbsp;2&nbsp;rest1 &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">let</span>&nbsp;(yearStr,&nbsp;rest3)&nbsp;=&nbsp;<span style="color:blue;">splitAt</span>&nbsp;2&nbsp;rest2 &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">let</span>&nbsp;sequenceNumberStr&nbsp;=&nbsp;<span style="color:blue;">take</span>&nbsp;4&nbsp;rest3 &nbsp;&nbsp;&nbsp;&nbsp;day&nbsp;&lt;-&nbsp;readMaybe&nbsp;dayStr &nbsp;&nbsp;&nbsp;&nbsp;month&nbsp;&lt;-&nbsp;readMaybe&nbsp;monthStr &nbsp;&nbsp;&nbsp;&nbsp;year&nbsp;&lt;-&nbsp;readMaybe&nbsp;yearStr &nbsp;&nbsp;&nbsp;&nbsp;sequenceNumber&nbsp;&lt;-&nbsp;readMaybe&nbsp;sequenceNumberStr &nbsp;&nbsp;&nbsp;&nbsp;tryCPRNumber&nbsp;day&nbsp;month&nbsp;year&nbsp;sequenceNumber</pre> </p> <p> All the variables bound by <code>&lt;-</code> arrows may cause the computation to short-circuit. This syntax is equivalent to F# <code>let!</code> bindings. Returning a short-circuiting value is also possible in both cases, but while F# requires the <code>return!</code> keyword, in Haskell this is done by omitting <code>return</code>. </p> <p> This Haskell language features is so powerful that <a href="/ref/real-world-haskell">Real World Haskell</a> (among other sources) calls it 'programmable semicolon'. You could use the same phrase for F# computation expressions. </p> <h3 id="2847e17397a54c2e98c0a8b8e25e1ba0"> Where C# falls short <a href="#2847e17397a54c2e98c0a8b8e25e1ba0">#</a> </h3> <p> The <code>async</code>/<code>await</code> feature of C# provides syntactic sugar similar to F# computation expressions and Haskell <code>do</code> notation, but unfortunately, <em>only</em> for asynchronous workflows. As long as your 'outer' monad is <code>Task&lt;T&gt;</code> it works decently, but it doesn't address other cases, like the above examples of short-circuiting computation. </p> <p> Ironically, C# has another language feature that enables syntactic sugar for monadic workflows: <a href="https://learn.microsoft.com/en-us/dotnet/csharp/linq/">Query syntax</a> (AKA LINQ). You can see a small example in the <a href="/2022/04/25/the-maybe-monad">Maybe monad</a> article, as well as plenty of other articles on this site. You could port the above CPR example to C# and achieve short-circuiting behaviour using query syntax. </p> <p> Is it possible to use query syntax with asynchronous workflows too? Yes, indeed, since <a href="/2022/06/06/asynchronous-monads">asynchronous computations are also monadic</a>. Is the <code>async</code>/<code>await</code> language feature redundant, then? </p> <p> No, because query syntax has other limitations. </p> <p> <img src="/content/binary/compexp-linq-async-sets.png" alt="Venn diagram of computation expressions showing overlap between LINQ and async/await. Both support sequential composition; LINQ uniquely emphasizes extensibility, while async/await uniquely includes branching and commands. Parallel composition is shown as part of computation expressions in general, but is not a member of neither LINQ nor async/await." width="400"> </p> <p> As this diagram attempts to capture, while LINQ works for any monad (any <a href="/2018/03/22/functors">functor</a>, in fact), it supports neither branching nor <a href="https://en.wikipedia.org/wiki/Command%E2%80%93query_separation">Commands</a>. That is, you can't use <code>if</code> or <code>switch</code> inside of a LINQ query, and you can't call <code>void</code> methods. You can see an example of the kind of trouble the latter issue causes in my <a href="https://cleancoders.com/episode/humane-code-real-episode-5">Preserved in translation</a> video. Another example of the awkwardness of LINQ can be seen in the article <a href="/2018/07/30/flattening-arrow-code-using-a-stack-of-monads">Flattening arrow code using a stack of monads</a>. </p> <p> On the other hand, as already covered, <code>async</code>/<code>await</code> does support branching and Commands, but is not user-definable; it only works for asynchronous workflows. </p> <p> Finally, while both support sequential composition (<a href="/2022/03/28/monads">monadic bind</a>), none of them support 'parallel' composition, which is what you can get by ignoring monads and instead emphasising <a href="/2018/10/01/applicative-functors">applicative functors</a>. By 'parallel' I mean that you can compose independent computations in a way where what happens to one computation does <em>not</em> short-circuit the rest of the composition. This is particularly useful for validation, as shown in <a href="/2020/12/28/an-f-demo-of-validation-with-partial-data-round-trip">An F# demo of validation with partial data round trip</a>. More specifically, it can be used to implement true parallelism, as demonstrated by the Haskell <a href="https://hackage-content.haskell.org/package/async/docs/Control-Concurrent-Async.html">async</a> package. </p> <h3 id="f72f5e0fc79b49fb96f02416d2620f38"> Language design versus implementation <a href="#f72f5e0fc79b49fb96f02416d2620f38">#</a> </h3> <p> To be clear, my gripe about <code>async</code>/<code>await</code> is about programming-language design. Given the language design choice, the C# (or rather: .NET) implementation of <code>async</code>/<code>await</code> is impressive. Clearly, a lot of work has gone into making it work efficiently. </p> <p> People who know how <code>async</code>/<code>await</code> and the Task Parallel Library works may consider the <a href="https://hackage-content.haskell.org/package/async/docs/Control-Concurrent-Async.html">async</a> package primitive at best, and possibly cheating. As far as I can tell, the Haskell async package creates a new thread every time you enter an <code>Async</code> computation. This can be expensive, and may not be necessary. </p> <p> A C# <code>Task</code>, on the other hand, may or may not run on a separate thread. Often they utilize thread pools and relinquish threads back to a pool while waiting for external I/O events. A lot of thought has gone into the implementation, and my experience is that it works well. The Haskell async package does none of that, as far as I can tell. </p> <p> The F# <code>task</code> computation expression, however, is simply syntactic sugar over the .NET implementation, thereby demonstrating that you can get the best of both worlds. A sophisticated, efficient implementation controlled by elegant and extensible language design. </p> <h3 id="44727cda9816457a9c73f145d66bc962"> Conclusion <a href="#44727cda9816457a9c73f145d66bc962">#</a> </h3> <p> C#'s <code>async</code>/<code>await</code> language feature is so celebrated that other languages have adopted it. Even languages with little or no connection to Microsoft, such as Python and JavaScript, have a similar feature, sometimes even using the same keywords. Surely, this is a sign of success? </p> <p> The <code>async</code>/<code>await</code> language feature is, in my eyes, a perfect example of Gabriel's maxim that <a href="https://en.wikipedia.org/wiki/Worse_is_better">worse is better</a>. It's an essentially ad-hoc addition by way of adding more keywords to an already-complicated programming language. </p> <p> What makes this disappointing is that a more elegant language design was already known at the time. C# could have got its own version of F# computation expressions, which would have enabled both language designers and 'normal' programmers to solve many more problems using the same, universal tool. </p> <p> Of course, since C# already has two competing, partially overlapping kinds of syntactic sugar, I can't rule out that one day, it'll get a third, proper language feature that solves this once and for all. But I don't really believe that. That ship has sailed. </p> <p> Which only underscores the message from the <a href="/2026/09/08/worse-is-better-c-versus-f">previous article</a>: F# is a better programming language than C#. </p> </div> <div id="comments"> <hr> <h2 id="comments-header"> Comments </h2> <div class="comment" id="bf6b8055b6d047c9beb46182db48a840"> <div class="comment-author">Johannes Egger <a href="#bf6b8055b6d047c9beb46182db48a840">#</a></div> <div class="comment-content"> <p> I'm sure you know that since C# 7, it's actually possible to use types other than <code>Task</code> as return types for <code>async</code> methods (see <a href="https://learn.microsoft.com/en-us/dotnet/csharp/asynchronous-programming/async-return-types#generalized-async-return-types-and-valuetasktresult" target="_blank">https://learn.microsoft.com/en-us/dotnet/csharp/asynchronous-programming/async-return-types#generalized-async-return-types-and-valuetasktresult</a>): </p> <pre><span style="color:#2b91af;">Console</span>.<span style="color:#74531f;">WriteLine</span>(<span style="font-weight:bold;color:#74531f;">Run</span>(<span style="color:#2b91af;">Option</span>&lt;<span style="color:blue;">int</span>&gt;.None));&nbsp;<span style="color:green;">//&nbsp;&quot;None&quot;</span> <span style="color:#2b91af;">Console</span>.<span style="color:#74531f;">WriteLine</span>(<span style="font-weight:bold;color:#74531f;">Run</span>(<span style="color:#2b91af;">Option</span>&lt;<span style="color:blue;">int</span>&gt;.<span style="color:#74531f;">Some</span>(3)));&nbsp;<span style="color:green;">//&nbsp;&quot;Some(5)&quot;</span> <span style="color:blue;">static</span>&nbsp;<span style="color:blue;">async</span>&nbsp;<span style="color:#2b91af;">Option</span>&lt;<span style="color:blue;">int</span>&gt;&nbsp;<span style="font-weight:bold;color:#74531f;">Run</span>(<span style="color:#2b91af;">Option</span>&lt;<span style="color:blue;">int</span>&gt;&nbsp;<span style="font-weight:bold;color:#1f377f;">b</span>) { &nbsp;&nbsp;&nbsp;&nbsp;<span style="font-weight:bold;color:#8f08c4;">return</span>&nbsp;<span style="font-weight:bold;color:#8f08c4;">await</span>&nbsp;<span style="color:#2b91af;">Option</span>&lt;<span style="color:blue;">int</span>&gt;.<span style="color:#74531f;">Some</span>(2)&nbsp;+&nbsp;<span style="font-weight:bold;color:#8f08c4;">await</span>&nbsp;<span style="font-weight:bold;color:#1f377f;">b</span>; }</pre> <p> But the majority of libraries out there don't seem to implement their monadic types like this. Maybe you know why? Is there something fundamentally wrong with this approach? </p> <details> <summary style="cursor: pointer">As a reference, click here to unhide the (AI-written) implementation of <code>Option&lt;T&gt;</code>.</summary> <pre><span style="color:blue;">using</span>&nbsp;System.Runtime.CompilerServices; <span style="color:blue;">using</span>&nbsp;System.Runtime.ExceptionServices; [<span style="color:#2b91af;">AsyncMethodBuilder</span>(<span style="color:blue;">typeof</span>(<span style="color:#2b91af;">OptionMethodBuilder</span>&lt;&gt;))] <span style="color:blue;">public</span>&nbsp;<span style="color:blue;">readonly</span>&nbsp;<span style="color:blue;">struct</span>&nbsp;<span style="color:#2b91af;">Option</span>&lt;<span style="color:#2b91af;">T</span>&gt; { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">private</span>&nbsp;<span style="color:blue;">readonly</span>&nbsp;<span style="color:#2b91af;">T</span>&nbsp;<span style="color:#1f377f;">_value</span>; &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:blue;">bool</span>&nbsp;HasValue&nbsp;{&nbsp;<span style="color:blue;">get</span>;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">private</span>&nbsp;<span style="color:#2b91af;">Option</span>(<span style="color:#2b91af;">T</span>&nbsp;<span style="font-weight:bold;color:#1f377f;">value</span>)&nbsp;{&nbsp;<span style="color:#1f377f;">_value</span>&nbsp;=&nbsp;<span style="font-weight:bold;color:#1f377f;">value</span>;&nbsp;HasValue&nbsp;=&nbsp;<span style="color:blue;">true</span>;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:blue;">static</span>&nbsp;<span style="color:#2b91af;">Option</span>&lt;<span style="color:#2b91af;">T</span>&gt;&nbsp;<span style="color:#74531f;">Some</span>(<span style="color:#2b91af;">T</span>&nbsp;<span style="font-weight:bold;color:#1f377f;">value</span>)&nbsp;=&gt;&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">Option</span>&lt;<span style="color:#2b91af;">T</span>&gt;(<span style="font-weight:bold;color:#1f377f;">value</span>); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:blue;">static</span>&nbsp;<span style="color:#2b91af;">Option</span>&lt;<span style="color:#2b91af;">T</span>&gt;&nbsp;None&nbsp;=&gt;&nbsp;<span style="color:blue;">default</span>; &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:#2b91af;">T</span>&nbsp;Value&nbsp;=&gt;&nbsp;HasValue&nbsp;?&nbsp;<span style="color:#1f377f;">_value</span>&nbsp;:&nbsp;<span style="font-weight:bold;color:#8f08c4;">throw</span>&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">InvalidOperationException</span>(<span style="color:#a31515;">&quot;Option&nbsp;is&nbsp;None&quot;</span>); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:green;">//&nbsp;Makes&nbsp;Option&lt;T&gt;&nbsp;awaitable</span> &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:#2b91af;">OptionAwaiter</span>&lt;<span style="color:#2b91af;">T</span>&gt;&nbsp;<span style="font-weight:bold;color:#74531f;">GetAwaiter</span>()&nbsp;=&gt;&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">OptionAwaiter</span>&lt;<span style="color:#2b91af;">T</span>&gt;(<span style="color:blue;">this</span>); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:blue;">override</span>&nbsp;<span style="color:blue;">string</span>&nbsp;<span style="font-weight:bold;color:#74531f;">ToString</span>()&nbsp;=&gt;&nbsp;HasValue&nbsp;?&nbsp;<span style="color:#a31515;">$&quot;Some(</span>{<span style="color:#1f377f;">_value</span>}<span style="color:#a31515;">)&quot;</span>&nbsp;:&nbsp;<span style="color:#a31515;">&quot;None&quot;</span>; } <span style="color:blue;">internal</span>&nbsp;<span style="color:blue;">interface</span>&nbsp;<span style="color:#2b91af;">INoneAwaiter</span>&nbsp;{&nbsp;} <span style="color:blue;">public</span>&nbsp;<span style="color:blue;">readonly</span>&nbsp;<span style="color:blue;">struct</span>&nbsp;<span style="color:#2b91af;">OptionAwaiter</span>&lt;<span style="color:#2b91af;">T</span>&gt;&nbsp;:&nbsp;<span style="color:#2b91af;">ICriticalNotifyCompletion</span>,&nbsp;<span style="color:#2b91af;">INoneAwaiter</span> { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">private</span>&nbsp;<span style="color:blue;">readonly</span>&nbsp;<span style="color:#2b91af;">Option</span>&lt;<span style="color:#2b91af;">T</span>&gt;&nbsp;<span style="color:#1f377f;">_option</span>; &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:#2b91af;">OptionAwaiter</span>(<span style="color:#2b91af;">Option</span>&lt;<span style="color:#2b91af;">T</span>&gt;&nbsp;<span style="font-weight:bold;color:#1f377f;">option</span>)&nbsp;=&gt;&nbsp;<span style="color:#1f377f;">_option</span>&nbsp;=&nbsp;<span style="font-weight:bold;color:#1f377f;">option</span>; &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:green;">//&nbsp;Some&nbsp;-&gt;&nbsp;completes&nbsp;synchronously;&nbsp;None&nbsp;-&gt;&nbsp;compiler&nbsp;asks&nbsp;the&nbsp;builder&nbsp;to&nbsp;&quot;suspend&quot;</span> &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:blue;">bool</span>&nbsp;IsCompleted&nbsp;=&gt;&nbsp;<span style="color:#1f377f;">_option</span>.HasValue; &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:#2b91af;">T</span>&nbsp;<span style="font-weight:bold;color:#74531f;">GetResult</span>()&nbsp;=&gt;&nbsp;<span style="color:#1f377f;">_option</span>.Value; &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:green;">//&nbsp;Never&nbsp;actually&nbsp;called:&nbsp;the&nbsp;builder&nbsp;intercepts&nbsp;None</span> &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:blue;">void</span>&nbsp;<span style="font-weight:bold;color:#74531f;">OnCompleted</span>(<span style="color:#2b91af;">Action</span>&nbsp;<span style="font-weight:bold;color:#1f377f;">continuation</span>)&nbsp;=&gt;&nbsp;<span style="font-weight:bold;color:#8f08c4;">throw</span>&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">NotSupportedException</span>(); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:blue;">void</span>&nbsp;<span style="font-weight:bold;color:#74531f;">UnsafeOnCompleted</span>(<span style="color:#2b91af;">Action</span>&nbsp;<span style="font-weight:bold;color:#1f377f;">continuation</span>)&nbsp;=&gt;&nbsp;<span style="font-weight:bold;color:#8f08c4;">throw</span>&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">NotSupportedException</span>(); } <span style="color:blue;">public</span>&nbsp;<span style="color:blue;">sealed</span>&nbsp;<span style="color:blue;">class</span>&nbsp;<span style="color:#2b91af;">OptionMethodBuilder</span>&lt;<span style="color:#2b91af;">T</span>&gt; { &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">private</span>&nbsp;<span style="color:#2b91af;">Option</span>&lt;<span style="color:#2b91af;">T</span>&gt;&nbsp;<span style="color:#1f377f;">_result</span>; &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">private</span>&nbsp;<span style="color:#2b91af;">ExceptionDispatchInfo</span>?&nbsp;<span style="color:#1f377f;">_error</span>; &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:blue;">static</span>&nbsp;<span style="color:#2b91af;">OptionMethodBuilder</span>&lt;<span style="color:#2b91af;">T</span>&gt;&nbsp;<span style="font-weight:bold;color:#74531f;">Create</span>()&nbsp;=&gt;&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">OptionMethodBuilder</span>&lt;<span style="color:#2b91af;">T</span>&gt;(); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:blue;">void</span>&nbsp;<span style="font-weight:bold;color:#74531f;">Start</span>&lt;<span style="color:#2b91af;">TStateMachine</span>&gt;(<span style="color:blue;">ref</span>&nbsp;<span style="color:#2b91af;">TStateMachine</span>&nbsp;<span style="font-weight:bold;color:#1f377f;">stateMachine</span>) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">where</span>&nbsp;<span style="color:#2b91af;">TStateMachine</span>&nbsp;:&nbsp;<span style="color:#2b91af;">IAsyncStateMachine</span> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;=&gt;&nbsp;<span style="font-weight:bold;color:#1f377f;">stateMachine</span>.<span style="font-weight:bold;color:#74531f;">MoveNext</span>(); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:blue;">void</span>&nbsp;<span style="font-weight:bold;color:#74531f;">SetStateMachine</span>(<span style="color:#2b91af;">IAsyncStateMachine</span>&nbsp;<span style="font-weight:bold;color:#1f377f;">stateMachine</span>)&nbsp;{&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:blue;">void</span>&nbsp;<span style="font-weight:bold;color:#74531f;">SetResult</span>(<span style="color:#2b91af;">T</span>&nbsp;<span style="font-weight:bold;color:#1f377f;">result</span>)&nbsp;=&gt;&nbsp;<span style="color:#1f377f;">_result</span>&nbsp;=&nbsp;<span style="color:#2b91af;">Option</span>&lt;<span style="color:#2b91af;">T</span>&gt;.<span style="color:#74531f;">Some</span>(<span style="font-weight:bold;color:#1f377f;">result</span>); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:blue;">void</span>&nbsp;<span style="font-weight:bold;color:#74531f;">SetException</span>(<span style="color:#2b91af;">Exception</span>&nbsp;<span style="font-weight:bold;color:#1f377f;">exception</span>)&nbsp;=&gt;&nbsp;<span style="color:#1f377f;">_error</span>&nbsp;=&nbsp;<span style="color:#2b91af;">ExceptionDispatchInfo</span>.<span style="color:#74531f;">Capture</span>(<span style="font-weight:bold;color:#1f377f;">exception</span>); &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:#2b91af;">Option</span>&lt;<span style="color:#2b91af;">T</span>&gt;&nbsp;Task &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">get</span>&nbsp;{&nbsp;<span style="color:#1f377f;">_error</span>?.<span style="font-weight:bold;color:#74531f;">Throw</span>();&nbsp;<span style="font-weight:bold;color:#8f08c4;">return</span>&nbsp;<span style="color:#1f377f;">_result</span>;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:blue;">void</span>&nbsp;<span style="font-weight:bold;color:#74531f;">AwaitOnCompleted</span>&lt;<span style="color:#2b91af;">TAwaiter</span>,&nbsp;<span style="color:#2b91af;">TStateMachine</span>&gt;(<span style="color:blue;">ref</span>&nbsp;<span style="color:#2b91af;">TAwaiter</span>&nbsp;<span style="font-weight:bold;color:#1f377f;">awaiter</span>,&nbsp;<span style="color:blue;">ref</span>&nbsp;<span style="color:#2b91af;">TStateMachine</span>&nbsp;<span style="font-weight:bold;color:#1f377f;">stateMachine</span>) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">where</span>&nbsp;<span style="color:#2b91af;">TAwaiter</span>&nbsp;:&nbsp;<span style="color:#2b91af;">INotifyCompletion</span> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">where</span>&nbsp;<span style="color:#2b91af;">TStateMachine</span>&nbsp;:&nbsp;<span style="color:#2b91af;">IAsyncStateMachine</span> &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="font-weight:bold;color:#8f08c4;">if</span>&nbsp;(<span style="font-weight:bold;color:#1f377f;">awaiter</span>&nbsp;<span style="color:blue;">is</span>&nbsp;<span style="color:#2b91af;">INoneAwaiter</span>) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#1f377f;">_result</span>&nbsp;=&nbsp;<span style="color:#2b91af;">Option</span>&lt;<span style="color:#2b91af;">T</span>&gt;.None;&nbsp;&nbsp;&nbsp;<span style="color:green;">//&nbsp;short-circuit:&nbsp;never&nbsp;resume&nbsp;the&nbsp;state&nbsp;machine</span> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="font-weight:bold;color:#8f08c4;">else</span> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="font-weight:bold;color:#8f08c4;">throw</span>&nbsp;<span style="color:blue;">new</span>&nbsp;<span style="color:#2b91af;">NotSupportedException</span>(<span style="color:#a31515;">&quot;Only&nbsp;Option&lt;T&gt;&nbsp;can&nbsp;be&nbsp;awaited&nbsp;inside&nbsp;an&nbsp;async&nbsp;Option&lt;T&gt;&nbsp;method.&quot;</span>); &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">public</span>&nbsp;<span style="color:blue;">void</span>&nbsp;<span style="font-weight:bold;color:#74531f;">AwaitUnsafeOnCompleted</span>&lt;<span style="color:#2b91af;">TAwaiter</span>,&nbsp;<span style="color:#2b91af;">TStateMachine</span>&gt;(<span style="color:blue;">ref</span>&nbsp;<span style="color:#2b91af;">TAwaiter</span>&nbsp;<span style="font-weight:bold;color:#1f377f;">awaiter</span>,&nbsp;<span style="color:blue;">ref</span>&nbsp;<span style="color:#2b91af;">TStateMachine</span>&nbsp;<span style="font-weight:bold;color:#1f377f;">stateMachine</span>) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">where</span>&nbsp;<span style="color:#2b91af;">TAwaiter</span>&nbsp;:&nbsp;<span style="color:#2b91af;">ICriticalNotifyCompletion</span> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">where</span>&nbsp;<span style="color:#2b91af;">TStateMachine</span>&nbsp;:&nbsp;<span style="color:#2b91af;">IAsyncStateMachine</span> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;=&gt;&nbsp;<span style="font-weight:bold;color:#74531f;">AwaitOnCompleted</span>(<span style="color:blue;">ref</span>&nbsp;<span style="font-weight:bold;color:#1f377f;">awaiter</span>,&nbsp;<span style="color:blue;">ref</span>&nbsp;<span style="font-weight:bold;color:#1f377f;">stateMachine</span>); }</pre> </details> </div> <div class="comment-date">2026-11-23 16:20 UTC</div> </div> <div class="comment" id="6e5f2c575ab54026b80326ab7235daef"> <div class="comment-author"><a href="/">Mark Seemann</a> <a href="#6e5f2c575ab54026b80326ab7235daef">#</a></div> <div class="comment-content"> <p> Thank you for writing. I was, indeed, aware of that option(!), but chose not to discuss it because I was concerned that it would make the article less readable. In any case, I don't think it changes the conclusion. </p> <p> The point of the article is that F# is a better programming language than C#. Even if something is <em>possible</em> in both languages, but one language makes it much harder than the other, then that only demonstrates that one is better than the other. </p> <p> Whether there is something <em>fundamentally</em> wrong with using awaitable types as monads, as you (and others) propose, is another question, and to be honest, I don't (yet) know. One way to attempt to answer that question is to examine whether or not the <a href="/2022/04/11/monad-laws">monad laws</a> hold for such an implementation. Given that the implementation is riddled with exception branches and mutable state, that's not an easy undertaking. </p> <p> This also hints at a more practical reason why you don't see this much in the wild. It's complicated. </p> <p> Still, you could argue that most monadic types (like your proposed <code>Option</code>) are reusable, so even if the implementation is tricky, once implemented and well tested, it could provide benefits to 'normal' users. So why don't we see this more? </p> <p> A more practical explanation, I'm guessing, is that it's just a hard sell. It's not natural to <em>await</em> an option. What's asynchronous about it? The same question could be asked of many other monadic types, like <a href="/2022/05/09/an-either-monad">Either</a>, <a href="/2022/06/20/the-state-monad">State</a>, or <a href="/2022/11/14/the-reader-monad">Reader</a>. What's asynchronous about <em>state</em>? Why would you await it? </p> <p> Another question that comes to mind that I honestly don't know the answer to is this: Theoretically, and in Haskell, a monad is always an <a href="/2018/10/01/applicative-functors">applicative functor</a>, and an applicative functor is always a <a href="/2018/03/22/functors">functor</a>. Thus, we would like our language feature to extend to, and be consistent with, such data structures. Is it possible to make a type awaitable if it's <em>only</em> a functor? </p> </div> <div class="comment-date">2026-12-03 07:20 UTC</div> </div> </div> <hr> This blog is totally free, but if you like it, please consider <a href="https://blog.ploeh.dk/support">supporting it</a>. Mark Seemann https://blog.ploeh.dk/2026/11/16/worse-is-better-asyncawait-versus-syntactic-sugar-for-monadic-composition QuickCheck property: Forced category limit applies https://blog.ploeh.dk/2026/11/09/quickcheck-property-forced-category-limit-applies/ Mon, 09 Nov 2026 06:37:00 UTC <div id="post"> <p> <em>A continued programming exercise using TDD with PBT.</em> </p> <p> This article is one of a series on <a href="/2026/10/19/properties-for-a-budgeting-exercise">finding properties for a budgeting kata</a>. I expect you to have read the previous articles in the series. </p> <p> The first property specified that a bill doesn't exceed the total budget, and that's all there is to say about the total budget. All the complication lies in how category budgets are handled. In this article, we get started on that work, which will continue for another seven properties. </p> <p> The code is <a href="https://github.com/ploeh/BudgetingHaskell">available on GitHub</a>, in the commit <code>aefa192</code>. </p> <h3 id="c3027148ebb142939405be8262dd27e0"> Per-category bounds <a href="#c3027148ebb142939405be8262dd27e0">#</a> </h3> <p> My plan for this exercise was always to attempt it with test-driven development (TDD) using properties rather than singular examples. When doing TDD, I usually keep the <a href="https://blog.cleancoder.com/uncle-bob/2013/05/27/TheTransformationPriorityPremise.html">transformation priority premise</a> in mind: When given a choice between test cases, pick the one you predict will provoke the smallest change to the System Under Test. </p> <p> Here, a good candidate may be a property specifying that for items that have no choice in which category to charge, the total cost of that category must not exceed the category limit. That description is dense, so let's unpack it. Each item in a bill comes with a set of categories. This set may be empty, a singleton, or contain multiple categories. </p> <p> <pre>ghci&gt;&nbsp;Item&nbsp;1&nbsp;1&nbsp;Set.empty Item&nbsp;{itemCost&nbsp;=&nbsp;1,&nbsp;itemCount&nbsp;=&nbsp;1,&nbsp;itemCategories&nbsp;=&nbsp;fromList&nbsp;<span style="color:blue;">[]</span>} ghci&gt;&nbsp;Item&nbsp;1&nbsp;1&nbsp;$&nbsp;Set.singleton&nbsp;<span style="color:#a31515;">&quot;a&quot;</span> Item&nbsp;{itemCost&nbsp;=&nbsp;1,&nbsp;itemCount&nbsp;=&nbsp;1,&nbsp;itemCategories&nbsp;=&nbsp;fromList&nbsp;[<span style="color:#a31515;">&quot;a&quot;</span>]} ghci&gt;&nbsp;Item&nbsp;1&nbsp;1&nbsp;$&nbsp;Set.fromList&nbsp;[<span style="color:#a31515;">&quot;a&quot;</span>,&nbsp;<span style="color:#a31515;">&quot;d&quot;</span>] Item&nbsp;{itemCost&nbsp;=&nbsp;1,&nbsp;itemCount&nbsp;=&nbsp;1,&nbsp;itemCategories&nbsp;=&nbsp;fromList&nbsp;[<span style="color:#a31515;">&quot;a&quot;</span>,<span style="color:#a31515;">&quot;d&quot;</span>]}</pre> </p> <p> Some or all of those categories may be 'unforced' or irrelevant categories. What matters is which categories are associated with limits in the budget. If the budget only comes with a limit for category "a", the first of the above examples has no category limit, and the two other items are uniquely constrained by the "a" limit. For the third example item, the "d" category is irrelevant, since there's no budget limit for "d". </p> <p> Another way to put it: If the intersection between an item's categories and the budget category limits is a singleton, then the item is uniquely constrained by that category. </p> <p> <img src="/content/binary/item-budget-category-singleton-intersection.png" alt="Set intersection of budget and item, sharing only the single category named a." width="200"> </p> <p> There could be more than a single item with the same intersection, but the sum of those items constitute the cost of that category, and (as long as the items are uniquely forced by a single category) that cost must not exceed the category limit. </p> <p> Now that I write this explanation, I wonder whether I could have expressed a property like that, but here's the property that I actually wrote: </p> <p> <pre>testProperty&nbsp;<span style="color:#a31515;">&quot;Forced&nbsp;category&nbsp;limit&nbsp;applies&quot;</span>&nbsp;$&nbsp;\ &nbsp;&nbsp;(<span style="color:blue;">fmap</span>&nbsp;getItem&nbsp;.&nbsp;getNonEmpty&nbsp;-&gt;&nbsp;bill&nbsp;::&nbsp;Bill&nbsp;Char) &nbsp;&nbsp;(NonNegative&nbsp;catLim)&nbsp;-&gt; &nbsp;&nbsp;Set.unions&nbsp;(itemCategories&nbsp;&lt;$&gt;&nbsp;bill)&nbsp;/=&nbsp;mempty&nbsp;==&gt; &nbsp;&nbsp;<span style="color:blue;">do</span> &nbsp;&nbsp;&nbsp;&nbsp;cat&nbsp;&lt;-&nbsp;elements&nbsp;$&nbsp;Set.toList&nbsp;$&nbsp;Set.unions&nbsp;(itemCategories&nbsp;&lt;$&gt;&nbsp;bill) &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:green;">--&nbsp;Force&nbsp;the&nbsp;selected&nbsp;category&nbsp;by&nbsp;making&nbsp;it&nbsp;the&nbsp;only&nbsp;category&nbsp;for&nbsp;those </span>&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:green;">--&nbsp;items&nbsp;that&nbsp;have&nbsp;it. </span>&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">let</span>&nbsp;bill&#39;&nbsp;=&nbsp;(\i&nbsp;-&gt;&nbsp;<span style="color:blue;">if</span>&nbsp;Set.member&nbsp;cat&nbsp;(itemCategories&nbsp;i) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">then</span>&nbsp;i&nbsp;{&nbsp;itemCategories&nbsp;=&nbsp;Set.singleton&nbsp;cat&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">else</span>&nbsp;i)&nbsp;&lt;$&gt;&nbsp;bill &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;budget&nbsp;=&nbsp;Budget&nbsp;(billCost&nbsp;bill&#39;)&nbsp;(Map.singleton&nbsp;cat&nbsp;catLim) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;actual&nbsp;=&nbsp;canAfford&nbsp;budget&nbsp;bill&#39; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;expected&nbsp;=&nbsp;categoryCost&nbsp;cat&nbsp;bill&#39;&nbsp;&lt;=&nbsp;catLim &nbsp;&nbsp;&nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;$&nbsp;counterexample&nbsp;(<span style="color:#a31515;">&quot;Budget:&nbsp;&quot;</span>&nbsp;++&nbsp;<span style="color:blue;">show</span>&nbsp;budget)&nbsp;$ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;counterexample&nbsp;(<span style="color:#a31515;">&quot;Bill:&nbsp;&quot;</span>&nbsp;++&nbsp;<span style="color:blue;">show</span>&nbsp;bill&#39;)&nbsp;$ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;expected&nbsp;===&nbsp;actual</pre> </p> <p> Like the <a href="/2026/10/26/quickcheck-property-uncategorised-bill">previous property</a> this one also <a href="/2018/05/14/project-arbitraries-with-view-patterns">uses view patterns to pull the <code>bill</code> out of a list of <code>AnyItem</code> values</a>, but now this list is a <a href="https://hackage-content.haskell.org/package/QuickCheck/docs/Test-QuickCheck.html#t:NonEmptyList">NonEmptyList</a>. Likewise, pattern matching on <code>NonNegative</code> makes <code>catLim</code> an <code>Int</code>. The entire type for the lambda expression (everything after <code>$&nbsp;\</code> ) is </p> <p> <pre><span style="color:blue;">NonEmptyList</span>&nbsp;(<span style="color:blue;">AnyItem</span>&nbsp;<span style="color:#2b91af;">Char</span>)&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;<span style="color:blue;">NonNegative</span>&nbsp;<span style="color:#2b91af;">Int</span>&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;<span style="color:blue;">Property</span></pre> </p> <p> Notice that I have now changed from <code>Bill String</code> to <code>Bill Char</code>. To be honest, I no longer remember why I did that, but it could be a remnant of an (uncommitted) attempt to constrain <a href="https://hackage.haskell.org/package/QuickCheck">QuickCheck</a>'s choice of categories, so as to increase the chance that it would occasionally create a <code>bill</code> where a category would span more than a single item. Given that <code>Char</code> is actually a Unicode character with more than a million possible values, this was probably naive. </p> <p> The property uses <a href="https://hackage-content.haskell.org/package/QuickCheck/docs/Test-QuickCheck.html#v:-61--61--62-">the implication operator</a> <code>==&gt;</code> to make sure that the generated <code>bill</code> has at least one category on some item. It then picks one category from the set of all categories of the <code>bill</code>, and creates a modified <code>bill'</code> that replaces category sets with only that category for those items that originally included that category. For example, if <code>cat</code> is <code>'a'</code> then </p> <p> <pre>Item&nbsp;1&nbsp;1&nbsp;$&nbsp;Set.fromList&nbsp;[<span style="color:#a31515;">'a'</span>,&nbsp;<span style="color:#a31515;">'d'</span>]</pre> </p> <p> becomes </p> <p> <pre>Item&nbsp;1&nbsp;1&nbsp;$&nbsp;Set.fromList&nbsp;[<span style="color:#a31515;">'a'</span>]</pre> </p> <p> The property constructs a <code>budget</code> by setting a limit <code>catLim</code> only for the chosen category <code>cat</code>. Since <code>catLim</code> is any <code>NonNegative</code> number, this limit may or may not make the bill affordable. This limit, however, is the only deciding factor, since the <code>budget</code> is constructed with a total limit of <code>billCost bill'</code>; in other words, the total limit is always just permissive enough. Thus, the <code>expected</code> result is whether the <code>categoryCost</code> is less than or equal to <code>catLim</code>. </p> <h3 id="4aba62bd800941dca5923ece8bcf6b03"> A questionable API <a href="#4aba62bd800941dca5923ece8bcf6b03">#</a> </h3> <p> I added the <code>categoryCost</code> function to the implementation code: </p> <p> <pre>categoryCost&nbsp;cat&nbsp;= &nbsp;&nbsp;<span style="color:blue;">sum</span>&nbsp;. &nbsp;&nbsp;<span style="color:blue;">fmap</span>&nbsp;(liftA2&nbsp;<span style="color:#2b91af;">(*)</span>&nbsp;itemCost&nbsp;itemCount)&nbsp;. &nbsp;&nbsp;<span style="color:blue;">filter</span>&nbsp;(Set.member&nbsp;cat&nbsp;.&nbsp;itemCategories)</pre> </p> <p> In retrospect, I'm not sure that this was a good idea, because one could argue that the cost of a category depends on how the final algorithm decides to distribute items among categories. For example, you could have a bill like this: </p> <p> <pre>bill&nbsp;=&nbsp;[Item&nbsp;2&nbsp;1&nbsp;$&nbsp;Set.fromList&nbsp;[<span style="color:#a31515;">&#39;a&#39;</span>,&nbsp;<span style="color:#a31515;">&#39;c&#39;</span>],&nbsp;Item&nbsp;2&nbsp;1&nbsp;$&nbsp;Set.fromList&nbsp;[<span style="color:#a31515;">&#39;b&#39;</span>,&nbsp;<span style="color:#a31515;">&#39;c&#39;</span>]]</pre> </p> <p> and a budget like this: </p> <p> <pre>budget&nbsp;=&nbsp;Budget&nbsp;4&nbsp;$&nbsp;Map.fromList&nbsp;[(<span style="color:#a31515;">&#39;a&#39;</span>,&nbsp;2),&nbsp;(<span style="color:#a31515;">&#39;b&#39;</span>,&nbsp;2),&nbsp;(<span style="color:#a31515;">&#39;c&#39;</span>,&nbsp;1)]</pre> </p> <p> A correct implementation of the decision algorithm would consider that bill affordable, because it can distribute the cost of the first item to the <code>'a'</code> category, and the second item to the <code>'b'</code> category. Effectively, the cost of category <code>'c'</code> for that <code>bill</code> is nought. Even so, that's not what <code>categoryCost</code> answers: </p> <p> <pre>ghci&gt;&nbsp;categoryCost&nbsp;<span style="color:#a31515;">&#39;c&#39;</span>&nbsp;bill 4</pre> </p> <p> In a sense, you could argue that this is correct, because <code>categoryCost</code> doesn't take the budget into account. Thus, it's rather an indication of the maximum cost of that category. Perhaps I should have named the function <code>maxCategoryCost</code>. </p> <h3 id="8f861786dd9d4e349f7d47d092fc30a3"> The simplest thing that works <a href="#8f861786dd9d4e349f7d47d092fc30a3">#</a> </h3> <p> Given the two properties so far, the simplest thing I could think of that passes all test cases is this: </p> <p> <pre>canAfford&nbsp;budget&nbsp;bill&nbsp;= &nbsp;&nbsp;billCost&nbsp;bill&nbsp;&lt;=&nbsp;totalLimit&nbsp;budget&nbsp;&amp;&amp; &nbsp;&nbsp;<span style="color:blue;">all</span> &nbsp;&nbsp;&nbsp;&nbsp;(\(cat,&nbsp;lim)&nbsp;-&gt;&nbsp;categoryCost&nbsp;cat&nbsp;bill&nbsp;&lt;=&nbsp;lim) &nbsp;&nbsp;&nbsp;&nbsp;(Map.toList&nbsp;$&nbsp;categoryLimits&nbsp;budget)</pre> </p> <p> It naively checks that for each budgeted category, the <code>categoryCost</code> must not exceed the the category limit. This is clearly incorrect, because it rejects, among many other examples, the <code>bill</code> and <code>budget</code> discussed above. More properties are needed. </p> <h3 id="491f5078d14e473cad0ce7343ba1ffc0"> Conclusion <a href="#491f5078d14e473cad0ce7343ba1ffc0">#</a> </h3> <p> Attempting to do the <a href="https://gist.github.com/hwayne/e5a65b48ab50a2285de47cfc11fc955f">budgeting exercise</a> with TDD using QuickCheck properties, I added the first of many properties to describe the desired behaviour related to category limits. It specifies that if an item is unambiguously forced by a single category limit, then that limit must not be exceeded. </p> <p> This property still feels a bit ad-hoc to me; as one of those 'examples on steroids' I've already discussed. Thus, I was keen to add something that sounded more like proper computer science. </p> <p> <strong>Next:</strong> <a href="/2026/11/23/quickcheck-property-monotonicity-in-items">QuickCheck property: Monotonicity in items</a> </p> </div><hr> This blog is totally free, but if you like it, please consider <a href="https://blog.ploeh.dk/support">supporting it</a>. Mark Seemann https://blog.ploeh.dk/2026/11/09/quickcheck-property-forced-category-limit-applies Is AI the next layer of abstraction? https://blog.ploeh.dk/2026/11/02/is-ai-the-next-layer-of-abstraction/ Mon, 02 Nov 2026 06:54:00 UTC <div id="post"> <p> <em>A question of semantics?</em> </p> <p> With increasing frequency, I come across the notion that <a href="https://en.wikipedia.org/wiki/Large_language_model">large language models</a> (LLMs) constitute a new level of abstraction in programming. A recent post on LinkedIn puts it well: </p> <blockquote> <p> "AI will be the next layer of abstraction in IT. </p> <p> "First we thought in machine instructions, then in procedures and functions, then in objects and patterns that are now built into the languages. With AI, we can use ordinary words to describe what we want, and then the AI writes the code." </p> <footer><cite><a href="https://lnkd.in/p/eiPhY3ek">LinkedIn post</a></cite>, Hans Kilian, 2026, my translation</footer> </blockquote> <p> The post has a bit more to say (in Danish), but is less relevant to the topic that I wish to discuss. To be clear, I have nothing against the assertion made, because whether you believe it ultimately boils down to how you define the term <em>abstraction</em>. </p> <h3 id="e934f65f069742d7a9f8d75854a8abaa"> Semantic levels <a href="#e934f65f069742d7a9f8d75854a8abaa">#</a> </h3> <p> How do you define the word 'abstraction'? While I could do a <a href="https://en.wikipedia.org/wiki/Rich_Hickey">Rich Hickey</a> and look it up in the dictionary, I rather want to pull from other sources. In ordinary language, the word can mean many things to diverse people, while in the context of programming, we have the opportunity to be more specific. </p> <p> You could argue that I'm now <a href="https://en.wikipedia.org/wiki/Argument_from_authority">appealing to authority</a>, but that's not the point I wish to get across. Rather, the layers of abstraction that Hans Kilian lists have some particular properties, nicely phrased by <a href="https://en.wikipedia.org/wiki/Edsger_W._Dijkstra">Edsger Dijkstra</a>: </p> <blockquote> <p> "the purpose of abstracting is <em>not</em> to be vague, but to create a new semantic level in which one can be absolutely precise." </p> <footer><cite><a href="https://www.cs.utexas.edu/~EWD/transcriptions/EWD03xx/EWD340.html">The Humble Programmer</a></cite>, Edsger W. Dijkstra, 1972</footer> </blockquote> <p> The requirement that the new layer of abstraction is precise is important. In general, earlier layers of abstraction have been precise in the sense that they are well-defined. (There are exceptions. <a href="https://en.wikipedia.org/wiki/C_(programming_language)">C</a> infamously have <a href="https://en.wikipedia.org/wiki/Unspecified_behavior">unspecified language features</a>. Haskell, too, is vague about what exactly <a href="https://hackage-content.haskell.org/package/base/docs/Prelude.html#t:Int">Int</a> is.) </p> <p> <img src="/content/binary/abstraction-levels-with-precise-translations.png" alt="Three levels of abstraction, with arrows pointing down from one to the other. The levels are labelled 'high-level languages', 'procedures, types', and 'machine code', respectively. The two arrows are labelled 'precise'." width="300"> </p> <p> The demand that one level of abstraction has a precise meaning in terms of the next level down is, as I view it, a fundamental property of how programming-language abstraction works. </p> <h3 id="c4ffec4978ad43059733d8f7ed2b8254"> Precision <a href="#c4ffec4978ad43059733d8f7ed2b8254">#</a> </h3> <p> How should we think about precision in this context? Fortunately, a complete definition is not required. A few crucial properties are enough to realize that LLM-based programming is not precise. </p> <p> In order to be "absolutely precise" we should at least demand that translation from a higher to a lower level of abstraction is </p> <ul> <li>well-defined and</li> <li>deterministic.</li> </ul> <p> LLM-based coding is neither. When you write an instruction using ordinary words, the translation to code is not defined at all, but rather the result of a prediction system. Furthermore, as most users of LLM hopefully realize, issuing the same prompt twice often elicits different results. </p> <h3 id="eaaa7b641f3f4d0b8ef8495fd346a0ef"> Tools versus automation <a href="#eaaa7b641f3f4d0b8ef8495fd346a0ef">#</a> </h3> <p> The above argument hinges on a particular understanding of the term 'abstraction'. I find this understanding proper in the context of programming-language abstraction, but this is not to say that it's the only reasonable interpretation of the word. </p> <p> Used more loosely, it seems evident that the ability to write program specifications in normal language, and get an executable artefact out of it, surely feels like abstraction. I think, however, that it's important to realize that it's not the same kind as we have previously understood it. </p> <p> Overlooking, or failing to understand, this difference seems dangerous to me. In the <a href="https://www.linkedin.com/pulse/ai-tool-rich-hickey-kjl8e/">words of Rich Hickey</a>, compilers are tools, whereas LLMs offer automation. Tools are predictable once mastered. Automation may or may not be predictable, but is not wielded. You have to trust that the automation does what you intent. Given that LLM-based automation is fundamentally non-deterministic, I personally have a hard time mobilizing such trust. </p> <h3 id="158c5abddc0a46399fe595fe9fd201df"> Conclusion <a href="#158c5abddc0a46399fe595fe9fd201df">#</a> </h3> <p> Is AI the next layer of abstraction? The answer depends on how you define 'abstraction'. In the narrow sense that programmers and computer scientists have historically thought about programming-language abstraction, LLM-based programming is fundamentally different. Under such an interpretation, using LLMs to write code does not constitute a level of abstraction. </p> <p> If, on the other hand, you view levels of abstraction as force multipliers that enable you to do more with less, then yes, LLM-based programming may be viewed as the next level of abstraction. </p> <p> It's up to you to decide which interpretation of the word you prefer. I can't be the judge of that. The point is rather that this new source of productivity is fundamentally different from previous incarnations of programming-language abstraction levels. Understanding this difference may be key to using the new technology effectively and safely. </p> </div><hr> This blog is totally free, but if you like it, please consider <a href="https://blog.ploeh.dk/support">supporting it</a>. Mark Seemann https://blog.ploeh.dk/2026/11/02/is-ai-the-next-layer-of-abstraction QuickCheck property: Uncategorised bill https://blog.ploeh.dk/2026/10/26/quickcheck-property-uncategorised-bill/ Mon, 26 Oct 2026 06:49:00 UTC <div id="post"> <p> <em>Initial API definition and a simple property.</em> </p> <p> This article is one of a series on <a href="/2026/10/19/properties-for-a-budgeting-exercise">finding properties for a budgeting kata</a>. I expect you to have read the previous articles in the series. </p> <p> In this article we get started by adding a first sketch of data structures and an initial, simple property. </p> <p> The code is <a href="https://github.com/ploeh/BudgetingHaskell">available on GitHub</a>, in the commit <code>1f7aceb</code>. </p> <h3 id="39637a0f4bb44bb993ea47155cb92340"> Budget type <a href="#39637a0f4bb44bb993ea47155cb92340">#</a> </h3> <p> My intent with the entire exercise is to follow a variation of test-driven development (TDD) that uses <a href="https://hackage.haskell.org/package/QuickCheck">QuickCheck</a> properties rather than static examples. Even so, <a href="https://www.haskell.org/">Haskell</a> is such a strongly typed language that I often start with a bit of type-driven development, sketching out how data types and functions may look. I did that here as well, starting with the budget. </p> <p> <pre><span style="color:blue;">data</span>&nbsp;Budget&nbsp;a&nbsp;=&nbsp;Budget &nbsp;&nbsp;{&nbsp;totalLimit&nbsp;::&nbsp;Int &nbsp;&nbsp;,&nbsp;categoryLimits&nbsp;::&nbsp;Map&nbsp;a&nbsp;Int &nbsp;&nbsp;}&nbsp;<span style="color:blue;">deriving</span>&nbsp;(<span style="color:#2b91af;">Show</span>,&nbsp;<span style="color:#2b91af;">Eq</span>)</pre> </p> <p> As I noted in the introduction article, this was my third attempt. Two previous attempts had taught me that it might be useful to be able to define the set of values from which category identifiers are picked by QuickCheck. <a href="https://gist.github.com/hwayne/e5a65b48ab50a2285de47cfc11fc955f">Hillel Wayne's examples use strings</a>, which seems quite natural. When, however, QuickCheck generates <code>String</code> values, it picks from an infinite set of values: <code>"a"</code>, <code>"fê</code>, <code>3_\g§ü:</code>, and unprintable things. The probability of generating two identical values in the same property is small, but sometimes, it turns out, that's exactly what we would like. </p> <p> There are many ways you can tell QuickCheck to generate values by picking from a small set, such as the <a href="https://hackage-content.haskell.org/package/QuickCheck/docs/Test-QuickCheck.html#v:elements">elements</a> combinator. The problem with ad-hoc use of such a combinator, however, is that it doesn't support shrinking, and it turns out that for this particular kata, shrinking is indispensable. </p> <p> As I also mentioned in the introduction, while being mature, QuickCheck also comes with some baggage. Perhaps the most prominent drawback is its lack of automatic shrinking. In order to support shrinking, you must define an <a href="https://hackage-content.haskell.org/package/QuickCheck/docs/Test-QuickCheck.html#t:Arbitrary">Arbitrary</a> instance, and this again means introducing a type. </p> <p> As so many other Haskell libraries, QuickCheck relies quite heavily on types. If you need to define a type in order to control how values are generated, it might be easier to make a data structure polymorphic and then pick a useful type on a property-by-property basis. So with that in mind (and two botched attempts already behind me), I made <code>Budget</code> parametric in its category identifier type: The <code>categoryLimits</code> element is a map from some identifier of the type <code>a</code> to an <code>Int</code>. Since <code>a</code> could be <code>String</code>, this design still supports the specification. </p> <p> This is a concession to better support testing, and ultimately, I'm not entirely sure that it helped that much. Ironically, there's some evidence that it might have been at least as useful to parametrize the limit itself, since <code>Int</code> also allows (at least) millions of distinct values. </p> <h3 id="850f2ac6cb974242bb347b5b23c91560"> Item and bill types <a href="#850f2ac6cb974242bb347b5b23c91560">#</a> </h3> <p> In order to compare budgets to bills, we must also make each item in a bill polymorphic: </p> <p> <pre><span style="color:green;">{-While&nbsp;the&nbsp;original&nbsp;problem&nbsp;specification&nbsp;has&nbsp;count&nbsp;and&nbsp;categories&nbsp;optional, &nbsp;&nbsp;we&nbsp;may&nbsp;deal&nbsp;with&nbsp;this&nbsp;in&nbsp;a&nbsp;hypothetical&nbsp;parsing&nbsp;step,&nbsp;setting&nbsp;count&nbsp;to&nbsp;1&nbsp;if &nbsp;&nbsp;missing,&nbsp;and&nbsp;likewise&nbsp;setting&nbsp;categories&nbsp;to&nbsp;the&nbsp;empty&nbsp;set&nbsp;if&nbsp;missing.-}</span> <span style="color:blue;">data</span>&nbsp;Item&nbsp;a&nbsp;=&nbsp;Item &nbsp;&nbsp;{&nbsp;itemCost&nbsp;::&nbsp;Int &nbsp;&nbsp;,&nbsp;itemCount&nbsp;::&nbsp;Int &nbsp;&nbsp;,&nbsp;itemCategories&nbsp;::&nbsp;Set&nbsp;a &nbsp;&nbsp;}&nbsp;<span style="color:blue;">deriving</span>&nbsp;(<span style="color:#2b91af;">Show</span>,&nbsp;<span style="color:#2b91af;">Eq</span>)</pre> </p> <p> As is suggested by the comment, I didn't really feel like dealing with defining count and categories as optional. Both have natural default values, as the specification also defines. I did, in fact, for a time toy with making <code>Item</code> a <code>Monoid</code> instance, but while a lawful definition exists, it doesn't fit the business rules. You can't meaningfully combine two items with different category sets. Doing so would change the outcome of the decision algorithm. </p> <p> A bill, then, is just a type alias for a list of items: </p> <p> <pre><span style="color:blue;">type</span>&nbsp;Bill&nbsp;a&nbsp;=&nbsp;[Item&nbsp;a]</pre> </p> <p> Those are all the data structures required for the kata. </p> <h3 id="b256c9803bfa4ff1849c051f1844fe23"> Functions <a href="#b256c9803bfa4ff1849c051f1844fe23">#</a> </h3> <p> In addition to <code>Budget</code> and <code>Item</code> we also need at least a <code>canAfford</code> function. It turns out that a few auxiliary functions are also useful when writing the QuickCheck properties. For the first property, only this <code>billCost</code> function is in use, but later commits add a few more: </p> <p> <pre><span style="color:#2b91af;">billCost</span>&nbsp;<span style="color:blue;">::</span>&nbsp;(<span style="color:blue;">Foldable</span>&nbsp;t,&nbsp;<span style="color:blue;">Functor</span>&nbsp;t)&nbsp;<span style="color:blue;">=&gt;</span>&nbsp;t&nbsp;(<span style="color:blue;">Item</span>&nbsp;a)&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;<span style="color:#2b91af;">Int</span> billCost&nbsp;bill&nbsp;=&nbsp;<span style="color:blue;">sum</span>&nbsp;$&nbsp;<span style="color:blue;">fmap</span>&nbsp;(liftA2&nbsp;<span style="color:#2b91af;">(*)</span>&nbsp;itemCost&nbsp;itemCount)&nbsp;bill</pre> </p> <p> As I've previously given out, I <a href="/2024/11/04/pendulum-swing-no-haskell-type-annotation-by-default">often don't add a type declaration to functions</a>, and if you consult the Git repository, you will also see that <code>billCost</code> is unannotated. I only added the type annotation in post-production, in order to make reading this article a iota easier. </p> <p> I did, however, add a type declaration to <code>canAfford</code>, because at first, in true TDD style, I left it unimplemented, and I needed to have enough of a type to prevent QuickCheck from complaining that it couldn't decide on which instance to pick. Or something. </p> <p> <pre><span style="color:#2b91af;">canAfford</span>&nbsp;<span style="color:blue;">::</span>&nbsp;<span style="color:blue;">Budget</span>&nbsp;a&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;<span style="color:blue;">Bill</span>&nbsp;a&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;<span style="color:#2b91af;">Bool</span></pre> </p> <p> The most important part of this declaration is that the type parameters for <code>Budget</code> and <code>Bill</code> must match. </p> <h3 id="a1b55fd6abe844a58b9371c06dced603"> An Arbitrary instance for Item <a href="#a1b55fd6abe844a58b9371c06dced603">#</a> </h3> <p> To define properties, we need test data generators. As I mentioned in the introduction article, property-based testing involves a degree of boilerplate code. <a href="/2019/09/02/naming-newtypes-for-quickcheck-arbitraries">In order to avoid orphan instances, you can define a test-specific AnyItem newtype</a>. </p> <p> <pre><span style="color:blue;">newtype</span>&nbsp;AnyItem&nbsp;a&nbsp;=&nbsp;AnyItem&nbsp;{&nbsp;getItem&nbsp;::&nbsp;Item&nbsp;a&nbsp;}&nbsp;<span style="color:blue;">deriving</span>&nbsp;(<span style="color:#2b91af;">Show</span>,&nbsp;<span style="color:#2b91af;">Eq</span>)</pre> </p> <p> You can now give <code>AnyItem</code> an <code>Arbitrary</code> instance. </p> <p> <pre><span style="color:blue;">instance</span>&nbsp;(<span style="color:blue;">Arbitrary</span>&nbsp;a,&nbsp;<span style="color:blue;">Ord</span>&nbsp;a)&nbsp;<span style="color:blue;">=&gt;</span>&nbsp;<span style="color:blue;">Arbitrary</span>&nbsp;(<span style="color:blue;">AnyItem</span>&nbsp;a)&nbsp;<span style="color:blue;">where</span> &nbsp;&nbsp;arbitrary&nbsp;=&nbsp;<span style="color:blue;">do</span> &nbsp;&nbsp;&nbsp;&nbsp;Positive&nbsp;cost&nbsp;&lt;-&nbsp;arbitrary &nbsp;&nbsp;&nbsp;&nbsp;Positive&nbsp;count&nbsp;&lt;-&nbsp;arbitrary &nbsp;&nbsp;&nbsp;&nbsp;AnyItem&nbsp;.&nbsp;Item&nbsp;cost&nbsp;count&nbsp;&lt;$&gt;&nbsp;arbitrary &nbsp;&nbsp;shrink&nbsp;(AnyItem&nbsp;(Item&nbsp;cost&nbsp;count&nbsp;categories))&nbsp;= &nbsp;&nbsp;&nbsp;&nbsp;[&nbsp;AnyItem&nbsp;$&nbsp;Item&nbsp;cost&#39;&nbsp;count&#39;&nbsp;categories&#39; &nbsp;&nbsp;&nbsp;&nbsp;|&nbsp;(Positive&nbsp;cost&#39;,&nbsp;Positive&nbsp;count&#39;,&nbsp;categories&#39;)&nbsp;&lt;- &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;shrink&nbsp;(Positive&nbsp;cost,&nbsp;Positive&nbsp;count,&nbsp;categories) &nbsp;&nbsp;&nbsp;&nbsp;]</pre> </p> <p> I often dispense with defining the <code>shrink</code> method, but for the properties we'll see before we are done, shrinking turns out to be quite useful. Just like the <code>arbitrary</code> method composes <code>Arbitrary</code> instances for the three constituent values of <code>Item</code>, the <code>shrink</code> method uses the shrinkers associated with <code>Positive Int</code> and <code>Set a</code>, respectively. The only marginally complicated part is the wrapping and unwrapping of <a href="https://hackage-content.haskell.org/package/QuickCheck/docs/Test-QuickCheck.html#t:Positive">Positive</a>, making sure that both <code>itemCost</code> and <code>itemCount</code> stay greater than nought. </p> <h3 id="ecd045360e5f4888a96f164ee99f24a1"> Property <a href="#ecd045360e5f4888a96f164ee99f24a1">#</a> </h3> <p> The first property that came immediately to mind was to consider the total limit. Regardless of all other rules, if the total cost of the bill exceeds the total budget, then the bill is not affordable. There are many ways you could express such a property, but I chose to do it like this: </p> <p> <pre>testProperty&nbsp;<span style="color:#a31515;">&quot;Uncategorized&nbsp;bill&nbsp;is&nbsp;only&nbsp;determined&nbsp;by&nbsp;its&nbsp;cost&quot;</span>&nbsp;$&nbsp;\ &nbsp;&nbsp;(<span style="color:blue;">fmap</span>&nbsp;getItem&nbsp;-&gt;&nbsp;bill&nbsp;::&nbsp;Bill&nbsp;String)&nbsp;(NonNegative&nbsp;lim)&nbsp;-&gt; &nbsp;&nbsp;<span style="color:blue;">let</span>&nbsp;budget&nbsp;=&nbsp;Budget&nbsp;lim&nbsp;(mempty&nbsp;::&nbsp;Map&nbsp;String&nbsp;Int) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;bill&#39;&nbsp;=&nbsp;(\i&nbsp;-&gt;&nbsp;i&nbsp;{&nbsp;itemCategories&nbsp;=&nbsp;mempty&nbsp;})&nbsp;&lt;$&gt;&nbsp;bill &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;actual&nbsp;=&nbsp;canAfford&nbsp;budget&nbsp;bill&#39; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;expected&nbsp;=&nbsp;billCost&nbsp;bill&#39;&nbsp;&lt;=&nbsp;lim &nbsp;&nbsp;<span style="color:blue;">in</span>&nbsp;counterexample&nbsp;(<span style="color:#a31515;">&quot;Budget:&nbsp;&quot;</span>&nbsp;++&nbsp;<span style="color:blue;">show</span>&nbsp;budget)&nbsp;$ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;counterexample&nbsp;(<span style="color:#a31515;">&quot;Bill:&nbsp;&quot;</span>&nbsp;++&nbsp;<span style="color:blue;">show</span>&nbsp;bill&#39;)&nbsp;$ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;expected&nbsp;===&nbsp;actual</pre> </p> <p> As I usually do, I wrote this property (and the ones that follow) as inlined values in a test list, similarly to <a href="/2018/05/07/inlined-hunit-test-lists">how I do it with example-based tests</a>. I also <a href="/2018/05/14/project-arbitraries-with-view-patterns">used view patterns to pull the <code>bill</code> out of the list of <code>AnyItem</code> values</a> I've asked it to generate. The entire type for the lambda expression (everything after <code>$&nbsp;\</code> ) is </p> <p> <pre>[<span style="color:blue;">AnyItem</span>&nbsp;<span style="color:#2b91af;">String</span>]&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;<span style="color:blue;">NonNegative</span>&nbsp;<span style="color:#2b91af;">Int</span>&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;<span style="color:blue;">Property</span></pre> </p> <p> That is, the property takes as input a list of <code>AnyItem String</code> and a <code>NonNegative Int</code>, and then defines the property as the <code>let</code>-<code>in</code> expression. Thanks to the magic of pattern matching and view patterns, <code>bill</code> is a <code>Bill String</code> and <code>lim</code> an <code>Int</code>. </p> <p> The reason I had to annotate <code>bill</code> is because otherwise the entire property is parametrically polymorphic, and then QuickCheck doesn't know what to do. </p> <p> Now that I'm writing this article, I think that I could have defined an even stronger property by just leaving <code>bill</code> be, instead of setting all <code>itemCategories</code> to the empty set. That would also have made the code simpler. </p> <p> A stronger reservation I have against this property is that it temporarily defines the implementation as the <code>expected</code> value. </p> <h3 id="8b5522c49da94e33a1919ceb4f4eccf0"> Implementation <a href="#8b5522c49da94e33a1919ceb4f4eccf0">#</a> </h3> <p> Not surprisingly, the simplest thing that passes all tests is this: </p> <p> <pre><span style="color:#2b91af;">canAfford</span>&nbsp;<span style="color:blue;">::</span>&nbsp;<span style="color:blue;">Budget</span>&nbsp;a&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;<span style="color:blue;">Bill</span>&nbsp;a&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;<span style="color:#2b91af;">Bool</span> canAfford&nbsp;budget&nbsp;bill&nbsp;=&nbsp;billCost&nbsp;bill&nbsp;&lt;=&nbsp;totalLimit&nbsp;budget</pre> </p> <p> Too close to the property for comfort. </p> <h3 id="33ecc195bf3a4e7c8604e88342d7b981"> Alternative properties <a href="#33ecc195bf3a4e7c8604e88342d7b981">#</a> </h3> <p> When I made my first attempt at the kata, I approached the first property in a more traditional example-driven way. I first wrote one test to demonstrate that an affordable bill without categories is affordable: </p> <p> <pre>testProperty&nbsp;<span style="color:#a31515;">&quot;Affordable&nbsp;uncategorized&nbsp;bill&quot;</span>&nbsp;$&nbsp;<span style="color:blue;">do</span> &nbsp;&nbsp;UncategorizedBill&nbsp;bill&nbsp;&lt;-&nbsp;arbitrary &nbsp;&nbsp;<span style="color:blue;">let</span>&nbsp;cost&nbsp;=&nbsp;billCost&nbsp;bill &nbsp;&nbsp;NonNegative&nbsp;surplus&nbsp;&lt;-&nbsp;arbitrary &nbsp;&nbsp;categories&nbsp;&lt;-&nbsp;listOf&nbsp;(CategoryBudget&nbsp;&lt;$&gt;&nbsp;arbitrary&nbsp;&lt;*&gt;&nbsp;arbitrary) &nbsp;&nbsp;<span style="color:blue;">let</span>&nbsp;budget&nbsp;=&nbsp;Budget&nbsp;(cost&nbsp;+&nbsp;surplus)&nbsp;categories &nbsp;&nbsp;<span style="color:blue;">let</span>&nbsp;actual&nbsp;=&nbsp;canAfford&nbsp;budget&nbsp;bill &nbsp;&nbsp;<span style="color:blue;">let</span>&nbsp;errMsg&nbsp;=&nbsp;<span style="color:#a31515;">&quot;budget:&nbsp;&quot;</span>&nbsp;++&nbsp;<span style="color:blue;">show</span>&nbsp;budget&nbsp;++&nbsp;<span style="color:#a31515;">&quot;,&nbsp;bill:&nbsp;&quot;</span>&nbsp;++&nbsp;<span style="color:blue;">show</span>&nbsp;bill &nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;$&nbsp;counterexample&nbsp;errMsg&nbsp;actual</pre> </p> <p> This property makes use of slightly different data definitions. You can see details in the <code>first-attempt</code> branch if you want. </p> <p> The point is that this property explicitly constructs a <code>budget</code> such that the <code>bill</code> is always affordable. It therefore asserts that <code>actual</code> is <code>True</code>. </p> <p> The corresponding implementation is, of course, </p> <p> <pre><span style="color:#2b91af;">canAfford</span>&nbsp;<span style="color:blue;">::</span>&nbsp;<span style="color:blue;">Budget</span>&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;<span style="color:blue;">Bill</span>&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;<span style="color:#2b91af;">Bool</span> canAfford&nbsp;_&nbsp;_&nbsp;=&nbsp;True</pre> </p> <p> Another property then explicitly checks the other <a href="https://en.wikipedia.org/wiki/Partition_of_a_set">partition</a>, which is when a bill without categories is always unaffordable. </p> <p> <pre>testProperty&nbsp;<span style="color:#a31515;">&quot;Unaffordable&nbsp;uncategorized&nbsp;bill&quot;</span>&nbsp;$&nbsp;<span style="color:blue;">do</span> &nbsp;&nbsp;UncategorizedBill&nbsp;bill&nbsp;&lt;-&nbsp;arbitrary &nbsp;&nbsp;<span style="color:blue;">let</span>&nbsp;cost&nbsp;=&nbsp;billCost&nbsp;bill &nbsp;&nbsp;Positive&nbsp;deficit&nbsp;&lt;-&nbsp;arbitrary &nbsp;&nbsp;categories&nbsp;&lt;-&nbsp;listOf&nbsp;(CategoryBudget&nbsp;&lt;$&gt;&nbsp;arbitrary&nbsp;&lt;*&gt;&nbsp;arbitrary) &nbsp;&nbsp;<span style="color:blue;">let</span>&nbsp;budget&nbsp;=&nbsp;Budget&nbsp;(cost&nbsp;-&nbsp;deficit)&nbsp;categories &nbsp;&nbsp;<span style="color:blue;">let</span>&nbsp;actual&nbsp;=&nbsp;canAfford&nbsp;budget&nbsp;bill &nbsp;&nbsp;<span style="color:blue;">let</span>&nbsp;errMsg&nbsp;=&nbsp;<span style="color:#a31515;">&quot;budget:&nbsp;&quot;</span>&nbsp;++&nbsp;<span style="color:blue;">show</span>&nbsp;budget&nbsp;++&nbsp;<span style="color:#a31515;">&quot;,&nbsp;bill:&nbsp;&quot;</span>&nbsp;++&nbsp;<span style="color:blue;">show</span>&nbsp;bill &nbsp;&nbsp;<span style="color:blue;">return</span>&nbsp;$&nbsp;counterexample&nbsp;errMsg&nbsp;$&nbsp;<span style="color:blue;">not</span>&nbsp;actual</pre> </p> <p> This property explicitly constructs a <code>budget</code> so that it always makes the <code>bill</code> unaffordable. It then asserts <code>not actual</code>; that is, that <code>actual</code> is <code>False</code>. </p> <p> Together with the previous property, this then leads to the implementation </p> <p> <pre><span style="color:#2b91af;">canAfford</span>&nbsp;<span style="color:blue;">::</span>&nbsp;<span style="color:blue;">Budget</span>&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;<span style="color:blue;">Bill</span>&nbsp;<span style="color:blue;">-&gt;</span>&nbsp;<span style="color:#2b91af;">Bool</span> canAfford&nbsp;budget&nbsp;bill&nbsp;=&nbsp;billCost&nbsp;bill&nbsp;&lt;=&nbsp;totalLimit&nbsp;budget</pre> </p> <p> This test design avoids duplicating implementation code as test code, so why didn't I stay that course? </p> <p> What I <em>don't</em> like about this approach is the test duplication. Notice how similar the two tests are. Some people might point out that tests may be <a href="http://blog.jayfields.com/2006/05/dry-code-damp-dsls.html">DAMP</a>, but as I've <a href="/2025/12/01/treat-test-code-like-production-code">already been over</a>, DRY and DAMP should be treated as an intersection rather than a dichotomy. </p> <p> Even so, I can live with a small degree of duplication if it serves a purpose. After all, if we follow the <a href="https://en.wikipedia.org/wiki/Rule_of_three_(computer_programming)">rule of three</a>, we haven't even introduced a triplicate yet. </p> <p> My problem with this duplication is rather that it seems to buy us nothing. Together, those two tests exhibits just as much 'knowledge' about the implementation than the single "Uncategorized bill is only determined by its cost" property does. </p> <p> The "Affordable uncategorized bill" property knows (or rather, specifies) that it can go right to the limit of <code>billCost bill</code>. It can add <code>0</code>, or anything greater than <code>0</code>, to <code>billCost bill</code>, and <code>actual</code> will remain <code>True</code>. </p> <p> Likewise, "Unaffordable uncategorized bill" knows (or, again, specifies) that it must subtract at least <code>1</code> from <code>billCost bill</code> for <code>actual</code> to become <code>False</code>. </p> <p> Let <code>lim = cost + surplus</code> or <code>lim = cost - deficit</code>, respectively. You now have two tests that effectively say </p> <p> <pre><span style="color:blue;">if</span>&nbsp;billCost&nbsp;bill&nbsp;&lt;=&nbsp;lim&nbsp;<span style="color:blue;">then</span>&nbsp;True&nbsp;<span style="color:blue;">else</span>&nbsp;False</pre> </p> <p> which is just a long-winded way of saying </p> <p> <pre>billCost&nbsp;bill&nbsp;&lt;=&nbsp;lim</pre> </p> <p> which <a href="https://hackage.haskell.org/package/hlint">hlint</a> will also tell you. </p> <p> So my reasoning is that the two alternative properties are effectively equivalent to the single "Uncategorized bill is only determined by its cost" property. </p> <p> I'm still not blissful about duplicating production code as test code, but I take solace in the prediction that the implementation of <code>canAfford</code> is not going to stay that simple. </p> <h3 id="d3f1a721e01240a6bcb171a533527fe1"> Conclusion <a href="#d3f1a721e01240a6bcb171a533527fe1">#</a> </h3> <p> In this article, you saw data definitions and an initial property to get started on the problem. The property is one of the simplest we are going to cover, but on the other hand, now that we have covered the data structures and the APIs, these will not change in any significant way. The next articles are more devoted to the properties being introduced. </p> <p> <strong>Next:</strong> <a href="/2026/11/09/quickcheck-property-forced-category-limit-applies">QuickCheck property: Forced category limit applies</a>. </p> </div> <hr> This blog is totally free, but if you like it, please consider <a href="https://blog.ploeh.dk/support">supporting it</a>. Mark Seemann https://blog.ploeh.dk/2026/10/26/quickcheck-property-uncategorised-bill Properties for a budgeting exercise https://blog.ploeh.dk/2026/10/19/properties-for-a-budgeting-exercise/ Mon, 19 Oct 2026 06:43:00 UTC <div id="post"> <p> <em>Attempting to conjure good properties.</em> </p> <p> Ever since I learned about property-based testing, I've been fascinated by it. The notion of <a href="/2017/09/18/the-test-data-generator-functor">test data generators</a> seem superior to <a href="http://www.natpryce.com/articles/000714.html">Test Data Builders</a>: Both require some degree of test-specific boilerplate code, but you get more bang for your bob with test data generators. Instead of hard-coding some (often arbitrary) constant value in a Test Data Builder, you define a range of values that, one hopes, belong to the same <a href="https://en.wikipedia.org/wiki/Equivalence_partitioning">equivalence class</a>. </p> <p> Getting started with property-based testing isn't much more difficult than writing good unit tests with Test Data Builders. You can start with a simple unit test that exercises a single example, and fairly mechanically use test data generators to abstract away all the test code that doesn't really matter, but has to be there anyway. I've shown a comprehensive example in my article <a href="/2023/04/17/a-restaurant-example-of-refactoring-from-example-based-to-property-based-testing">A restaurant example of refactoring from example-based to property-based testing</a>. </p> <p> This process, however, may ultimately produce what I've privately dubbed 'example-driven tests on steroids'. They can be useful enough, but don't seem to embody the notion of a <em>property</em>. </p> <h3 id="a9a7945a7eb549c18f8c67a195d1f46a"> What's a property? <a href="#a9a7945a7eb549c18f8c67a195d1f46a">#</a> </h3> <p> First, it may be helpful to dispel any confusion. Some languages have <a href="https://en.wikipedia.org/wiki/Property_(programming)">properties</a>: A special kind of class member that looks like a public class field, but provides a limited buffer zone between an object's internal data structures and the outside world. To be clear, I <a href="/2012/11/27/Encapsulationofproperties">don't consider this kind of feature to be worth much in terms of encapsulation</a>, but that's a different discussion. </p> <p> Property-based testing is not about that kind of property. </p> <p> Rather, the point of property-based testing is to test how an operation systematically behaves. The technique originates in functional programming as a means to test functions. If you think of functions as mathematical objects, a function may exhibit various properties, such as being <a href="https://en.wikipedia.org/wiki/Monotonic_function">monotonic</a>, being <a href="https://en.wikipedia.org/wiki/Differentiable_function">differentiable</a>, defining a <a href="https://simple.wikipedia.org/wiki/Relation_(mathematics)">relation</a>, being <a href="https://en.wikipedia.org/wiki/Associative_property">associative</a>, <a href="https://en.wikipedia.org/wiki/Idempotence">idempotent</a>, etc. </p> <p> When it comes to software design, the notion of a function having properties seems closely related to <a href="/encapsulation-and-solid">encapsulation</a>, in the sense of design by contract. An <em>invariant</em> sounds to me like a synonym for <em>property</em>. </p> <p> When working in the realm of mathematics, identifying properties may be fairly straightforward. On the other hand, when working with business rules, or some kind of domain with no direct line to mathematics, they can be harder to find. Particularly if you wish to avoid repeating implementation logic in the properties. For example, it took me years before I managed to identify <a href="/2021/06/28/property-based-testing-is-not-the-same-as-partition-testing">good properties even for such a simple problem as FizzBuzz</a>. </p> <p> Even though Scott Wlaschin, as ever, has a great <a href="https://fsharpforfunandprofit.com/posts/property-based-testing-2/">list of suggestions</a>, finding true properties seems like an elusive problem. Which often makes me grab onto it with even more resolve. </p> <h3 id="d388da20d9384d7eb55a3d1ea0986a87"> Hillel Wayne's budgeting kata <a href="#d388da20d9384d7eb55a3d1ea0986a87">#</a> </h3> <p> When I ran into Hillel Wayne's <a href="https://gist.github.com/hwayne/e5a65b48ab50a2285de47cfc11fc955f">budgeting problem</a>, I knew I had to try my hand at it. </p> <p> It takes less that five minutes to read the problem description, so there's no point in summarizing it here. A bit of context, on the other hand, may be in order, since the problem definition offers none. I found out about it via <a href="https://www.crustofcode.com/arriving-at-properties/">one of Brian Marick's blog posts</a>, but that article doesn't give much context either. So <a href="https://mastodon.social/@ploeh/116001192839854849">I asked Brian Marick</a>, who graciously supplied a little more information. Later, <a href="https://bsky.app/profile/hillelwayne.com/post/3mwdv3k6us22f">Hillel Wayne confirmed</a> that it's a problem designed to compare property-based testing to example-based testing. </p> <p> As I often do <a href="/2020/01/13/on-doing-katas">when I engage with katas</a>, I imposed some constraints. I wanted to take on this problem using test-driven development (TDD) driven by true properties, rather than 'examples on steroids'. </p> <p> This turned out to be surprisingly formidable. </p> <h3 id="80ab898f20064aa9a81974d9ade8b0fa"> The third time's a charm <a href="#80ab898f20064aa9a81974d9ade8b0fa">#</a> </h3> <p> I don't know if my limited exposure to <a href="https://en.wikipedia.org/wiki/Large_language_model">LLM</a>-driven development had already dulled my skills, or if this is just a truly difficult problem, but I had two false starts before I managed to arrive at something that I consider adequate. </p> <p> I've posted the relevant <a href="https://github.com/ploeh/BudgetingHaskell">repository on GitHub</a>. The first two attempts are visible in the <code>first-attempt</code> and <code>second-attempt</code> branches, but I'm going to offer no commentary. You may consult the commit messages if you are curious. </p> <p> In the rest of this article series, I will cover my progress one property at a time. </p> <ul> <li><a href="/2026/10/26/quickcheck-property-uncategorised-bill">QuickCheck property: Uncategorised bill</a></li> <li><a href="/2026/11/09/quickcheck-property-forced-category-limit-applies">QuickCheck property: Forced category limit applies</a></li> <li><a href="/2026/11/23/quickcheck-property-monotonicity-in-items">QuickCheck property: Monotonicity in items</a></li> <li>QuickCheck property: Monotonicity in categories</li> <li>QuickCheck property: Valid assignment</li> <li>QuickCheck property: Category zero-limits</li> <li>QuickCheck property: No category fit is unaffordable</li> <li>QuickCheck property: Adding unbudgeted category</li> <li>QuickCheck property: Distributivity</li> </ul> <p> I chose QuickCheck for property-based testing (PBT) because it's so mature. It also has some drawbacks, particularly when it comes to shrinking. Thus, I may revisit this problem with another PBT framework, possibly in another programming language. That's the reason I've prefixed all article names with QuickCheck: It leaves room for more articles using another framework. </p> <h3 id="8848dc9c6a2b4d27ae509e9f3f876b94"> Conclusion <a href="#8848dc9c6a2b4d27ae509e9f3f876b94">#</a> </h3> <p> Having also read <a href="https://www.crustofcode.com/hillel-budget/">Brian Marick's walkthrough</a> of his example-driven attempt, I'd be inclined to accept defeat. It looks as though this problem would be easier to solve with 'old-fashioned' TDD. </p> <p> On the other hand, I learned a thing or two along the way, so I still think it was a rewarding exercise, worth reporting on. </p> <p> <strong>Next:</strong> <a href="/2026/10/26/quickcheck-property-uncategorised-bill">QuickCheck property: Uncategorised bill</a>. </p> </div> <hr> This blog is totally free, but if you like it, please consider <a href="https://blog.ploeh.dk/support">supporting it</a>. Mark Seemann https://blog.ploeh.dk/2026/10/19/properties-for-a-budgeting-exercise Releasing AI-generated software https://blog.ploeh.dk/2026/10/12/releasing-ai-generated-software/ Mon, 12 Oct 2026 06:22:00 UTC <div id="post"> <p> <em>On software engineering, epistemology, and liability when code is generated by LLMs.</em> </p> <p> Robert C. Martin recently generated much interest with a tweet: </p> <blockquote> <p> "My current strategy is to not read any of the code written by my agents. That's the only way I can take advantage of their productivity. What I do instead is to surround the agents with extreme constraints. Unit tests, gherkin tests, QA procedures, quality metrics, mutation testing, test coverage, and a plethora of others. In the end, I have very high confidence in the code they produce because they've had to run the gauntlet of all of my constraints and tests." </p> <footer><cite><a href="https://x.com/unclebobmartin/status/2080257779395154409">Tweet</a></cite>, Robert C. Martin, 23 July 2026</footer> </blockquote> <p> The author of <a href="/ref/clean-code">Clean Code</a> no longer reads code? What implications for software engineering does this suggest? </p> <p> To be clear, how <a href="https://twitter.com/hillelogram/status/1445435617047990273">thought leaders</a> interact with LLMs change so rapidly these days that what someone wrote months ago may no longer apply. And, indeed, Robert C. Martin recently <a href="https://x.com/unclebobmartin/status/2098432570887217520">walked back on his harness use</a>. </p> <p> The point of this article, however, is not to perform an exegesis on Robert C. Martin tweets, but rather to ponder the implications for software engineering. </p> <h3 id="5b34aef318e3492eb56085923dfdb9f7"> Looking at the code was never foolproof <a href="#5b34aef318e3492eb56085923dfdb9f7">#</a> </h3> <p> My first reaction to the notion of not even looking at LLM-generated code was: <em>If you're no longer reading the code, then how do you know whether it's correct?</em> </p> <p> And a second later, I realized that that's just a knee-jerk reaction from an old programmer. I know full well that looking at the code was never foolproof. </p> <p> All programmers make mistakes. We write code thinking it does one thing, but it turns out that it works slightly differently. It may exhibit liminal behaviour where it throws null-reference exceptions, has off-by-one errors, perform overlooked state mutation, or is otherwise just plain wrong. </p> <p> Some <a href="/2020/05/25/wheres-the-science">research</a> seems to indicate that code reviews are one of the more effective methods for catching bugs (see e.g. <a href="/ref/code-complete">Code Complete, 2nd ed</a>, chapter 21). Even so, these techniques don't detect all defects. Some errors slip through, even when subjected to critical and systematic inspection. </p> <p> In other words, humans looking at code is no foolproof software-engineering technique. </p> <h3 id="ef1e62f2055347669ee0740438417caa"> A new notion of software engineering? <a href="#ef1e62f2055347669ee0740438417caa">#</a> </h3> <p> Dave Farley's book <a href="/ref/modern-software-engineering">Modern Software Engineering</a> presents a view of software engineering congruent with <a href="/2025/10/20/epistemology-of-software">my own</a>. Ultimately, software engineering boils down to rapid feedback on <a href="https://en.wikipedia.org/wiki/Falsifiability">falsifiable</a> predictions about the software. </p> <p> Even if we give up the notion of writing and reviewing source code, there are checks we can perform. Some people experiment with 'teams' of agents, each agent having a particular role: You could have one agent write automated tests, another performing code reviews, etc. While I have <a href="/2026/01/26/ai-generated-tests-as-ceremony">previously been sceptical of such seemingly infinite regress</a>, I have recently come to the understanding that our previous, human-centred practices, aren't foolproof either. </p> <p> Even though I believe that <a href="/2025/10/20/epistemology-of-software">test-driven development (TDD) is the most scientific approach to software development that I know of</a>, you can still make mistakes. The most common sort of mistake in TDD is the test(s) that you don't write. Missing test cases leaves the System Under Test underspecified, but you may not even realize it. </p> <p> LLMs seem to produce code, even automated test code, using other heuristics. People who use 'teams' of agents report good results. </p> <p> Ultimately, demanding perfection from LLM-based software engineering sets a bar we human programmers never cleared. Rather, we seem to arrive at the same argument that you often encounter related to self-driving cars: The system doesn't have to be perfect: It just has to be <em>better</em> than the human-centred system. </p> <p> My claim is not that we have already arrived at that state. The point is rather that there seems to be no inherent barrier to a fully LLM-driven process of software engineering. </p> <h3 id="899c925f4b41488d9982c5167d00bfda"> Where does liability fall? <a href="#899c925f4b41488d9982c5167d00bfda">#</a> </h3> <p> You may, then, imagine a fully LLM-driven software release process. Perhaps humans are involved, but not as programmers, and not as code reviewers. Imagine that no-one looks at the code, but rather relies on other quality-assurance techniques to decide whether or not to deploy. Imagine, even, for the sake of argument, that the frequency of defects is lower than any comparable human-driven process. </p> <p> Lower. Not zero. </p> <p> Errors still make it to production. Most of these will probably be of a benign nature: A button's alignment is off. A text is shown in the wrong language. A message arrives twice, or out of order. Perhaps a bit more serious than that: A shopping-basked discount is applied incorrectly. The wrong song plays on your phone. A traffic signal is stuck at red. </p> <p> Benign errors are, in this rough categorization, errors that are somehow rectifiable. Once you've discovered it, you can fix the problem. Perhaps you'll have to apologize to people, or if the discount was miscalculated to the seller's advantage, you may offer the user some kind of compensation. </p> <p> Other kinds of errors will, however, be more serious: You <a href="https://en.wikipedia.org/wiki/Mars_Climate_Orbiter">lose a million-dollar spacecraft</a>. Your car <a href="https://safetyresearch.net/toyota-unintended-acceleration-and-the-big-bowl-of-spaghetti-code/">accelerates when you step on the brakes</a>. You receive a <a href="https://en.wikipedia.org/wiki/Therac-25">deathly radiation overdose because of a race condition</a>. </p> <p> Such errors don't even have to be that bad. It could 'only' be that people miss their flight, are denied the hotel room they already reserved, receive incorrect tax bills, or lose their insurance coverage. </p> <p> When software defects are serious enough, there could be repercussions. Where does the blame land? </p> <h3 id="9da01c9e2db2400792e3195a7c6fed37"> Consequences <a href="#9da01c9e2db2400792e3195a7c6fed37">#</a> </h3> <p> Consider, at first, bugs that 'merely' cost its owners a lot of money. The <a href="https://en.wikipedia.org/wiki/Mars_Climate_Orbiter">Mars Climate Orbiter fiasco</a> falls in that category. No laws were broken. The only problem was that 327.6 million (taxpayer) dollars were wasted. </p> <p> It would be an extraordinary software organization if such an error didn't have consequences for someone. When people were still writing code by typing it into the computer, it was easy to point and exclaim: <em>Dave wrote that code</em>. </p> <p> Not that such simple ways of assigning blame are fair, or even productive, but they do happen. Someone suffers the consequences, even if he or she is only a scapegoat. </p> <p> As long as the problem is mostly internal to the organization, if you're the scapegoat, the worst that may happen is that you're fired. </p> <p> If, on the other hand, the error causes a legal liability, then the software organization responsible may have to go to court. As we have seen in e.g. <a href="https://en.wikipedia.org/wiki/Volkswagen_emissions_scandal">Dieselgate</a>, individual software developers may have to take the fall. Again, whether this is fair, or reflects the actual reality of what happened, is not my point. The point, rather, is that judicial branches around the world are likely to have a view on where responsibility goes that is decoupled from how software is actually produced. </p> <p> - But, your honour, the LLM wrote the bug. </p> <p> - So you say, son, but you signed off on the release, didn't you? </p> <p> - Yes... </p> <p> - I can't send an LLM to prison, but I <em>can</em> sentence you. </p> <p> Any software organization that considers going 'full AI' need to think hard about what that means when it comes to liability. </p> <h3 id="082580676b864e36a2c58a7cca3e1b4d"> People will play the odds <a href="#082580676b864e36a2c58a7cca3e1b4d">#</a> </h3> <p> Let's consider a recent development in a different field to illustrate what I think will happen: In June 2026, the <a href="https://www.fstyr.dk/nyheder/2026/jun/teslas-foererassistentsystem-fsd-supervised-er-foreloebigt-godkendt-i-danmark">Danish traffic authority, Færdselsstyrelsen, approved Tesla FSD</a> (self-drive), with the proviso that the human behind the wheel is ultimately responsible for the car. Drivers are expected to pay attention to traffic, and take the wheel in case a dangerous situation threatens. </p> <p> What I think is going to happen is that drivers will become increasingly inured by the effectiveness of the system. The better it performs, the more drivers will zone out. After a few weeks or months, drivers will be on their phones during most of the ride, paying little to no attention to traffic. It will mostly go well. </p> <p> Then, once in a blue moon, an accident will happen. As Danish law currently works, if the accident involves loss of human life, the driver faces a sentence for involuntary manslaughter. This usually means prison time. </p> <p> It's not going to matter if the 'actual' cause of the accident was a software error. Legally, the responsibility lies elsewhere. Often, the underlying reason is that legislation lags behind technological reality. </p> <p> I think that the same will happen with LLM-driven software engineering. People will play the odds because they look so compelling. </p> <p> How much you invest in safeguards and various quality-assurance technologies may not matter. You could establish the most elaborate system of verification and still be liable for any errors. How do you feel about releasing LLM-generated software? <a href="/2026/03/23/will-you-go-to-prison-for-an-ai">Are you ready to go to prison for an AI</a>? </p> <h3 id="67481017c646464e8caa662faf0d5d72"> Conclusion <a href="#67481017c646464e8caa662faf0d5d72">#</a> </h3> <p> Software engineering may not be what we thought it was. Or, rather, it may not be limited to a particular set of methodologies centred around human programmers and testers. </p> <p> It's conceivable that the future holds fully automated software-engineering processes that are at least as safe as those we currently know. Even so, the human notion of liability and responsibility may not keep up. </p> <p> When things go wrong, will organizations write off the error as nobody's fault? Will courts of justice consider serious defects as essentially another accident? Or will someone have to take the blame? Who will it be, if no-one wrote any code? </p> </div> <hr> This blog is totally free, but if you like it, please consider <a href="https://blog.ploeh.dk/support">supporting it</a>. Mark Seemann https://blog.ploeh.dk/2026/10/12/releasing-ai-generated-software Redesign without fear https://blog.ploeh.dk/2026/10/02/redesign-without-fear/ Fri, 02 Oct 2026 10:58:00 UTC <div id="post"> <p> <em>Avoid merge conflicts with side-by-side changes.</em> </p> <p> Tim Ottinger published a blog post titled <a href="https://agileotter.blogspot.com/2026/09/why-redesign-doesnt-happen-enough.html">Why redesign doesn't happen (enough)</a>. It's a good article that you can read in five minutes, and I recommend that you do. The gist of it is that larger redesigns in established code bases rarely happen because changing too much code in one go risks conflicting with parallel work being done by colleagues. </p> <p> Tim Ottinger argues that this often leads to merge conflicts, which again reflects poorly on the well-meaning programmer who undertook the work of improvement. His final question is </p> <blockquote> <p> "What interventions would defang this fear and allow teams to move the design and architecture forward?" </p> <footer><cite><a href="https://agileotter.blogspot.com/2026/09/why-redesign-doesnt-happen-enough.html">Why redesign doesn't happen (enough)</a></cite>, Tim Ottinger, 2026</footer> </blockquote> <p> One effective method is side-by-side implementation work. </p> <h3 id="b01819bef7af4164b8d57d4988e7c0e7"> Add new APIs rather than changing existing code <a href="#b01819bef7af4164b8d57d4988e7c0e7">#</a> </h3> <p> As I describe in <a href="/2021/06/14/new-book-code-that-fits-in-your-head">Code That Fits in Your Head</a>, you can apply the <a href="https://martinfowler.com/bliki/StranglerFigApplication.html">Strangler Fig</a> pattern at the code level, too. Instead of implementing a a new design (say, a new object model) by making direct changes to the existing code, add the new code side-by-side with the old, problematic code. </p> <p> Once the new design is implemented and works, leave it inert af first, but share it with all coworkers by pushing and integrating it. Since you have only added new files that no-one else uses, there's little risk of merge conflicts. </p> <p> As a second stage of the process, now that the new design is in place, migrate the problematic code one location at a time by replacing it with simple calls to the new API. You can do this with a granularity of your own choice, thereby minimizing the risk of merge conflicts. </p> <h3 id="8de4d6eb802046c18e3f3e7cc0ab2b99"> Making sure that the design is right <a href="#8de4d6eb802046c18e3f3e7cc0ab2b99">#</a> </h3> <p> One reasonable objection to such a plan would be the following. If you implement a new design, but <em>don't use it</em> at first, then how do you know that it works? How do you know that it actually solves the problem you set out to address? </p> <p> After all, even with much forethought, it often turns out that your first design doesn't work when you attempt to use it for its real purpose. This is important feedback, so it seems misguided to attempt a redesign without verifying whether it works in reality. </p> <p> This would be sensible criticism. That's a true problem that you must address. </p> <p> What you can do is to try it out on the problematic code. Actually perform some of the changes where you replace the problematic code with calls to your new design; what I called the second stage of the process. Do this, however, in a separate <a href="https://git-scm.com/">Git</a> branch that you keep on your own machine. </p> <p> Once you have evidence that the new design is right, share that first, but not the 'strangling' commits. You can then later push those extra commits as well, unless the code base has moved so much in the meantime that it's easier to redo the work by moving code over based off of newer snapshots of the repository. </p> <h3 id="44672a682ded4da38f31240d2890fe6a"> Conclusion <a href="#44672a682ded4da38f31240d2890fe6a">#</a> </h3> <p> As I write in <a href="/code-that-fits-in-your-head">Code That Fits in Your Head</a>, making changes to an existing code base is easy if you are a solo developer. When you work in a team, things become more difficult. The good news is that it's a skill that can be learned. Some techniques include patterns like Feature Flag and Strangler Fig, thinking explicitly about versioning, and working deliberately with separating changes of automated tests from changes to the System Under Test. </p> <p> The book has examples and more details. </p> </div><hr> This blog is totally free, but if you like it, please consider <a href="https://blog.ploeh.dk/support">supporting it</a>. Mark Seemann https://blog.ploeh.dk/2026/10/02/redesign-without-fear On learning programming in an age of LLMs https://blog.ploeh.dk/2026/09/16/on-learning-programming-in-an-age-of-llms/ Wed, 16 Sep 2026 05:29:00 UTC <div id="post"> <p> <em>Open answers to a reader's letter.</em> </p> <p> A reader recently wrote me a long letter with lots of questions about learning programming in this age of LLMs. After a bit of back-and-forth, I got permission to quote extensively from the letter in order to attempt some answers in public. </p> <p> None of my answers I consider particularly rigorous; the situation is so uncertain that I can only answer to the best of my abilities, but I don't claim them to hold any kind of immutable truth. </p> <blockquote> <p> "I'm trying to understand how people who deeply understand software think about learning and competence in the age of AI. I'm approaching it almost as a historian would: asking people directly how they make sense of a technological transition while actually living through it. </p> <p> "About a year ago I became fascinated by AI-assisted programming. Despite having no formal CS background, with LLMs I managed to build a fairly large TypeScript/JavaScript system involving APIs, PostgreSQL, LLM pipelines, research automation and multi-model workflows. At first it felt almost magical: AI seemed to collapse the distance between having an idea and being able to build it. </p> <p> "But now I'm trying to turn that system into a real production product, and I'm struggling. I fix one error with AI, then another appears, then another part behaves in a way I don't fully understand. After months of refactoring I had an uncomfortable realization: I may have built a system that is above my own level of understanding. When everything works, that gap is almost invisible. When it doesn't, it becomes very real. </p> <p> "Sometimes I genuinely don't know what to do next without asking another model. That made me wonder whether I spent a year building a product, or partly building the appearance of one: something sophisticated enough to work, but which I don't yet understand deeply enough to truly own. </p> <p> "I'm not anti-AI at all. I'm fascinated by these systems and want to work with them professionally. But I'm unsure what the right relationship with them should be." </p> </blockquote> <p> Indeed, I'm not sure either, but before proceeding, I find it most transparent to reveal my position. I haven't yet decided on AI, but <a href="/2026/05/04/motivated-reasoning">I lean toward disliking it</a>, knowing full well that it may be unstoppable. </p> <p> I do work and experiment with it, and it often impresses me. At other times, it frustrates me. It's usually when it impresses me the most that I resent it maximally. </p> <p> When it's bad, it can be frustrating, but then at least I can absorb an ember of warmth in the illusion that what I've spent more than thirty years learning is still relevant. When it's at its best, I sometimes think: <em>Where do I sign up for <a href="https://dune.fandom.com/wiki/Butlerian_Jihad">the Butlerian jihad</a>?</em> </p> <p> My position on LLMs is only partly based on my own socio-economic status. I'm old enough, and have had enough success already, that all other things being equal, I can survive unemployment. I'm not sure, on the other hand, than any knowledge-based society can. </p> <p> It may be that LLMs will take programmer jobs before they take other white-collar jobs. After all, programming <em>may</em> be a discipline where verification is easier than, say, insurance claims management. Still, if we reach a point of mass unemployment among knowledge workers, I'm not sure society as we know it will survive. </p> <p> I usually don't talk much about my background as an economist, but in this context I find it relevant to mention. As an economist, I can't imagine that mass unemployment of 30-40% will not have a significant impact on the economy. </p> <p> I'm painfully aware of the arguments that this has happened before: There may be job loss, but the advance of technology leads to new jobs we can't even imagine today. It was like that with the introduction of the <a href="https://en.wikipedia.org/wiki/Stocking_frame">stocking frame</a>, the steam engine, the internal combustion engine, computers, etc. This is only partly true: Yes, new jobs were created, but often not for those people who lost their jobs. Coal miners didn't just become programmers overnight. </p> <p> The same kind of argument was used when <a href="https://en.wikipedia.org/wiki/China_shock">China was admitted to the World Trade Organization</a>. And indeed, lots of new jobs were created, just not in the Western world. </p> <p> So, based on lived and historical experience, I'm sceptical of arguments that all will be fine. </p> <p> But I sincerely hope that I'm wrong. I love to program, and wouldn't mind doing it for another ten years. Perhaps more importantly, I have young adult children. I hope that there's a world for them, too. </p> <blockquote> <p> "So I'd really like to know how you think about this. Are you glad you learned programming fundamentals before LLMs existed? If you were starting today, would you still seriously study languages, data structures, databases, networking, operating systems, debugging and architecture? Do you think AI can let people become capable of building much faster than they become capable of understanding?" </p> </blockquote> <p> Am I glad that I learned programming before LLMs? Yes, of course. Those skills served me well for thirty years. </p> <p> If I was starting today, I'd seriously consider learning carpentry, metalworking, gun-smithing, or something else that requires hand-eye coordination. I know that advances are made in robotics, too, but replacement of manual labour seems to lie farther in the future. </p> <p> But to address the question: I am, personally, currently learning data structures, language semantics, etc. as part of a university programme. I do that because I'm curious, however, and not because I expect to get much monetary reward out of it. </p> <p> Do I think that AI enables people to develop faster than they can keep up? This remains to be seen. Software developers have already, for decades, been working on top of abstractions they didn't understand. If you were a web developer, you didn't know much about compiler programming. If you were a compiler programmer, you didn't know much about integrated circuit design. And if your job was to engineer integrated circuits, you wouldn't know much about the levels of abstraction <em>above</em> you. </p> <p> A good rule of thumb was: Understand the level of abstractions directly below the one you work in, as well as the one above. That would enable you to troubleshoot <em>most</em> problems. </p> <blockquote> <p> "And how do you personally deal with that? When AI can solve something immediately, how do you decide when to use it and when to work through the problem yourself? If you were in my position, with a substantial AI-built project but weak foundations underneath it, would you step back and systematically learn those foundations, keep building and learn as problems appear, or combine the two?" </p> </blockquote> <p> That's two radically different questions, because I no longer have a weak foundation in software development. Even if I were dealing with something far from what I usually do, I can ramp up leveraging what I already know. Let's imagine that someone tasked me with maintaining an application written exclusively in <a href="https://riscv.org/">RISC-V</a> assembly code. That's the most alien software environment I can imagine for myself. Adapting to such a development environment would be difficult for me, but still not as difficult as it would be for someone new to programming in general. Believe it or not, I <em>have</em> written small exercise programs in RISC-V, as well as an exercise compiler that compiled to RISC-V. </p> <p> But what if I had virtually no software background? </p> <p> Well, once upon a time, I was in exactly that situation. When I started my career, for years I balanced a knife's edge of getting things done while learning on the job. Beginning in 1999, I wrote COM components in <a href="https://en.wikipedia.org/wiki/C%2B%2B">C++</a>, not understanding much of what I was doing. Somehow, I still made it work, even to a degree that I managed to eliminate any obvious memory leaks. </p> <p> I was, however, never happy just slapping things together without understanding how they worked. So I did, as suggested by the question, step back to systematically learn <a href="/2024/05/20/fundamentals">fundamentals</a>. This worked well for a career launched in the mid 1990s. Will it work well today? </p> <p> I'm not so sure: Reaching a level of competency high enough to recognize your past confidence as clearly lying on the too-ignorant-to-realize-it portion of the <a href="https://en.wikipedia.org/wiki/Dunning%E2%80%93Kruger_effect">Dunning-Kruger</a> curve took decades. Do you have that much time today? </p> <p> Granted, with LLMs, you can learn faster, because you can ask more directed questions. Thirty years ago, I would buy books in the hope that they would contain <em>some</em> helpful material. This still meant slogging through a lot of learning material not immediately relevant to the task at hand. </p> <p> Still, I doubt that it's possible to significantly speed up human learning. The bottleneck is hardly the teachers nor the materials, but how fast a human brain can absorb new knowledge. </p> <blockquote> <p> "One last thing I would be especially grateful to hear about is how you learned programming yourself, and how you learn new technical things today. How did you approach learning a new language earlier in your career? Books, projects, reading other people's code, exercises, debugging, something else? And if you had to learn a completely new programming language today, with AI available, how would you do it?" </p> </blockquote> <p> The short answer to the first question: Slowly, based on much trial and error, occasionally backed by a book. </p> <p> Apart from a very early false start with <a href="https://en.wikipedia.org/wiki/COMAL">COMAL 80</a>, my first programming projects was to (re)calculate <a href="https://en.wikipedia.org/wiki/Bifurcation_diagram">bifurcation diagrams</a> and the <a href="https://en.wikipedia.org/wiki/Lorenz_system">Lorenz attractor</a> for my master's thesis in economics. Reaching for what I had, I wrote them in <a href="https://en.wikipedia.org/wiki/QBasic">QBasic</a>, learning from the samples that shipped with it, as well as occasionally asking a friend. </p> <p> While I'm glossing over many details, in the 1990s and 2000s, I mostly learned from examples and documentation. While I did buy a book about C++, I don't think I ever finished it, and I picked up various Basic dialects as well as C# exclusively from documentation and example code. </p> <p> That said, although I never read a book to learn C#, books were instrumental in teaching me both <a href="https://fsharp.org/">F#</a> and <a href="https://www.haskell.org/">Haskell</a>. I have, over the years, relied heavily on books to educate myself, but as <a href="https://www.goodreads.com/author/show/4383188.Mark_Seemann">my Goodreads profile</a> reveals, I love books in general. </p> <p> How do I learn a completely new programming language today? Again, my experience is useless to someone new to programming in 2026: I've now seen so many programming languages that if I run into a new one, I can usually pick it up from perusing existing code and looking up the few things that aren't immediately clear. </p> <p> But that's presupposing that the language in question is 'normal'. If I had to get back into <a href="https://en.wikipedia.org/wiki/APL_(programming_language)">APL</a>, I'd at least have to find a tutorial. </p> <p> You may have noticed that I don't much use LLMs for learning. <a href="/2026/04/06/the-hailo-effect">LLMs don't hallucinate; they bullshit</a>, and I'm deeply distrustful of anything they tell me. This is not to say that I don't use LLMs, but I tend to ask them questions that yield verifiable answers. <em>Can I make this Haskell expression more succinct?</em> Any useful answer to such a question is a code suggestion that either works, or doesn't work; is shorter, or isn't. That's easy to verify. </p> <p> <em>What should I learn next?</em> does, on the other hand, not yield a verifiable answer. I tend to not to ask such questions of LLMs. </p> <p> In conclusion, you could say that I prefer asking LLMs <a href="https://en.wikipedia.org/wiki/Falsifiability">falsifiable</a> questions. </p> </div><hr> This blog is totally free, but if you like it, please consider <a href="https://blog.ploeh.dk/support">supporting it</a>. Mark Seemann https://blog.ploeh.dk/2026/09/16/on-learning-programming-in-an-age-of-llms