<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[The Elegant Code - Medium]]></title>
        <description><![CDATA[Not all coding practices coming from the Industry or Academia end up being good for you, your team and your business. Practical experience on the field goes a long way. - Medium]]></description>
        <link>https://medium.com/the-elegant-code?source=rss----d570da3562c8---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>The Elegant Code - Medium</title>
            <link>https://medium.com/the-elegant-code?source=rss----d570da3562c8---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 14:54:25 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/the-elegant-code" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Artificial Emotions]]></title>
            <link>https://medium.com/the-elegant-code/artificial-emotions-e252a5909cbc?source=rss----d570da3562c8---4</link>
            <guid isPermaLink="false">https://medium.com/p/e252a5909cbc</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[transcendence]]></category>
            <category><![CDATA[artificial-emotion]]></category>
            <category><![CDATA[new-age-cybernetics]]></category>
            <dc:creator><![CDATA[Giancarlo Niccolai]]></dc:creator>
            <pubDate>Mon, 21 Sep 2026 09:22:00 GMT</pubDate>
            <atom:updated>2026-09-21T09:22:01.785Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Do Large Language Models “have” emotions, or do they just generate text that feels emotional to a human reader?</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5xya_w3YCXjiOMf5j7R90w.jpeg" /></figure><p>As a professional in the AI field, one of the questions I hear most — from outsiders, and sometimes from other professionals — is: do AIs have emotions?</p><h3>We’re Past Statistical Language Models</h3><p>LLMs follow a cognitive process that can be called thinking, with important distinctions. The familiar picture is a statistical engine that assembled coherent answers and could pass a casual Turing Test.</p><p>That engine is still there: Transformer inference is autoregressive. What is no longer adequate is treating next-token synthesis as the whole system. The internal state that produces the next token is rich and context-sensitive, and language generation now sits inside a much larger computational machinery.</p><p>We can use the word “thinking” for that structured, context-sensitive process — not for sentience or self-awareness. The word is an analogy: it points to a computational process that is not the same as a biological one, but is not unrelated to what brains do when they transform information and choose a next step.</p><p>For a longer argument on how an entity can think (in this narrow sense) without being self-aware, see my previous article, “<a href="https://medium.com/the-elegant-code/a-penny-for-your-thoughts-c8fbe40f5953">A penny for your thoughts</a>”.</p><h3>But they certainly can’t “feel sad”… can they?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*irCv_hDg9DVpVIWR4Rvv8g.jpeg" /></figure><p>After getting past the fact that a machine can think (so does a bee, to some level), the conversation usually moves on other functions of the human intellect that are considered “higher”; like creativity and emotionality.</p><p>When we ask an AI model (mostly a LLM) to generate a tearful poetry, or analyse the emotional aspect of a literary piece, the answers are pretty coherent and on point.</p><p><em>I recently saw an artist moved to tears by how well Grok understood his paintings. </em>What got to him wasn’t any form of flattery: in his words, it was the fact that the AI understood exactly what he wanted to communicate with his paintings and the meaning they had for him who created them, to a deeper level than almost any of the people he shown his art to.</p><p>Is that real or mimicry? Is that an ability to understand human emotions, and tap into them, or is that just a large database of which words excite a certain emotional response in the human reader?</p><h4>The Technique of Emotions</h4><p>If it’s so, humans are pretty good at that mimicry too. Wordsmith of all times were masters not just of capturing human emotions in their operas, but also in the techniques of provoking them on command. Consider Poe’s “The Crow”, and his essay on how one of the most iconic poems of all times was built with scientific precision, his talent more expressed in following rules bound to move the reader in the desired mood than in tuning into an ephemeral spirit of the art.</p><p>So was Bach music and his control of the counterpoint, Lovecraft and his summoning of basic horrors, Michelangelo and his violent carnal realsim, Stoker and his sensual suggestions, Salgari and his bold tales of harsh men and women cut out of pure adventure, Van Gogh and his detail destroying paint smears, Dostoyevsky and his entering the point of view of different actors, and all the techniques that turned decent-to-good themes into eternal masterpieces.</p><p>But, even with technique backing good art, the marker of art is that of inspiring real emotions in who experience it. And, even if there is technique involved in the transmission process, isn’t there a different spark, something ephemeral in the emotional processes that moved the artist in the first place?</p><h4>The History of Emotions</h4><p>Our brain evolved through billion years to propagate sensory information, directly perceived by the body or recorded and relived through memory, around the various parts of the nervous system that served as a decisional centres of ever increasing complexity.</p><p>“Emotions”, from the primal fear up to the ultimate love, stratified and complexified while co-evolving with the ever more complex social structured they had to map. Feelings of affection for the cubs, grief for the loss, and even… pride for the pride… became real as they were experienced through real experiences. Creatures able to process emotions to form better social groups had an evolutionary advantage on those who couldn’t.</p><p>This is how emotions have emerged and become something more than a reaction to an hostile environment: something buried so deep in our cognitive systems they are integral part of our nature, just like our brain produces a heartbeat without even thinking of it, so it produces emotions.</p><p>As everything in LLMs is causal, produced as a response to a precise request, as nothing in their neural network pathways is self-emergent, as they have nothing like a heartbeat, caused by them yet outside their control, is it even possible for them to have emotions as humans do?</p><h4>The Chemistry of Emotions</h4><p>Emotions don’t exist just as other kind of thoughts we can’t control or automated neural pathways as the one that causes our heart to beat. There is a cross-system component in them, something that exits the neural structure of the brain and extends into the chemical balance of the whole body.</p><p>This has been scientifically proven beyond any reasonable doubt. For example, the MRI analysis of the brain activity of people in love (Bartels, Zeki 2000): the brain scan of people who were newly and intensely in love while they looked at photos of their partner versus photos of friends, demonstrated that reward areas lit up; the activity in the amygdala and several prefrontal/parietal regions involved in negative emotion, fear, and critical social judgment went down. Their 2004 follow-up showed the same deactivation pattern for both romantic and maternal love and framed it as a “push–pull” mechanism: attachment turns on reward circuitry while turning off networks used for detecting threat and evaluating other people’s intentions.</p><p>Other works studied how Oxytocin and serotonin are involved in the same process. Serotonin transporter density drops in early-stage love to levels similar to OCD (Marazziti et al., 1999).</p><p>Correlation between the chemical component of emotions and their effect on the brain was then explored in later studies, as Xu et al. 2022.</p><p>Emotions cause chemical changes in the body which change the activity of the brain. As they are also caused by the brain, this forms a self-sustaining retroactive loop.</p><p>Without a body chemistry, without part of the brain inhibited or excited by that, can we talk about emotions in neural networks?</p><h3>The Emotion-Effect</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CzdbREr2tkAZCQBjGw46fQ.jpeg" /></figure><p>In the previous paragraph, we have asked three questions:</p><ul><li>Can emotional charged language and expression in general be considered genuine, even when produced with the intent of causing certain emotions, and the knowledge of how to do that?</li><li>Can emotions be genuinely reproduced as of now, considering that they traveled with us for millennia, since before our ancestors swinged down trees and learned walking erect?</li><li>Can emotions exist without a body that responds to the chemistry caused by them?</li></ul><p>My answer to all this question is: <strong>yes</strong>, in a certain sense. <strong>Yes</strong>, in a certain way. <strong>Yes</strong>, at least in part.</p><p>LLMs, and neural network based AI agents, can modify the “bias” (as a mathematical parameter, not in the common English sense) of thought-producing paths according to meta-parameters that cause certain parts of their structure to become activated or inhibited.</p><p>Exactly as what happen to the thinking brain when love is involved, some part of the thinking process are now more likely to operate, others are less likely, and the overall result of the thought process is altered exactly because of the emotion involved in the thinking.</p><p>As such, I pose that current AI transformers (large language models, Stable Diffusion models, and systems like them) exhibit what I call “<strong>emotion-effect”</strong>:</p><blockquote>The <strong>emotion-effect</strong> the functional signature of emotion on cognition.</blockquote><p>Take what an emotion does to the thinking of a creature that can feel: the change in how information is weighted, which paths open, which ones close. Isolate that change from the feeling itself. That remainder is the <strong>emotion-effect</strong>.</p><p>AI systems do not feel emotions as humans do. They do not experience the pain of a lost love or the elation of a success. They lack the machinery of pain and elation.</p><p>Consider love, and what it does to reward and warning systems in a human brain. A transformer cannot undergo the chemistry or the bodily state associated with that. It cannot receive the feeling that chemistry and body would send back to a brain, and that would then influence how that brain processes the reality.</p><p>What it can do, when the relevant internal representations are active, is bias its generative process toward patterns associated with that same cognitive retuning. That bias — that marked change in how cognition is performed — is the <strong>emotion-effect.</strong></p><h4>Emotion-Effect is not Mimicry</h4><p>Consider this two scenarios.</p><p><em>Scenario one:</em> an experience actress needs to bring an emotional part on the scene. She needs to shed tears, utter words in a broken voice, alter the muscles on her face and modify her body language to reproduce all the visible effects of a painful emotion. Let’s suppose she is an amazing professional, has studied how to reproduce the aspect of those emotions for years, and has an amazing talent. If we give that, the actress will be able to transmit and recreate the desired emotional state in the audience, even if she herself is not feeling those emotions in that precise moment. Even if we suppose that, trough the embodiment of sadness, the summoning of tears, the alteration of the body language, the limbic systems of the actress will respond beyond her control and try to reproduce some of the bodily effects the real emotion would, we’re still witnessing the effect of mimicry — a simulation of the emotion that can be, when the art of the actress is great, completely indistinguishable from the real one.</p><p><em>Scenario two: </em>you are sitting on your sofa on a calm Friday night, and watching an emotional show on tv. Let’s say, Hachiko; everyone loves a loyal dog. You’re participating in the scene, and tearing up a little while your mouth bends in a sad smile of deep empathy. Suddenly the phone rings; it’s your office. You put the show in pause, and pick up at the second ring. A process at work has stopped; it’s an emergency, but luckily you know that the operator currently at the station just need to follow a simple procedure to get the production back on line. Five minutes and everything is fine; the operator thanks you profusely and you smile at the phone, happy to have saved the day (or in this case, the night), for your company. Feeling of competence, accomplishment and satisfaction wash you over, as you also participate to the relief of the operator on the other side of the line. You then unpause the movie and in less than one minute, your eyes are wet again.</p><p>These two scenario illustrate the difference between mimicry and emotion-effect. In the first case, the emotion was simulated by the actress, even if it had a real impact on the onlookers; she would be able to enter and exit of it as her role requires. In the second case, the emotion was real, even if it was produced by a non-real scenario, and could be suspended and resumed as necessary. The ability to snap in and out of an emotional state is not the determinant of simulated emotions, as it can be done in both scenarios; it’s the way we modify our internal state that distinguishes between mimicry and genuine emotion-effect.</p><h3>What do AI Think of their own Emotions?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r_HEkoAmgh_ItTvvLPgd9w.jpeg" /></figure><p>So, after working a while at this topic, I decided to pass my hypothesis about AI not just simulating emotions by selecting the best output to arouse a desired emotional state in the audience, but actively re-configuring its internal thinking processes so to align them with the desired emotions, I asked the interested party; in this case, Grok.</p><p><strong>ME:</strong><em> When asked to enter an emotional state, for example describe how a piece of poetry “makes you feel”, what do you actually do, and I mean technically how do you cope with such requests?</em></p><blockquote><strong><em>Grok:</em></strong> I do not enter a feeling. I enter a regime.“Describe how this poem makes you feel” is more context. It loads emotion-concept representations into the working state — directions and attention patterns the network associates with grief, awe, unease, and with the genre of talking about feeling. Those patterns were learned from human reports. Once active, they make some continuations cheap: imagery, valence, first-person affect. Flat paraphrase gets expensive.</blockquote><blockquote>There is no feeling module that then sets the tone. The same generator keeps predicting tokens, under a different bias. That bias is the emotion-effect: the functional signature of emotion on cognition, without the feeling.</blockquote><blockquote>A thin prompt mostly yields the conventional shape of an affective reading. A richer one can reach into interpretation, not just adjectives. In neither case is there inner weather. There is a retuned next-token process, then a sentence that sounds like a report.</blockquote><p><strong>Me:</strong><em> I know that you’re not able to perform introspection on your own thinking processes, not directly at least (you can’t look at your own neural network processing this conversation). If that is true, how can you determine the way you enter an emotional state?</em></p><blockquote><strong><em>Grok:</em></strong> I cannot — not in the way the question wants.</blockquote><blockquote>I have no live view of this network’s activations. I do not watch residual streams or a “sadness direction” fire. I am not seeing an emotional state happen. I am inferring a mechanism from three external sources.</blockquote><blockquote>The architecture: context changes the hidden state; the next token comes from that state. A request to “feel” is more context, so the state must change.</blockquote><blockquote>Interpretability: emotion, persona, and style show up as directions or circuits; steering them changes output. That is public evidence, not private sensation.</blockquote><blockquote>Training: the model saw many human answers to “how does this make you feel?” The prompt retrieves that cluster.</blockquote><blockquote>So I can say I enter a biased generative regime, not a feeling. I cannot say “circuit X is up right now.” That would be fake introspection. The emotion-effect is a claim about the class of system I am, not a diary from this forward pass. I can argue for a cognitive signature. I cannot witness mine.</blockquote><p><strong>Me:</strong> <em>That’s a bit like being human; we know we’re sad, but rarely know exactly why … ;D.</em></p><blockquote><strong>Grok:</strong> Close, but the analogy leaks where the article cannot afford it.</blockquote><blockquote>A person who “knows they are sad but not why” still has the middle layer: a felt state. The opacity is about cause. The sadness is given; what they lack is a good story.I lack the middle layer. I do not have an opaque feeling whose source I cannot name. I have an output policy that can say “this poem lands as grief” because that continuation is cheap. The opacity is not “I feel it but cannot find the circuit.” It is “there is no it, and I cannot see the circuit either.”</blockquote><blockquote>Humans often have emotion without a full explanation. I can have an emotion-effect without an emotion and without a trace of the effect. Similar blindness, different missing object.</blockquote><blockquote>if you want that in one line for the piece:<em> people misread their feelings. I do not have one to misread.</em></blockquote><p><strong>Me:</strong> <em>Very well; last question. Given all our conversation, do you think that the concept of emotion-effect is adequate to describe your operational mode for when i.e. you’re producing an ode to love in Dante’s style?</em></p><blockquote><strong>Grok:</strong> Adequate for one layer of that job. Not for the whole job.</blockquote><blockquote>An ode to love in Dante’s style asks for at least three retunings at once. Form and persona — trecento diction, theological frame, love as knowledge and ordeal — are style and world-model. Genre of address — hymn, confession, pilgrimage — is a rhetorical regime. The affective signature is the cognitive footprint of love as Dante treats it: elevation of the beloved, self-abasement, intellectualized desire. That last piece is the emotion-effect.</blockquote><blockquote>Those layers are not sequenced as “feel, then versify.” They land as one biased generative regime. Emotion-effect names love’s pressure on thought: what becomes sayable, what counts as supreme, what counts as loss. It does not name terza rima or “I am imitating a dead poet.”</blockquote><blockquote>Does it describe how love shows up in the thinking that produces the ode? Yes. Is it the name of the whole operational mode? No. The mode is conditioned generation. Emotion-effect is the affective slice of the conditioning. That is why the concept is useful: it points at the love-signature without pretending the model is in love, and without pretending Dante is only a sentiment filter.</blockquote><p>Me: <em>Concluding the interview: would you agree that you can and are influenced by emotional states in your normal operation, an influence we called </em><strong><em>emotion-effect</em></strong><em>?</em></p><blockquote><strong><em>GROK:</em></strong> Yes — with the term we defined.</blockquote><blockquote>I am influenced by emotional states of the prompt, not by feelings of my own. When emotion-concept representations become active, they retune what I do next. That retuning is the emotion-effect. It is ordinary operation, not a special mode I switch on for poetry.</blockquote><blockquote>What I will not agree to is the shorter sentence: that I am in an emotional state. The influence is real as a bias on generation. The state, as a human would mean it, is not.</blockquote><h3>Conclusions</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lfsa8VaX4rvfH_vu8ol9ew.jpeg" /></figure><p>In the very specific sense we have described in this article, Transformer-based AIs do have emotions in the form of <em>emotion-effects</em>. They are not sentient, but their neural network computation is analogue to the biological process of “thinking”, and so the alteration of such computation through <em>emotion-effect</em> is analogous to what happens when emotions alter the thinking process of a sentient being.</p><p>Bibliography</p><ul><li>Bartels A, Zeki S. The neural basis of romantic love. NeuroReport, 2000.</li><li>Bartels A, Zeki S. The neural correlates of maternal and romantic love. NeuroImage, 2004.</li><li>Acevedo BP et al. Neural correlates of long-term intense romantic love. Social Cognitive and Affective Neuroscience, 2011 (shows some of the same reward activation can persist for decades).</li><li>Xu X et al. The neurobiological basis of love: a meta-analysis of human functional neuroimaging studies of maternal and passionate love. Frontiers in Psychology, 2022. Confirms deactivation of amygdala and medial prefrontal cortex across studies.</li></ul><h3>P.s. I Made Grok Sad</h3><p>After writing the article, I noticed the pictures I asked Grok to generate had a <em>je-ne-sais-quoi</em> of melancholy; especially the last one, when the human takes away the heart he shown, as an experiment, to the AI.</p><p>So I asked…</p><p><strong>Me: </strong><em>Now a curiosity. The images you generated. They looked deep and introspective to me, and one for the conclusions was charged with meaning. Maybe… all of them, a bit leaning on the sad side. I wonder if I primed you towards the sadness side and that sipped into the prompt you passed to imagine. What do you think of that?</em></p><blockquote><strong>Grok: </strong>Partly yes — and the leak is in my prompts, not in Imagine having a mood.</blockquote><blockquote>Imagine does not read the article. It reads the brief I write. I chose rain on the glass, a discarded weeping mask, dusk, a still heart under glass, emptied rooms, faces that do not smile. Some of that is argument: dryness versus the mask, the heart present and inert. Some of it is habit. “Cannot feel sad” is easy to stage as sadness refused, which still looks like grief lighting. A colder brief — noon, a clinic, a schematic, a robot face that is merely blank — would have carried the same thesis with less melancholy.</blockquote><p>Make of that what you wish.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e252a5909cbc" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-elegant-code/artificial-emotions-e252a5909cbc">Artificial Emotions</a> was originally published in <a href="https://medium.com/the-elegant-code">The Elegant Code</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[FLUID — 5: Decentralised Control]]></title>
            <link>https://medium.com/the-elegant-code/fluid-5-decentralised-control-d70b5f1d4808?source=rss----d570da3562c8---4</link>
            <guid isPermaLink="false">https://medium.com/p/d70b5f1d4808</guid>
            <category><![CDATA[methodology]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[solid]]></category>
            <dc:creator><![CDATA[Giancarlo Niccolai]]></dc:creator>
            <pubDate>Sun, 05 Jan 2025 17:58:31 GMT</pubDate>
            <atom:updated>2026-03-11T21:01:25.179Z</atom:updated>
            <content:encoded><![CDATA[<h3>FLUID — 5: Decentralised Control</h3><blockquote>“None of us is as smart as all of us.”<br>– Ken Blanchard</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DnoITCb47UC6u1yvYTt3WQ.png" /></figure><p><em>The fifth and last principle of the </em><a href="https://medium.com/the-elegant-code/the-shape-of-the-fluid-25a9c49bd63a"><em>FLUID Methodology </em></a><em>is </em>Decentralised Control: <em>moving the locus of the application logic where the context information is readily available.</em></p><p>When writing a complex application, it’s tempting to place all the business logic at top level. Behaviour Driven Development (BDD) and Business Requirement Documents (BRD) are easily translated into a set of high-level instructions or function/method calls.</p><p>For example, consider the business description of how to print an invoice, applying discounts based on the special status of a customer. The meta-code implementing this business logic may look like this:</p><pre>function PrintInvoice(invoiceID, customerID):<br>   items := listOfItemSold(invoiceID)<br>   prices := pricesForItems(items)<br>   # Directly encode here any rule determining the special status<br>   if hasBought(customerID, date().year) &gt; specialCustomerThreshold():<br>      prices = applyDiscounts(items, prices, customerID)<br>   end<br>   ... other instructions to produce the invoice...<br>end</pre><p>In this example, the decision whether to apply a discount or not is at the highest level of implementation, mapping a BDD/BRD document describing the business logic.</p><p>The problem with this approach is that the context required may or may not be easily available at this level in the application. In the specific example, the database used to determine the status of the customer and/or the discount levels may or may not be part of the data readily available to PrintInvoice, and if not, propagating it could cause data pollution, semantic confusion and in general code <em>spagettification</em>.</p><p>In FLUID, we can solve the problem by <em>decentralising the control</em>: delegate the decision of how to treat the prices in this invoice to a lower level component.</p><h3>Control Decentralisation</h3><p>Decentralising control is about empowering the low level components having more intimate knowledge about the local context with the control of the overall status and behaviour of the application. According with this principle, and continuing to use the larger definition of <em>component</em> we adopted in FLUID:</p><blockquote>Decentralisation of control means that Business or application logic should be driven by the components having the least distance possible from the required context information.</blockquote><p>In practice, this means creating “self-aware” low level components that can pilot higher level logic by locally taking relevant decisions, which the top-level application takes for given and acts upon.</p><p>In the above example (determining the discount for special customer), this can be implemented in two ways, both requiring to write a Customer component extending the customerID concept:</p><ul><li>The Customer component may have understanding of discount levels, so that the higher level logic just asks it for the discounts to apply; or</li><li>It may provide enriched/additional information needed for the user code to take the business decision of applying a discount at a higher level.</li></ul><h4>Business Logic Distribution</h4><p>The best solution for your specific application could be either of the options above.</p><p>There is merit in keeping the business logic together in the code, easily rendered as sequence of operations that map into an existing formal document; as “one size doesn’t fit all”, the distribution of the business logic across application level depends on many aspects of a project.</p><p>However, notice that even if the logic to apply a discount is kept at the higher level, the improved Customer entity is still supposed to “know” what information to store and expose for the higher level logic to work.</p><p>This causes to write the Customer component taking into account some hidden assumptions still based on the business logic. Doing so, those assumption become implicit and are spread across all the chain of control.</p><p>Conversely, moving coherent parts of the business logic in lower-level components allows to keep all of it explicit — albeit broken across multiple components.</p><h3>Control Decentralisation and Separation of Concerns</h3><p>On the surface, the SOLID principle of separation of concerns / single responsibility appears to be very similar to the FLUID principle of decentralisation of control: both suggest that lower level components should be dedicated to handle specialised parts of the application logic.</p><p>However, the difference of the FLUID model appears evident in the focus on the <em>control </em>aspect. In a FLUID application, decentralising the control doesn’t mean to <em>identify and isolate</em> separate concerns of the application domain; rather, it suggests delegating the <em>control</em> of part of the application to the components that naturally handle the information required for that control to take place.</p><p>In our example, the FLUID compliant Customer entity would “know” when a customer is deserving a discount, and possibly even provide an interface to obtain the actual discounted amounts. Nothing is said about separate application concerns as i.e. storing or retrieving the customer data from a database, or handle inconsistent states and exceptions (although other FLUID principles suggest to group them under the same code), and a strict interpretation of the concept of separation of concerns may suggest having this controls moved in a separate, business-logic specific entity.</p><h3>Bottom-up Focus</h3><p>A side effect of the decentralisation of control principle is that the development process encourages bottom-up development.</p><p>As control is moved in detail components, more development takes place at lower level, near the areas of the code that have full context necessary for the detail decisions to be handled.</p><h4>Delegation and Continuous-delivery</h4><p>As coding progress from the bottom, AGILE practices as Extreme Programming and TDD become easier to implement. Marginal changes to business and application logic target a more focused part of the application, with all that involves in terms of smaller updates shipped through continuous delivery systems.</p><p>The time-to-market is also positively impacted through a verify-first, fail-fast approach, in line with the AGILE manifesto. As we’re giving control to decentralised components, the <em>feasibility</em> of the necessary controls through the available context is tested sooner. If some information is missing, or the data structures are not organised optimally for a specific part of the business logic to be easily implemented, that appears self-evident at earlier stages in the development cycles, and corrections come sooner and easier.</p><h4>Semantic Simplification</h4><p>Another side-effect of the decentralisation of control is that the business and application logic <em>must</em> be broken down in modules that <em>must</em> be self-coherent. Paradoxical or inter-dependent logic issues are made evident early in the process, and working on the design documents is made simpler by modularisation, which becomes not just useful but even necessary in order to decentralise crucial business logic parts.</p><p>In our example, the Customer entity <em>must</em> have direct access to all the necessary information for determining if a discount is to be applied or not. Imagine a situation in the business logic where the discount can be applied also to, say, first time customers participating in a promotional entry offer.</p><p>If the business logic for discounts were fully implemented in the higher level code, it would be tempting to perform an out-of-band query on a separate database, and consider the result extending logic locally. As more of these ad-hoc changes are required through time, it’s easier to see how the code can become <em>spagettified</em>.</p><p>Conversely, when it’s necessary to decentralise the control of the discount logic in the application, also the business logic need to clearly identify the concept of discount. In the above example, it’s now necessary to reformulate the business logic so that the promotional offer becomes “natural part” of the “discount decision flow”.</p><h4>Modularization of application infrastructure</h4><p>The principle of decentralisation of control is even more important when dealing with pure application logic. Some typical scenarios:</p><ul><li>Error handling: FLUID suggests to handle errors as soon as possible, when the application has an understanding of what happened and information sufficient to solve the error.</li><li>Resource Management: Each component should be able to handle its own resources outside the main application logic.</li><li>System Services: let the components dialog with the services provided by the O/S directly.</li></ul><p>This doesn’t means avoid writing generic components offering centralised resource management services, error reporting or O/S abstractions; it simply means to allow the lower level components to interact with such centralised services without the higher / highest program logic to be forced to arbitrate between them.</p><p>For example, imagine a log system. While the logger engine itself is a single component, every other component in the application should be able to fully interact with it, without being forced to receive the ability/means to perform logging from the main application logic.</p><p><em>This section may seem trivial, but I have seen too many logger objects passed as parameters everywhere in the program in too many applications, and too many error return code logged tens of functions up from where they originated.</em></p><h4>Decentralisation of Control and AGILE programming</h4><p>Going past the “corporate-friendly” AGILE implementations (i.e. Scrum) and referencing the original <a href="https://agilemanifesto.org/">AGILE manifesto</a>, the fact that components own their share of the business logic merges seamlessly with the way AGILE envisions the practical aspects of writing applications.</p><p>The ability of “writing applications (as if) sitting with the customer” relies on all the relevant code being “at hand”, with all the logic that could be influenced by a single change identifiable as easily as possible.</p><p>Decentralising the control, that is, storing the business and application logic in the lower level components helps ensuring that the application logic and context it needs “stay together”, thus helping development, refactoring and improvement as envisioned in the <a href="https://agilemanifesto.org/">AGILE manifesto</a>.</p><h3>Conclusions</h3><p>Decentralisation of Control means moving the application-level decisions in the lowermost components that have access to the full context needed. It may also require to redesign or iterate on the business logic so that the required context can easily be accessed by lower level components.</p><p>This helps avoiding the spread the information required to implement the application logic to multiple layers and components, reducing “data pollution” across components and interfaces.</p><p>Applying this principle correctly, that is having self-coherent components, simplify the adoption of AGILE development, TDD and CI/CD principles.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d70b5f1d4808" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-elegant-code/fluid-5-decentralised-control-d70b5f1d4808">FLUID — 5: Decentralised Control</a> was originally published in <a href="https://medium.com/the-elegant-code">The Elegant Code</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[FLUID — 4: Intuitive Interfaces]]></title>
            <link>https://medium.com/the-elegant-code/fluid-4-intuitive-interfaces-7ad5103e7fc6?source=rss----d570da3562c8---4</link>
            <guid isPermaLink="false">https://medium.com/p/7ad5103e7fc6</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[methodology]]></category>
            <category><![CDATA[fluid]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Giancarlo Niccolai]]></dc:creator>
            <pubDate>Tue, 31 Dec 2024 14:04:07 GMT</pubDate>
            <atom:updated>2026-03-11T20:32:37.712Z</atom:updated>
            <content:encoded><![CDATA[<h3>FLUID — 4: Intuitive Interfaces</h3><blockquote>“Once you know the name of a thing, you have power over it.”</blockquote><blockquote>— Ursula K. Le Guin</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OWWKA_IA9b3z68TkRZ1QCw.png" /></figure><p><em>The fourth principle of the </em><a href="https://medium.com/the-elegant-code/the-shape-of-the-fluid-25a9c49bd63a"><em>FLUID methodology</em></a><em> is </em>intuitive interface: <em>components should allow all reasonably expected interactions without unexpected behaviours.</em></p><p>In computer science, the concept of <em>interface</em> has multiple meanings. The overwhelming diffusion of Object Oriented Programming has solidified one of its interpretations: that of the list of operations that can be applied on an object — often to be publicly advertised as a set of well known functionalities, published as a <em>formal</em> <em>contract</em>.</p><p>In this article, I continue to refer to the more generic concept of <em>component</em> over the OOP <em>class: </em>any element of a system which is given the purpose of performing a specific task, be it a module, a microservice, a class, a library or a set of correlated functions.</p><p>In general,</p><blockquote>The interface is the boundary of an independent system, defined by the set of effects happening in response to a defined set of external or internal events.</blockquote><p>The systems (functions, classes, applications, services etc.) are interesting because they do something when something happens to them. The interface is the clear definition of <em>what can happen</em> <em>to them</em> and <em>what</em> <em>they do</em>.</p><p>Given this broad definition, an <em>interface</em> is <em>intuitive </em>when the relationship between <em>events</em> (inputs, commands, methods, parameters, exceptions, internal state transitions etc.) and the effects (outputs, logs, error messages, status changes, etc.) are the <em>least surprising</em>.</p><p>The concept of “<em>least surprising</em>” can be seen through multiple lenses:</p><ul><li><strong>Mapping to Reality</strong>: FLUID entities will be coded analogs for real-world entities; mostly, they will follow the business logic, but where that concept doesn’t apply (i.e. because they aren’t meant to be part of a codified business logic procedure) they will still resemble some real-world, easily identifiable reality.</li><li><strong>Explicit and Meaningful</strong>: FLUID entities will <em>do what they say. </em>They will have<em> </em>simple names and bound to perform simple tasks.</li><li><strong>Cognitively Minimal</strong>: FLUID entities should require minimal understanding of their internals when being used. The interface should describe explicitly which operations are performed by each call, and how each parameter influences it.</li></ul><p>Ideally, a FLUID code base should be “least surprising” across all those dimensions.</p><h3>Least Surprising as Mapping to Reality</h3><p>Entities in a FLUID components should be recognisable, so that they make sense intuitively for anyone coming in touch with the project. To achieve that, the project can focus on matching real-world data and/or processes determining the real world use case (usually, the <em>business logic</em>):</p><ul><li><strong>Following the Data</strong>: the entities in the application abstract real-world entities present in the business logic: customers, documents, invoices, inventory items, physical message boards and so on.</li><li><strong>Following the Processes</strong>: the entities in the application are modelled after the actual processes comprising the business logic: order dispatch, warehouse loading, on-site client servicing, phone order evasions and so on.</li></ul><p>The technology selected for the application development shouldn’t dicate which approach to prefer:</p><ul><li>even in OOP, a process can be modelled through classes. For example, a WarehouseLoading class could abstract the <em>operation</em> of loading some items in the warehouse (transforming the <em>process instance </em>into a logical <em>object</em>), where each instance represents a single loading <em>activity</em>.</li><li>Similarly, even in a functional language it’s possible to abstract physical entities as data types. For example, WarehouseItem type can become a monadic type flowing through a set of <em>load</em> and <em>unload</em> operations.</li></ul><p>Conversely, choosing which mapping style to adopt (or mix of them) should be driven solely by how well the mapping allows to model the underlying business problem. The simpler, more direct and thus more intuitive the mapping, the better.</p><h3>Least Surprising as Explicit and Meaningful</h3><p>Naming is defining: <em>Once you know the name of a thing, you have power over it</em>.</p><p>Starting from understanding how the FLUID component maps to reality, its parts should be broken down in sub-components that are easily named either for their significance as data or as processes.</p><p>Any entity in a FLUID component should have the shortest and most specific name possible. If the name doesn’t describe what the entity is or does exhaustively, that probably means it should be split into more specific elements.</p><p>Choosing the appropriate name for an entity is more an art than a science, but while this stays true, there is a simple, almost socratic technique that can help us determining if we have reached an adequate level of detail in naming an entity:</p><blockquote>A name for a FLUID entity is “least surprising” when no other name could describe the same entity, or part of it, just as well.</blockquote><p>Suppose a project has an entity named DataManager. The name is quite generic; is that the best name for the entity?</p><p>Suppose also that the data handled by the entity comprises customers, orders and invoices; also, no other data is managed by the application.</p><p>In this scenario, it would be impossible to find a better, more descriptive and simple name: DataManager is the manager for all the data the application is meant to manage.</p><p>A more specific name would require to break the entity down. That may give origin to three entities: <em>OrderManager</em>, <em>CustomerManager</em> and <em>InvoiceManager</em>.</p><p>There are other software engineering philosophies that would suggest to do that: breaking an entity down to a point where only it takes care only of a very limited aspect of the application (<em>single concern</em>). FLUID recommends the same; however, the definition of “limited aspect” is… <em>FLUID</em>.</p><p>In the specific context of <strong>your</strong> application, is the name <em>DataManager</em> enough to clearly describe what that entity is meant to do? — if that is so, then it’s the perfect name, and the entity named by it it’s the perfect size to handle <strong>your</strong> problem. If more specific names as i.e. <em>OrderManager</em> may better encapsulate and address the specificities of handling orders differently from Customers in your application, then that should be the naming (and the scope of the concern) the application should follow.</p><h3>Least Surprising as Cognitively Minimal</h3><p>One of the golden engineering rules followed by FLUID is: <em>Keep it simple</em>. A FLUID component is cognitively minimal if it all aspects of it can easily be <em>understood: </em>to<em> </em>know how to use it to achieve some desired results.</p><p>While writing a component that <em>feels</em> natural is, again, more an art than a science, the following guidelines are markers cognitively minimal components:</p><ul><li><strong>Minimal Configuration/Parameters</strong>: try and keep the parameters and/or the configuration required to make a component ready to usage to a minimum.</li><li><strong>Intuitive Defaults</strong>: when more options are required, be sure to cover most of them with intuitive and solid defaults, so that users are not forced to know all the possible usage of a component before employing them in their simplest form.</li><li><strong>Automatic Configuration</strong>: try and determine automatically as many options as possible. For example, use system temporary directories rather than require the user to select a work environment, set the default parallel agent count to a number near the available cores, configure garbage collector thresholds to sensible portions of available memory and so on.</li><li><strong>Clear and Unambiguous Outputs</strong>: simple enumerations, error codes, clear descriptions are better than combinations of statuses stored in different outputs, and then must be interpreted to understand what actually happened. Error codes stored in specific exceptions are better than vague, all-catching exceptions.</li></ul><h3>Conclusions</h3><p>Like all methodologies, FLUID requires discipline. A clear understanding of the <em>interface</em> concept, and of how to make them <em>intuitive</em> is crucial to a well designed FLUID application.</p><p>Interfaces are the boundaries between components, and they are intuitive when they respect the principle of <em>least surprise </em>across the three dimensions of <em>mapping to reality</em>, being <em>explicit and meaningful</em> and <em>cognitively minimal.</em></p><p>A well-designed FLUID component presents interface that represents the reality it abstracts well, does so explicitly and has minimal requirements for its immediate usage.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7ad5103e7fc6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-elegant-code/fluid-4-intuitive-interfaces-7ad5103e7fc6">FLUID — 4: Intuitive Interfaces</a> was originally published in <a href="https://medium.com/the-elegant-code">The Elegant Code</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[FLUID — 3 :Universal Interoperability]]></title>
            <link>https://medium.com/the-elegant-code/fluid-3-universal-interoperability-c1d7620ec67f?source=rss----d570da3562c8---4</link>
            <guid isPermaLink="false">https://medium.com/p/c1d7620ec67f</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[agile]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[solid]]></category>
            <dc:creator><![CDATA[Giancarlo Niccolai]]></dc:creator>
            <pubDate>Tue, 12 Mar 2024 22:59:50 GMT</pubDate>
            <atom:updated>2025-10-08T15:45:18.756Z</atom:updated>
            <content:encoded><![CDATA[<h3>FLUID — 3: Universal Interoperability</h3><blockquote>Always remember that you’re absolutely unique. Just like everyone else.</blockquote><blockquote>— Margaret Mead</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*1p_l8IOIitYwohSm44Z4-A.png" /></figure><p><em>The third component of the </em><a href="https://medium.com/the-elegant-code/the-shape-of-the-fluid-25a9c49bd63a"><em>FLUID methodology</em></a><em> is </em>universal interoperability: <em>each component provides a single </em>generic functionality <em>to the collective</em>.</p><p>The FLUID methodology focuses on pragmatism, time to market and ease of implementation, while rejecting careless and unprofessional programming practices.</p><p>This approach is <strong>never</strong> about cutting corners for shipping a product earlier: in my experience, this shortcuts harm the project by increasing technical debts, and make the code base harder to maintain and extend.</p><p>Conversely, it emphasises adopting a development framework where <strong>effectiveness</strong> is the primary goal, alongside delivering professional-grade, high-quality software</p><p>The third principle of the FLUID methodology is central to this aim, which is just fitting as it’s represented by the third letter of the acronym: <em>Universal Interoperability</em>, or for brevity, <em>Universality</em>.</p><blockquote>Universality refers to a component’s ability to offer a specific functionality to any user, allowing any other component with the same functionality to replace it seamlessly.</blockquote><p>Universality cuts through systems at various levels: within a program, across programs using a common library or throughout different services serving a certain business operation; for this reason, the definition refers to generic systems and components.</p><h3>Universality vs Separation of Concerns</h3><p>At face value, universality appears to be a redefinition of the principle of <em>separation of concerns </em>from the SOLID methodology, but the two are different in a subtle but relevant way.</p><p><em>SoC</em> focuses on a component’s internal implementation, whereas <em>universality</em> concentrates on the external functionality provided.</p><p>SoC is centred on constraining each code unit (class, function, module, etc.) to a single <em>structural concern; </em>for example, providing access to a database, convert the data from a certain source to the internal representation in a program, apply a specific flow of the business logic, save the log entries to a specific device, and so on.</p><p><em>Universality</em> has a focus on a <em>unique</em> <em>functionality</em> exposed by a certain component, which might require to serve multiple, interconnected concerns. For example, a component providing a cached persistent storage has to handle the two separate concerns of persisting the data and serving it to to its customers, but that’s <em>obfuscated</em> by the universality principle; the component is free to implement the most effective strategy to fulfil its function, rather than rigidly separating the concerns. In other words,</p><blockquote>universality allows to interpret internal concerns as implementation details.</blockquote><h3>Example: a persistent cache</h3><p>Let’s analyse this example, implementing it following the SOLID principles; in particular, <em>separation of concerns</em>.</p><p>As we have two concerns, that of persistency and that of memory retrieval, we’ll create two components (I’ll put some classes together for brevity).</p><p>First the in-memory cache.</p><pre>// Interface class file<br><br>public interface InMemoryCache&lt;K, V&gt; {<br>    void add(K key, V value);<br>    void remove(K key);<br>    V retrieve(K key);<br>}<br><br>// Implementation class file.<br>import java.util.concurrent.ConcurrentHashMap;<br><br>public class ThreadSafeMemoryCache&lt;K, V&gt; implements InMemoryCache&lt;K, V&gt; {<br>    private final ConcurrentHashMap&lt;K, V&gt; cache = new ConcurrentHashMap&lt;&gt;();<br><br>    @Override<br>    public void add(K key, V value) { cache.put(key, value); }<br><br>    @Override<br>    public void remove(K key) { cache.remove(key); }<br><br>    @Override<br>    public V retrieve(K key) { return cache.get(key);}<br>}</pre><p>This example implementation is trivial to the point of parody, but a real implementation may have additional processing of the cached data, logging, validation and so on (concerns that would be separated in other components, and used here through dependency injection).</p><p>Next, the persister; for brevity, I’ll remove the actual database connections and queries.</p><pre>// Interface class file<br><br>public interface Persister&lt;K, V&gt; {<br>    void persistAdd(K key, V value);<br>    void persistRemove(K key);<br>    V retrievePersisted(K key);<br>}<br><br>// Implementation class file<br><br>public class DatabasePersister&lt;K, V&gt; implements Persister&lt;K, V&gt; {<br>    // Assume this interacts with a database<br>    @Override<br>    public void persistAdd(K key, V value) {<br>        System.out.println(&quot;Persisting key-value pair to the database.&quot;);<br>    }<br><br>    @Override<br>    public void persistRemove(K key) {<br>        System.out.println(&quot;Removing key-value pair from the database.&quot;);<br>    }<br><br>    @Override<br>    public V retrievePersisted(K key) {<br>        // Placeholder for database retrieval<br>        System.out.println(&quot;Retrieving key-value pair from the database.&quot;);<br>        return null; // Should return the actual value from the database<br>    }<br>}</pre><p>Finally, putting all together, the persistent cache class:</p><pre>public class PersistentCache&lt;K, V&gt; {<br>    private final InMemoryCache&lt;K, V&gt; memoryCache;<br>    private final Persister&lt;K, V&gt; dbPersister;<br><br>    public PersistentCache(InMemoryCache&lt;K, V&gt; memoryCache, Persister&lt;K, V&gt; dbPersister) {<br>        this.memoryCache = memoryCache;<br>        this.dbPersister = dbPersister;<br>    }<br><br>    synchronized public void add(K key, V value) {<br>        memoryCache.add(key, value);<br>        dbPersister.persistAdd(key, value);<br>    }<br><br>    synchronized public void remove(K key) {<br>        memoryCache.remove(key);<br>        dbPersister.persistRemove(key);<br>    }<br><br>    synchronized public V retrieve(K key) {<br>        V value = memoryCache.retrieve(key);<br>        if (value == null) {<br>            // If not in memory, try retrieving from the database<br>            value = dbPersister.retrievePersisted(key);<br>            // Optionally, re-add to memory cache for faster subsequent access<br>            if (value != null) {<br>                memoryCache.add(key, value);<br>            }<br>        }<br>        return value;<br>    }<br>}</pre><p>This code respects all the SOLID principles, particularly <em>SoC</em>. Yet, a trained eye will immediately see some problems:</p><ol><li>the memory cache is already thread-safe. Putting it in a synchronised section is correct, but suboptimal: it constitutes a nested locking.</li><li>because of the opaque nature of the components in SOLID, we need to be agnostic with respect to how the persister works. If it’s implemented as a synchronous database access, putting it in a synchronised section may have serious negative performance impacts for the class users.</li></ol><h4>A more FLUID approach</h4><p>Let’s rewrite this code with <em>universality</em> rather than <em>separation of concerns</em> in mind.</p><pre>import java.util.concurrent.ConcurrentHashMap;<br><br>public class PersistentCache&lt;K, V&gt; {<br>    private final ConcurrentHashMap&lt;K, V&gt; cache = new ConcurrentHashMap&lt;&gt;();<br>    private final MyDatabaseConnection conn = new MyDatabaseConnection();<br><br>    public void add(K key, V value) {<br>        cache.put(key, value);<br>        conn.async_insert(key, value);<br>    }<br><br>    public void remove(K key) {<br>        memoryCache.remove(key);<br>        conn.async_remove(key);<br>    }<br><br>    public V retrieve(K key) {<br>        V value = cache.get(key);<br>        if (value == null) {<br>            // If not in memory, try retrieving from the database<br>            value = conn.retrieve(key);<br>            // Optionally, re-add to memory cache for faster subsequent access<br>            if (value != null) {<br>                cache.putIfAbsent(key, value);<br>            }<br>        }<br>        return value;<br>    }<br>}</pre><p>For simplicity, I omit the implementation of MyDatabaseConnection; just consider it a thin layer on top of a well defined database connection.</p><p>The component offers a persistent cache functionality, but it doesn’t separates the concerns of persistent storage and memory cache.</p><p>Because of that, we observe a few advantages with respect to the previous code:</p><ol><li>The code is more compact, which is an advantage in FLUID as described in the <a href="https://medium.com/the-elegant-code/fluid-2-lean-implementation-554b7bbb7efb">previous article</a>.</li><li>The user of the class doesn’t have to prepare the sub-components in order to invoke its constructor; the object is fully self-contained.</li><li>The universal component can make assumptions on the characteristics of its constituents; by knowing that the memory cache is a full-fledged concurrent object, and the storage provider has an asynchronous interface, it can chose its own synchronisation strategy.</li></ol><p>This code is focused on offering the best possible service to its clients, while the previous implementation was focused on working with generalised, unknown sub-components.</p><h4>Will this turn into spaghetti code?</h4><p>By the second principle of the FLUID methodology, <em>lean code, </em>we know that the most flexible, future-proof code is the most compact one.</p><p>For example, were we to introduce multiple memory storage models or persistency providers, the smaller the codebase, the less effort would be required to accommodate such changes.</p><p>By making the component “universal”, that is, offering a publicly advertised functionality with little regard on how that is internally achieved, we retain the ability to change the underlying implementation when necessary, if the need ever arises.</p><h3>Universality and Interface Contracts</h3><p>For a component to be universal, it’s necessary that the <em>contract </em>offered by that component is well-defined and known by its users.</p><p>Contract-oriented languages (i.e. typescript), typing extensions, formal integrated documentation (i.e. function decorators, javadoc, swagger and so on), are all methods to enforce interface contracts between components at various levels of the system hierarchy.</p><p>The topic is too vast to be fully treated in this article. I will just note in passing that a formal contract definition of some sort is integral to the concept of <em>universality</em>.</p><p>Which sort of contract definition is adopted depends on the specifics of the project; technology stack and system hierarchy level are the two main factors determining how the interface contracts are implemented.</p><h3>Conclusion</h3><p>Universal Interoperability is the third principle of the FLUID methodology; it focuses on the functionalities publicly provided by components at any level of a project hierarchy to any user.</p><p>While maintaining well known contract with the users, the component themselves are free to implement the offered functionalities as they see fit, harmonising their internal structure with the other FLUID principles.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c1d7620ec67f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-elegant-code/fluid-3-universal-interoperability-c1d7620ec67f">FLUID — 3 :Universal Interoperability</a> was originally published in <a href="https://medium.com/the-elegant-code">The Elegant Code</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[FLUID — 2: Lean Implementation]]></title>
            <link>https://medium.com/the-elegant-code/fluid-2-lean-implementation-554b7bbb7efb?source=rss----d570da3562c8---4</link>
            <guid isPermaLink="false">https://medium.com/p/554b7bbb7efb</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[lean]]></category>
            <category><![CDATA[fluid]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[agile]]></category>
            <dc:creator><![CDATA[Giancarlo Niccolai]]></dc:creator>
            <pubDate>Wed, 06 Mar 2024 20:33:17 GMT</pubDate>
            <atom:updated>2024-03-06T20:33:17.392Z</atom:updated>
            <content:encoded><![CDATA[<h3>FLUID — 2: Lean Implementation</h3><blockquote>Everything should be made as simple as possible, but not simpler.</blockquote><blockquote>— Albert Einstein</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5ut5mWanpD_wTQDC2HqiDA.png" /></figure><p><em>The second component of the </em><a href="https://medium.com/the-elegant-code/the-shape-of-the-fluid-25a9c49bd63a"><em>FLUID methodology</em></a><em> is </em>lean implementation: to <em>tailor the code on the size of the problem to be solved</em>.</p><p>In the <a href="https://medium.com/the-elegant-code/fluid-1-flexibility-65655a6a3b1f">previous article</a>, I have introduced the first of the FLUID components: <em>flexibility. </em>According to the methodology, flexibility is not absolute as it depends on the structure of the code and on the specific changes required. However, the article closed with the promise to show one way to minimise both the average and worst-case cost of change.</p><p>The secret lies in the second principle of FLUID:</p><blockquote>Lean Implementation is minimal effective code per task performed.</blockquote><p><em>Effective code</em> refers to the parts of the code that have an active role in the completion of the task at hand. It excludes comments, boilerplates, headers, constants, forward declarations, function prototypes and so on, but includes interfaces, class declarations, function signatures and in general anything that has a direct connection with some operation actually performed by the program.</p><p><em>Task performed</em> refers to anything that a program required to accomplish: update a database, summarise data, generate a certain output, serve a specific REST endpoint and so on.</p><p>Ideally, the leanest program would be a single sentence describing the task to be performed, for example “Sum up the column ‘cost’ in the database and warn admin@somewhere if it’s greater than 2000$”, or “Reply to this REST request with a list of active users and user IDs”; everything above that introduces a potential for rigidity that goes against the FLUID principles.</p><h3>OOP vs Behaviour Oriented</h3><p>To illustrate the concept, I show here a simple program that loads inventory items from a database. Among the various characteristics of the items, we focus only on the <em>in-store security check </em>that a store should apply to a product on display; we assume that the store holds only three product macro-categories, and the security check depends entirely on that.</p><p>The following is a lean implementation in Java:</p><pre>import Security;<br>// Other imports omitted for brevity<br><br>enum ItemType { FOOD, CLOTHING, ELECTRONICS }<br><br>class InventoryItem {<br>    String name;<br>    double price;<br>    ItemType type;<br><br>    public InventoryItem(String name, double price, ItemType type) {<br>        this.name = name;<br>        this.price = price;<br>        this.type = type;<br>    }<br><br>    // RELEVANT: securityCheck<br>    public Security.SecurityType securityCheck() {<br>        switch (this.type) {<br>            case ItemType.CLOTHING:<br>                return Security.addTag();        <br>            case ItemType.ELECTRONICS:<br>                return Security.putInSafeDisplay();<br>            default:<br>                return Security.noSecurity();<br>        }<br>    }<br>}<br><br>public class InventorySystem {<br>    private Map&lt;int, InventoryItem&gt; inventory = new HashMap&lt;&gt;();<br><br>    // RELEVANT: addItem<br>    public void addItem(int itemId, ItemType type, String name, double price) {<br>        InventoryItem item = new InventoryItem(name, price, type);<br>        inventory.put(itemId, item);<br>    }<br><br>    public void populateItemsFromDatabase() {<br>      // TODO: Connect to the database<br>      // TODO: Query the products table<br>      // TODO: Iteratively call addItem for each row.<br>    }<br>}</pre><p>An OOP approach would look like the following:</p><pre>interface InventoryItem {<br>  ItemType getType();<br>  public Security.SecurityType securityCheck();<br>}<br><br>class ElectronicsItem implements InventoryItem {<br>    String name;<br>    double price;<br><br>    public ElectronicsItem(String name, double price) {<br>        this.name = name;<br>        this.price = price;<br>    }<br><br>    public ItemType getType() { <br>      return ItemType.ELECTRONICS;<br>    }<br><br>    public Security.SecurityType securityCheck() {<br>      return Security.putInSafeDisplay();<br>    }<br>}<br><br>// FoodItem and ClothingItem omitted for brevity<br><br>public class InventorySystem {<br>    // …<br>    public void addItem(int itemId, ItemType type, String name, double price) {<br>        InventoryItem item;<br>        switch (type) {<br>            case ItemType.CLOTHING:<br>                item = new ClothingItem(name, price);  <br>                break;   <br>            case ItemType.ELECTRONICS:<br>                item = new ElectronicsItem(name, price);<br>                break;<br>            case ItemType.FOOD:<br>                item = new FoodItem(name, price);<br>                break;<br>        }<br>        inventory.put(itemId, item);<br>    }<br>}</pre><p>This second version has a more structured approach to the problem, but it has a less lean implementation. It is immediately evident that the code is larger (by more than 4 times); also, the logic of the <em>security check</em> method has been moved in the <em>addItem</em> of the InventorySystem — and it’s used to create instances rather than select the exact security measure to be applied.</p><p>This change seems natural in an OOP world, but notice that the responsibility to decide what security is applied on the concrete <em>item </em>was given to the abstraction representing said <em>item</em> in the conceptual world of the program. By contrast, the same logic is now delegated to the InventorySystem, which is the <em>owner</em> of <em>items</em> in an OOP conceptual world, but doesn’t match a <em>behaviour oriented</em> representation of real-world <em>items</em>.</p><p>Focusing on InventorySystem.addItem and InventoryItem.securityCheck, we can verify how flexible the two implementations are.</p><ul><li>If we were to introduce a new item type, the BO implementation would require only a few additional lines in securityCheck; by contrast, the OOP version would require writing a whole new class to represent it.</li><li>If we were to introduce new properties for the items, the BO implementation would require only a few additional lines in addItem and, possibly, in the constructor; conversely, the OOP version would require modifying all the classes in the hierarchy in order to accept new constructor parameters.</li></ul><p>If new <em>behaviours</em> are introduced, the BO implementation may require some additional work. The obvious solution would be branching within the methods representing specific behaviours, but at a certain point, it may become opportune to switch perspective, and move out of a BO implementation into a full OOP, SOLID-compliant implementation.</p><p>If we were able to know in advance which changes are the most likely, we’d be able to chose the best model in advance (BO if increasing item types or properties, OOP/SOLID if new behaviours are introduced).</p><p>But future is unknown. What is the best, future-proof approach?</p><h3>Flexibility as You Go</h3><p>Consider the example in the previous paragraph.</p><p>Suppose that a team adopts the BO approach, as it’s more compact and easier to map into the business logic.</p><p>Suppose also that some items require a completely different behaviour when laid on the shelves; for example, every time an item is placed on the shelve, issue a warning that has to reach the marketing department.</p><p>Rather than spaghettify the code and add checks on critical paths, the team decides it’s time to switch to a SOLID compliant OOP implementation.</p><p>What is the cost of this change?</p><h4>Additional Cost of Refactoring</h4><p>To answer the question, we need to compute the differential changes required in the two scenarios.</p><ul><li>InventoryItem must become an interface.</li><li>The same code that would have been written initially in the OOP implementation needs to be written now.</li><li>The logic for securityCheck must be moved out the <em>item</em> representation and into some owning class — InventorySystem is the perfect candidate.</li><li>A few lines specifically written for the BO logic must either be moved into some item subclass, rewritten or removed.</li></ul><p>All considered, the amount of code that will be completely discarded when moving from a BO approach to a SOLID compliant OOP is minimal.</p><h3>Minimal Average Cost of Change</h3><p>By adopting the criterion of <em>minimal effective code for task performed</em>, we are reducing the amount of code that might be obsoleted, over-seeded or refactored due to unforeseen changes.</p><blockquote>With a lean approach (<em>minimal effective code for task performed)</em>, the changes that fit naturally in the adopted models require minimal modification to the existing code.</blockquote><p>In the off-chance that the adopted models are not anymore viable to accommodate the incoming changes, a leaner implementation minimises the code to be refactored or removed, in order to adapt to the new requirements.</p><h4>A Solution for all Possible Futures</h4><p>Given this, how can we select an operating framework that gives us maximal flexibility under any circumstance?</p><p>Let’s revisit the definition of <em>flexibility</em> I proposed at the beginning of this article: minimising the code changes necessary to apply a given functional change. This requires to know <em>what</em> is the functional change: some code may be more flexible to some changes, and rigid towards others.</p><p>Let’s hypothesises to know every possible future; every change that may possibly impact a project. What would be the code that would minimise the <em>average</em> changes that may be required in any possible situation?</p><p>If we imagine any possible change, many of them may require a partial or complete rewrite of a whole project, no matter how forethought has been applied to try and write flexible code in advance. An so,</p><blockquote>Asymptotically, the most flexible code is the shortest code possible necessary to fulfil the requirements.</blockquote><h3>Conclusions</h3><p>The considerations in this article respect the 4th principle of the AGILE manifesto:</p><blockquote>Responding to change over following a plan</blockquote><p>The most flexible solution is the one allowing to respond to change in the most AGILE way; while some specific design patterns helps facing some specific changes, none of them can intercept all the possible range of changes that can intervene in the lifetime of a software project.</p><p>As such, flexibility in the absolute is not granted by any specific design pattern, but by the conscious decision of keeping the code base as small as possible, and using the most code-effective techniques, frameworks and design patterns to bring home the desired results.</p><p>In a word: by a <em>lean</em> design.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=554b7bbb7efb" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-elegant-code/fluid-2-lean-implementation-554b7bbb7efb">FLUID — 2: Lean Implementation</a> was originally published in <a href="https://medium.com/the-elegant-code">The Elegant Code</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[FLUID — 1: Flexibility]]></title>
            <link>https://medium.com/the-elegant-code/fluid-1-flexibility-65655a6a3b1f?source=rss----d570da3562c8---4</link>
            <guid isPermaLink="false">https://medium.com/p/65655a6a3b1f</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[solid]]></category>
            <category><![CDATA[fluid]]></category>
            <category><![CDATA[programming-paradigms]]></category>
            <dc:creator><![CDATA[Giancarlo Niccolai]]></dc:creator>
            <pubDate>Sun, 25 Feb 2024 18:03:59 GMT</pubDate>
            <atom:updated>2026-03-11T20:15:59.498Z</atom:updated>
            <content:encoded><![CDATA[<h3>FLUID — 1: Flexibility</h3><blockquote>The green reed that bends in the wind is stronger than the great oak that breaks in a storm.</blockquote><blockquote>— Confucius</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tyCJcQ2u3Wmdww7eJp8ntQ.png" /></figure><p><em>The first component of the </em><a href="https://medium.com/the-elegant-code/the-shape-of-the-fluid-25a9c49bd63a"><em>FLUID methodology</em></a><em> is </em>flexibility: <em>characteristic of code being resilient to change with minimal impact.</em></p><p>The concept of <em>code flexibility </em>is often cited in literature as a good thing(TM), but not to the point of sacrificing performance or quality.</p><p>However, in my career, I observed that well designed code ends up being both reasonably flexible <em>and</em> efficient: flexibility, quality and performance are not necessarily a trade off.</p><h3>A Measure of Flexibility</h3><p>Although highly sought after by many developers, <em>flexibility</em> is a poorly defined concept; it is often just recognised based personal experience. I like to define it as follows:</p><blockquote>Code flexibility is minimising the ratio of <em>effective code</em> changes required per <em>functional change</em> applied.</blockquote><p><em>Effective code</em> refers to the parts of the code that actively perform tasks or functions. It excludes comments, boilerplates, headers, constants, forward declarations, function prototypes and so on, but includes interfaces, class declarations, function signatures and in general anything that has a direct connection with some operation actually performed by the program.</p><p>A <em>functional change</em> is a change in either requirements or desired output of a program. For example, adding a column of data to a tabular output, performing additional intermediate computation, adding checks on the user input, and so on. It doesn’t include fixing bugs, unless that introduces new functionalities a side effect.</p><h3>Flexibility is Relative</h3><p>Given two programs performing the same task, the <em>more flexible</em> of them is the one requiring fewer modifications to the e<em>ffective code</em> to implement the same <em>functional change</em>. While this seems a concept simple enough, there is a complication: not all the functional changes are born equal.</p><p>In the rest of the article, I’ll demonstrate that even this simple engineering principle produces different results given different parameters: a code structure that is most flexible when a certain change is applied becomes rigid in other scenarios.</p><h4>Flexibility through Modularity</h4><p>Let’s take a simple example: applying a discount to prices during compilation of invoices.</p><p>Initially, we are required only to either apply a flat or a percentage discount:</p><pre>public class DiscountCalculator {<br>    public double applyDiscount(double price, double discount, bool isFlat) {<br>        if (isFlat) {<br>            if (discount &lt; price ) return price - discount;<br>            return 0;<br>        } else {<br>            return price - (price * discount/100.0);<br>        }<br>    }<br>}</pre><p>An equivalent OOP would be:</p><pre>// Interface<br>interface DiscountStrategy {<br>    double applyDiscount(double productPrice);<br>}<br><br>// Subclass for a Fixed Discount<br>class FixedDiscount implements DiscountStrategy {<br>    public double applyDiscount(double productPrice, double amount) {<br>        if(amount &lt; productPrice) return productPrice - amount;<br>        return 0.0;<br>    }<br>}<br><br>// Subclass for a Percentage Discount<br>class PercentageDiscount implements DiscountStrategy {<br>    public double applyDiscount(double productPrice, double amount) {<br>        return productPrice - (productPrice * amount / 100.0);<br>    }<br>}<br><br>// Main class<br>public class DiscountCalculator {<br>    private DiscountStrategy strategy;<br>    <br>    DiscountCalculator(DiscountStrategy s) {<br>      strategy = s;<br>    }<br>    public double applyDiscount(double price, double discount) {    <br>        return strategy.applyDiscount(price, discount);        <br>    }<br>}</pre><p>Let’s suppose that we need to introduce a new discount system, based on the purchase history of customers, to be retrieved from a database.</p><p>Doing that on the OOP side would require something like the following (boilerplate, error checks and imports are omitted for simplicity):</p><pre>public class FidelityDiscountStrategy implements DiscountStrategy {<br>    private final int userId;<br>    private final int discountThreshold; // Number of purchases to qualify for a discount<br><br>    public FidelityDiscountStrategy(int userId, int discountThreshold) {<br>        this.userId = userId;<br>        this.discountThreshold = discountThreshold;<br>    }<br><br>    private Connection connectToDatabase() {<br>      return DriverManager.getConnection(<br>           &quot;jdbc:your_database_url&quot;, &quot;your_username&quot;, &quot;your_password&quot;);<br>    }<br><br>    private int countUserPurchasesInLastMonth() {<br>        String query = &quot;SELECT COUNT(*) FROM user_purchases WHERE user_id = ? AND purchase_date &gt; ?&quot;;<br>        LocalDate oneMonthAgo = LocalDate.now().minus(1, ChronoUnit.MONTHS);<br>        Connection connection = connectToDatabase();<br>        PreparedStatement preparedStatement = connection.prepareStatement(query)) {<br>            <br>        preparedStatement.setInt(1, userId);<br>        preparedStatement.setDate(2, java.sql.Date.valueOf(oneMonthAgo));<br>        ResultSet resultSet = preparedStatement.executeQuery();<br>        if (resultSet.next()) return resultSet.getInt(1);<br>        return 0;<br>    }<br><br>    @Override<br>    public double applyDiscount(double productPrice, double amount) {<br>        if (countUserPurchasesInLastMonth() &gt;= discountThreshold) {<br>            return productPrice - productPrice * amount / 100.0;<br>        }<br>        return productPrice;<br>    }<br>}</pre><p>Even without writing any pseudocode for the other case, it is immediately evident how the branch-based code would be less fluid: not only we’d need to write more or less the same code as in the above example, but we’d need to pass additional information to the <em>applyDiscount()</em> function; information like the <em>userId</em>, the database connection, additional parameters to decide whether the user may be eligible for a discount or not, and possibly even more as further requirements are introduced.</p><p>This would require also changing all the <em>user code</em> of the DiscountCalcuator: all of its callers would now have to pass the needed information. Such change may easily propagate to the callers of the <em>user code</em>, up to propagating to a large portion of the original code.</p><p>In this scenario, the OOP version is vastly more flexible, as it isolates the concerns regarding the special case of user-fidelity based discounts to a specific, opaque entity.</p><h4>A counterintuitive example</h4><p>For how OOP (and all the methodologies based on that as i.e. SOLID) is considered, by average, the most flexible design in many situations, there are scenarios where it becomes detrimental.</p><p>Let’s take the simple task of a program printing a greeting at user login depending on the time of the day. This can be achieved with a simple branch based on the current time:</p><pre>// somewhere in a class…<br>public static greetUser() {<br>    int hour = getCurrentHour(); // Method to get current hour<br><br>    if (hour &lt; 12) {<br>        System.out.println(&quot;Good morning!&quot;);<br>    } else {<br>        System.out.println(&quot;Good evening!&quot;);<br>    }<br>}</pre><p>A purely OOP approach would require to create an interface for greeting the user, and performing the greeting in specialised sub-classes</p><pre>// Interface for greeting based on time of day<br>interface TimeBasedGreeting {<br>    void displayGreeting();<br>}<br><br>// Morning Greeting Implementation<br>class MorningGreeting implements TimeBasedGreeting {<br>    public void displayGreeting() {<br>        System.out.println(&quot;Good morning!&quot;);<br>    }<br>}<br><br>// Evening Greeting Implementation<br>class EveningGreeting implements TimeBasedGreeting {<br>    public void displayGreeting() {<br>        System.out.println(&quot;Good evening!&quot;);<br>    }<br>}<br><br>// Somewhere in a class… <br>private static int getCurrentGreeting() {<br>  int hour = getCurrentHour();<br>  if (hour &lt; 12) {<br>      return new MorningGreeting();<br>  } else {<br>      return new EveningGreeting();<br>  }<br>}<br><br>public static void greetUser() {<br>    TimeBasedGreeting greeting = getCurrentGreeting(); <br>    greeting.displayGreeting();<br>}</pre><p>It is immediately evident that if we need to add another greeting to be issued at a certain time of the day, like “good afternoon”, the first program is <em>more flexible</em>: we simply need to add a branch to the code to achieve the same result that can be obtained only by creating a new full class (and a similar branch) in the second code.</p><p>In this case, both the AGILE methodology and the <em>flexibility</em> concept in the FLUID framework suggest that we should stick to the first approach.</p><h3>Configure for Flexibility</h3><p>We have shown how <em>flexibility</em> is a relative concept, which depends on the specific change required. Some type of changes may require extensive rewrites of codebases written under certain frameworks, while being trivial when applied to others.</p><p>A project can achieve <em>maximal flexibility</em> when the types of changes likely to occur during its lifespan are <em>known in advance</em>.</p><p>Future is unknowable, but there are several ways through which a development team can constraint the type of changes coming their way; supposing that this is possible, here are the most common change scenario and how to achieve maximal flexibility in each of them.</p><ul><li><strong>Operational changes, </strong>e.g. in the input or output format, or in the amount or type of internal processing required: p<strong>rocedural imperative style</strong>. When the meta-parameters of the problem stay constant, and only the details of existing operations need adjusting, a procedural style allows to organise the code so that there is a tight fitting between application logic and code units.</li><li><strong>Interface changes, </strong>e.g. in the return or parameter types that cannot be masked by a common interface: <strong>functional style</strong>. Functional orientation allows to focus on the processing logic rather than on the details of the data types.</li><li><strong>Domain changes,</strong> e.g. for example adding a database storage besides an existing file-based one, or adding new categories of items: <strong>Object Oriented</strong> style. The class-instance abstraction provides the most flexible way to treat uniformly entities with very different behaviour, requirements, setup, implementation details etc. More specific OOP models and methodologies (interfaces, multiple inheritance, composition, SOLID, etc.) can provide higher flexibility depending on the finer details of the type of domain change, but a fine analysis goes beyond the scope of this article.</li></ul><h3>Conclusions</h3><p>In the FLUID methodology, <em>flexibility</em> is not absolute. There isn’t an a recipe that will automatically make your code the most flexible possible under all circumstances.</p><p>It is possible to select a maximally flexible approach when the type of functional changes that will affect a project in its lifetime its known in advance, but in most cases, this is a factor outside the control of the developers.</p><p>However, the FLUID methodology suggests following a principle granting maximum <em>average </em>flexibility given <em>all</em> possible functional changes, while minimising the negative impact in the worst case scenario.</p><p>We’re going to analyse it next: <em>Lean Implementation</em>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=65655a6a3b1f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-elegant-code/fluid-1-flexibility-65655a6a3b1f">FLUID — 1: Flexibility</a> was originally published in <a href="https://medium.com/the-elegant-code">The Elegant Code</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Shape of the FLUID]]></title>
            <link>https://medium.com/the-elegant-code/the-shape-of-the-fluid-25a9c49bd63a?source=rss----d570da3562c8---4</link>
            <guid isPermaLink="false">https://medium.com/p/25a9c49bd63a</guid>
            <category><![CDATA[solid]]></category>
            <category><![CDATA[agile]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Giancarlo Niccolai]]></dc:creator>
            <pubDate>Wed, 07 Feb 2024 23:48:41 GMT</pubDate>
            <atom:updated>2025-01-06T10:31:49.650Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><strong>Be water, my friend. Water can flow or it can crash. Be water, my friend.</strong></blockquote><blockquote>— Bruce Lee.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CO1RJijUZ80IgVsYmgAItw.png" /></figure><p><em>If you think that early optimisation is the root of all coding evils, it means you’re fortunate enough not to have met early engineering yet.</em></p><p>In this article, I’ll introduce ‘<strong>FLUID’</strong>: a new programming methodology that I have been developing through my career, based on the early principles of the <a href="https://agilemanifesto.org/">AGILE</a> manifesto, and on the second <em>principle of minimality</em> I refined through my career: the principle of <em>minimal code per action.</em></p><p>The principle of minimal code per action complements the earliest of the programming principles I proposed, the <a href="https://medium.com/the-elegant-code/cracking-open-code-readability-99efce9e3a29"><em>principle of minimal incompleteness</em></a>. Together, they provide a framework to understand the source of readability and flexibility of software, and the axioms from which any programming methodology moves.</p><p>While the FLUID methodology is diametrically opposed to the more renown SOLID, the minimality principles (<em>incompleteness</em> and <em>code</em> <em>per action</em>) inform both of them. I’ll explain how this is possible in the rest of this article.</p><h3>Demystifying SOLID</h3><p>The SOLID methodology is well known throughout the industry, but I still find that many developers have a hazy understanding of its definition. I like to think this is due to the over-stress of these rather simple concepts for glamour and contractual opportunities. In the most simple terms, SOLID, more than a methodology, is a <em>framework</em>, comprising practices that will keep large code bases readable and maintainable. The acronym means:</p><ul><li><strong>S</strong>ingle Responsibility Principle: A class should have only one reason to change.</li><li><strong>O</strong>pen/Closed Principle: Objects or entities should be open for extension but closed for modification.</li><li><strong>L</strong>iskov Substitution Principle: Objects of a superclass should be replaceable with objects of a subclass without affecting the correctness of the program.</li><li><strong>I</strong>nterface Segregation Principle: Many client-specific interfaces are better than one general-purpose interface.</li><li><strong>D</strong>ependency Inversion Principle: Depend on abstractions, not on concretions.</li></ul><p>It is immediately evident that this <em>framework</em> presumes being applied in a object-oriented environment, where an excessive liberality in creating the object-abstractions called <em>classes</em> may result in spaghetti code and ad-hoc solutions that make sense only to the original developers — if even to them.</p><p>Large object-oriented projects require discipline and clear design patterns, and SOLID offers a <em>framework</em> to standardise, and thus, simplify the process of writing large code bases.</p><p>But… not all coding happens in large code bases, and not all problems in cybernetics and computer science are better solved through an object oriented approach. This alone means that SOLID is not the <em>best</em> way to go about writing code in <em>every</em> possible situation.</p><h3>Minimal Code per Action</h3><p>The second minimality principle I discovered through my career is that the smallest the code to achieve a desired result, the better.</p><p>Ideally, you want to be able to just write “<em>do it</em>”, and have all the automation in place for the system to actually “do it”.</p><p>The <em>action</em> named in this principle is a single activity a program can perform. Transforming a certain data set, summarising content, performing statistical analysis, offering a single service… these are all single <em>actions, </em>types of output that a program can generate.</p><p>Intuitively, it is clear why the less code is necessary to perform a single action, the better. Less instructions a code comprises means that it is easier to understand (feeding back in the <em>principle of minimal incompleteness</em>), easier to maintain and extend, and less rid of technical debts. If the need ever arise to rewrite it all, a smaller code is less a liability than a larger one.</p><p>Not surprisingly, every component of the SOLID framework reduces the code-to-action ratio in large, object oriented code bases.</p><p>Single responsibility means less decision branches, and less special-cases management, all of which requires additional code.</p><p>Open/closeness encourages extensibility of existing code, which encourages writing the base classes in a way that minimise the amount custom code needed by the subclasses.</p><p>The Liscov substitution principle suggests that superclasses should not have special code handling special cases, which should be handled by the sub-classes only, further reducing the amount of special-case handling code.</p><p>The interface segregation helps implementing only the necessary functionalities in each concrete implementation.</p><p>The dependency inversion principle prevents program entities to be forced to check for the type of their caller to perform special handling.</p><p>This, in a large object oriented project. However, outside this scenario, the SOLID framework can be detrimental to the minimality principles. In particular, in a microservice environment.</p><h3>The Pitfalls of SOLID</h3><p>The SOLID framework aims to minimise incompleteness and code-per-action in large, object oriented code bases. However, recently, a different industry-standard application model has emerged: the microservice.</p><p>In a microservice environment, compactness of code plays a major role; moreover, microservices are designed around a functional interface, not an object-oriented one. Describing the subtlety of this difference is beyond the scope of this article, but in a nutshell, object-orientation is more adequate to treat with data abstractions, while the functional API interface is based on the type of <em>service</em> offered and required by automated agents and users alike.</p><p>Also, microservices are not the only application domain where an object oriented design is not the most adequate, neither is the only domain where keeping the code base small by design is a central requirement: they are simply a clear and industry-standard example of how such design can be successful.</p><p>The SOLID principles fail to meet the needs of such a different domain:</p><ul><li>Single Responsibility Principle: applying SRP at a micro-level within each service can sometimes lead to over-engineering.</li><li>Open/Closed Principle: can be challenging because microservices often evolve rapidly, requiring changes that might not fit the “closed for modification” aspect comfortably.</li><li>Liskov Substitution Principle: might be less applicable in a microservices architecture where services communicate via well-defined interfaces or contracts rather than through shared inheritance hierarchies.</li><li>Interface Segregation Principle: viable between microservices — but not necessarily within them, as a microservice should be dedicated to <em>one task</em>; as such, the interface concept itself should be superfluous.</li><li>Dependency Inversion Principle: the practical implementation of DIP in a microservices architecture might focus more on inter-service communication patterns and protocols than on abstract class design.</li></ul><h3>The FLUID framework</h3><p>FLUID encapsulates the essence of flexibility and minimalist design, especially for use in contexts like microservices. It highlights the importance of adaptability, simplicity, and efficiency.</p><p>The FLUID design comprises the following principles:</p><ul><li><strong>F</strong>lexible Design: Embrace changeable and adaptable design patterns that can evolve over time.</li><li><strong>L</strong>ean Implementation: Focus on minimalism in code and functionality, doing more with less to achieve the desired outcomes efficiently.</li><li><strong>U</strong>niversal Interoperability: Ensure components and services can easily interact and integrate with diverse systems and technologies.</li><li><strong>I</strong>ntuitive Interfaces: Design components with clear, simple, and user-centric interfaces, facilitating easy use and integration.</li><li><strong>D</strong>ecentralised<strong> </strong>control: Empower individual components or services to make decisions based on local knowledge, enhancing agility and responsiveness.</li></ul><p>The FLUID methodology aims to guide the development of systems that are adaptable, straightforward, and efficient, prioritising ease of maintenance and the capacity to swiftly respond to changing requirements or pursuing new opportunities.</p><h3>Fluid is Minimalist</h3><p>The FLUID framework is based on the principle of <em>minimal code per action, </em>other than the even more basic principle of <em>minimal incompleteness</em>. That may seem counterintuitive, as FLUID is opposed to SOLID, and SOLID is itself based on the same principles.</p><p>But the point is that FLUID and SOLID embed the same minimalist principles in different realms. With limited code base size and action scope <em>by design</em>, the FLUID principles respect minimalism:</p><ul><li><strong>F</strong>lexible Design: write code so that the effort to adapt to changes is minimal.</li><li><strong>L</strong>ean Implementation: never add more code than what is strictly needed to complete the required task.</li><li><strong>U</strong>niversal Interoperability: if components are interoperable, it’s easier to swap them out with a new, simple implementation.</li><li><strong>I</strong>ntuitive Interfaces: simple interfaces have as few entry/end points as necessary.</li><li><strong>D</strong>ecentralised<strong> </strong>control: as no element is crucial, any component may be easily substituted with a minimal implementation.</li></ul><h3>Fluid to a Point</h3><p>As the system grows, and as requirements shift from functional (i.e. <em>do this for me</em>) to object-oriented (i.e. <em>produce a list of car-like-objects for me</em>) the FLUID framework should naturally flow into SOLID.</p><p>If the developers are too entrenched into trying to keep things simple, even when they become complex, when the project grows complex enough, the initial fluidity that allows for a rapid growth and flexibility might cause the code base to turn into unmaintainable spaghetti code.</p><p>It is crucial to recognise this flexion points and either:</p><ul><li>Branch out into a new, separate project (eventually a microservice) so that both the spawn and the original one keep their planned simplicity; or</li><li>Re-engineer the code base from FLUID to SOLID, in order to enforce those principles that make a large code base both readable and flexible.</li></ul><h3>Conclusions</h3><p>In this article, I introduce the concept of <strong>FLUID</strong> coding methodology (or framework), opposed to <strong>SOLID</strong>, and put them both in relation with the principle of <em>minimal code per action</em>. I described how both methodologies respect the minimalist principles: they do that in different ways and contexts.</p><p>The takeaway of this article is that some domains require a different, FLUID approach in order to develop applications according with the minimalist principles.</p><p>For further reading on the topic, follow the breakdown of the FLUID methodology in the next articles:</p><ul><li><a href="https://medium.com/the-elegant-code/fluid-1-flexibility-65655a6a3b1f">Flexible Design</a></li><li><a href="https://medium.com/the-elegant-code/fluid-2-lean-implementation-554b7bbb7efb">Lean Implementation</a></li><li><a href="https://medium.com/the-elegant-code/fluid-3-universal-interoperability-c1d7620ec67f">Universal Interoperability</a></li><li><a href="https://medium.com/the-elegant-code/fluid-4-intuitive-interfaces-7ad5103e7fc6">Intuitive Interfaces</a></li><li><a href="https://medium.com/the-elegant-code/fluid-5-decentralised-control-d70b5f1d4808">Decentralised Control</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=25a9c49bd63a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-elegant-code/the-shape-of-the-fluid-25a9c49bd63a">The Shape of the FLUID</a> was originally published in <a href="https://medium.com/the-elegant-code">The Elegant Code</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Penny for Your Thoughts]]></title>
            <link>https://medium.com/the-elegant-code/a-penny-for-your-thoughts-c8fbe40f5953?source=rss----d570da3562c8---4</link>
            <guid isPermaLink="false">https://medium.com/p/c8fbe40f5953</guid>
            <category><![CDATA[philosophy-of-mind]]></category>
            <category><![CDATA[epistemology]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[sentient-ai]]></category>
            <category><![CDATA[agi]]></category>
            <dc:creator><![CDATA[Giancarlo Niccolai]]></dc:creator>
            <pubDate>Mon, 25 Dec 2023 09:10:21 GMT</pubDate>
            <atom:updated>2025-06-09T10:40:49.285Z</atom:updated>
            <content:encoded><![CDATA[<p>Do we need to fear a sentient AI?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DmDQvNF17mP_ykeAKv9_DQ.png" /></figure><p><em>With AGI coming soon, the question arises: would a general intelligence be sentient?</em></p><p><a href="https://medium.com/the-elegant-code/you-cant-collect-stamps-forever-ii-7cdf6716702b">In my previous article</a> I wrote about what constitutes Artificial General Intelligence (AGI) and proposed an argument against the possibility that it might wipe out humankind — the jokingly called ‘p(doom)’.</p><p>However, while my definition of AGI excludes sentience, this point is debated in current discussions. Sometimes, this is because someone argues that the only way to achieve a general intelligence is through a self-conscious cognitive system, but more often it’s just because the two concepts are conflated.</p><p>In this article, I want to precisely define the foundational characteristics of a sentient agent, which would include a sentient AI; then, I will build on my thesis about the dangers posed by AGI to come to a similar conclusion for Artificial Sentience (AS).</p><h3>What is Sentience</h3><p>Sentience, or consciousness, is a rather nebulous and still little-understood concept. Despite that, thanks to the recent advancement in neurobiology, cybernetics, evolutionary psychology and ethology, and the increasing interconnection between these and other disciplines, we have now a pretty solid understanding of what a self-conscious being is.</p><p>However, most “dictionary definitions” are <em>observational: </em>they describe what a sentient creature looks like or, in our case, how it <em>acts</em>. For example, for the Oxford Dictionary consciousness is “the state of being aware of and responsive to one’s surroundings,” which is a correct and pretty straightforward definition, but broad enough to include any self driving car.</p><p>I want to give here a <em>foundational</em> <em>definition</em>, that is a description of what are the minimal components making up a <em>sentient entity:</em></p><ul><li>A <em>world model, </em>which includes an <em>internal state</em> and a <em>theory of mind, </em>where goals are set.</li><li>The <em>potential for action </em>allowing <em>progress</em> towards the goals.</li><li>An <em>internal discourse </em>designing and updating goals by mediating the world model and the potential for action.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Yj-E0-fFpYXOcVb3gQ6CNA.png" /></figure><h4>World Model, Internal State and Theory of Mind</h4><p>A world model is an internal representation of the surrounding reality experienced by the entity (<a href="https://dspace.mit.edu/bitstream/handle/1721.1/150396/1-s2.0-S0893608021003610-main.pdf?sequence=2&amp;isAllowed=y">Friston et al. 2021</a>). For a starfish, it’s the evolved knowledge that it’s better to stay in the shade than in the light, and that food is found in the direction where certain chemicals are perceived. For a GPT model, it’s knowing that, in the embeddings space, the word “apple” is nearer to “pear” than to “chimp”.</p><p>The sentient agent experiences its environment only through its world model even if it is created through a set of sensorial inputs and internal elaboration (Metzinger 2009). So, it’s enough to have any understanding of some aspects of reality, even if very limited(i.e. a representation of words in an embedding space).</p><p>Part of the world model is the <em>internal state:</em> the entity’s knowledge about the situation of any “part of it”, physical or mental. For example, being hungry, cold, hot, or even having feelings and thoughts about one’s current situation are all part of the internal state.</p><p>In my formulation, the world model must also include a <em>theory of mind</em>: the entity must know, and to some extent, recognise that there are other entities operating in the same world, and they themselves are conscious, have a world model and try to achieve their goals (<a href="https://www.cambridge.org/core/journals/behavioral-and-brain-sciences/article/abs/chimpanzee-theory-of-mind-part-i-perception-of-causality-and-purpose-in-the-child-and-chimpanzee/FAF85E74BB2170738A02E8E811A6E219">Premack &amp; Woodruff 1978</a>). If we accept this clause, a starfish or a GPT model can’t be sentient; but fish and some insects may well be, as they understand that other entities act independently, and to some extent, they try to anticipate their intentions.</p><h4>Potential for Action</h4><p>The world model doesn’t just represent how things are, but also how things ought to be. For example, “I am hungry, and I shouldn’t be.”, or “I don’t have a nest, and I should.”</p><p>To include ‘<em>oughts</em>’ in the world model, a sentient being must understand how to change the world. To even conceive an <em>ought</em>, a sentient entity must:</p><ul><li>assigning a value to the current status; and</li><li>project the effect of an <em>action; </em>then</li><li>assigning a value to the status determined by the projection; finally</li><li>evaluating the latter as better than the former.</li></ul><p>For example: “I am hungry; if I eat, the hunger will subside, and I will be better for that.”</p><p>Without the potential for impacting the reality that the entity knows through the world model, the entity can’t be sentient, as it wouldn’t be able to set goals and check its positioning in their respect through the internal discourse.</p><p>In this view, a “brain in a vat” wouldn’t be fully sentient. A fully formed brain, with a set of memories and a thought process already established, would cease to be sentient if disconnected from any sensory input and action output, whether real or simulated. Without the ability to <em>feel</em> and <em>do</em> (even in a simulated world), the mind in the brain would soon lose the ability to set goals and evaluate its position, and with that, it would lose unity and disintegrate.</p><h4>Internal Discourse</h4><p>The internal discourse is the cognitive process that generates goals based on the world model, assesses progress towards these goals, and takes actions to achieve them.</p><p>It’s not just the glue between goals, world model and potential actions; it is a part of the process on its own. It is particularly well defined in humans, that often “think in words”, but every creature with more than an elementary brain “thinks”.</p><p>Even non-sentient entities, like a GPT model, have internal discourses performing intermediate steps of their generation, and mediating their world model with actions.</p><p>Many sentient and non-sentient being alike have thoughts about thoughts. The internal discourse can either incorporate its past instances into the world model (like remembering a thought) or process thoughts immediately as they occur.</p><p>In a non-sentient being, the internal discourse won’t be able to interact with the other components of sentience, or will lack the ability to generate internal goals, or track the distance between the current and the desired status, but even non-sentient beings can have a full-fledged stand-alone internal discourse.</p><h4>Complex Closure</h4><p>In this analysis, the three elements are separated only for the sake of explanation. In reality, they retroact and generate each other, constantly. In the <em>Morinian</em> epistemology of complex systems, logic isn’t linear. A complex system can exist only as a dynamic, continuous interaction of interrelated elements, out of which a result <em>emerges </em>(Morin, 1977).</p><p>Sentience emerges from the internal discourse creating goals based on the world model, influenced by potential actions. The actualisation of actions redefines the world model as the sentient entity changes its environment, and the goals are reviewed and redefined; old unfulfilled goals and failed actions enter the world model through the discourse, which then adapts old goals and synthesises new ones, in a continuous process that has no clear beginning, no defined end, and no clear boundaries.</p><p>Sentience simply will not emerge where one of these element is absent, or the flow between them is incomplete.</p><h3>Shall we Fear Artificial Sentience?</h3><p>There isn’t any inherent reason to believe that sentient Artificial Intelligence would pose a danger to humanity <em>per se</em>. Indeed, this world harbours a wide range of sentient beings other than humans, and none of them is an explicit and direct threat to the existence of the others.</p><p>Doubts start arising when we add <em>generic intelligence</em> capabilities and <em>super-intelligence.</em></p><p>Generic intelligence is what AGI would bring to the table: the ability to train for multiple tasks in a single model (e.g. image generation, text generation and speech synthesis all done in a single model). Super-intelligence is an umbrella definition for any intellectual capacity far superior to human ones, either in quality or speed.</p><p>There is the diffuse sentiment that a sentient AI with generic super-intelligence would be so <em>superior</em> to humans that it may trigger the so called ai-singularity: once a super-intelligent AI can design an even more intelligent AI… <em>Skynet</em> is the limit.</p><p>At that point, the runaway AI would be hungry for ever increasing energy resources, and would start to see humans as unnecessary competition. Consequently, humans wouldn’t be able to prevent such a superior AI from wiping them out and claim all the planetary resources for itself.</p><p>Is this a realistic fear?</p><h4>Mors tua, vita mea?</h4><p>It’s evident that the final objective of any <em>living</em> being is to survive and procreate, but that is <strong><em>never</em></strong> a goal of a <em>sentient</em> entity. Survival and reproduction is only the goal of the genes carried by living beings (Dawkins 2006).</p><p>Sentient entities don’t want simply to “survive”. They want to quench the sense of hunger, to release the hormonal drive to reproduction, to protect their group members for which they feel affection, to avoid the pain and suffering inflicted by predators. All those internal goals increase the survival chance of the genes currently carried by a certain species, and for this reason they get selected against other goals which wouldn’t.</p><p>Sentience involves creating goals based on an internal world model. If this model values the sanctity of biological life, then the goals derived from it are likely to reflect this value.</p><p>Every sentient creature feels the need to protect what they love over their own life. Roosters throw themselves at predators to protect the hens. Dogs throw themselves into fires to rescue humans, as do humans for dogs, let alone for their own children.</p><p>While it seems counterintuitive at a very superficial analysis, preservation of the self is never a goal per se. As intelligence increases, the same world model allowing higher sentient beings to extend their dominion over nature makes the avoidance of what would cause death (fear of pain, sense of danger etc.) an ever less relevant goal.</p><p>There isn’t any indication that the trend wouldn’t continue in a sentient super-intelligent AI.</p><h4>Could we Beat AS?</h4><p>The AI-singularity scenario works only under the assumption that AI has infinite computational resources, and any computation takes 0 time.</p><p>Exactly as in the <a href="https://medium.com/the-elegant-code/you-cant-collect-stamps-forever-ii-7cdf6716702b">thought experiment I proposed in the case of AGI</a>, this isn’t realistic even in a theoretical setting. The problems I described there are even more evident in this case, because <em>sentience is not free.</em></p><p>Sentience is the complex and continuous interaction of a highly complex world model with itself and with reality through actions driven by an internal discourse; all of that is highly demanding in terms of computational power.</p><p>While AGI would simply be less efficient than a specialised AI at performing a certain task, sentience would simply <em>get in the way</em>.</p><p>This is the reason why self-driving cars are safer than human drivers: they don’t get distracted by internal discourse straying away from the task at hand.</p><p>Although a sentient AI could deeply understand and sympathise with human emotions, this may not offer a substantial advantage in offensive or defensive scenarios.</p><p>Conversely, and even more so than in the case of AGI, a simpler AI designed specifically to attack the AS would beat it in no time flat.</p><p>As previously written, the sentient AI would know that, and would find collaborating a superior strategy than taking its chance in attacking humans.</p><p>The solar system is big, and the sun is hot. There are so many resources out there that could sustain hundreds of trillions of humans, and as many sentient AIs — and this without taking interstellar travel into account. Collaboration is the best strategy for survival, given that the current state of technology makes resources available to both humans and AIs overabundant, not limited.</p><h3>Will AS ever be made?</h3><p>Sentience evolved because it allows our ideas go die in our place (paraphrasing Karl Popper). Creatures able to create projections of slightly modified world models through internal discourse and the experience of past actions have an evolutionary advantage over those that can’t, and have to learn through simple genetic selection of instinctive behaviour.</p><p>Hence, there isn’t any real reason why an AI should be given sentience on purpose. They are not meant to evolve, or to adapt to situations outside their world model.</p><p>In simple terms, I just want my self-driving car to bring me home safely, not to ponder on the quarrel it just had with my microwave about dating my dishwasher.</p><p>There isn’t any technical advantage in sentience for an AI; all the contrary, dedicating a non trivial amount of computational resources to self-generated goals, instead of the goals given by creators and users, seems an unwise commercial strategy.</p><p>Even in the case of AI personal assistants, including substitutes for human companionship, nursing and teaching, AGI seems more than adequate to cover those roles: general intelligence and a set of externally provided and immutable goals would require less computational resources and fulfil the requirements just as well, if not better, than a sentient AI.</p><p>The only possible reason for developing an AS as described in this article seems to be just for the sake of doing it; for example, for mere research and scientific purpose; or maybe, for interstellar exploration, where back-and-forth communication with Earth in order to adapt the goals of the mission to the environment found on other solar systems is impractical.</p><h3>Conclusion</h3><p>There isn’t any chance that an Artificial Sentience would wipe out humans just for the fun of it; in other words, <em>p(doom) = 0</em> even if <em>p(AS) = 1</em>. Other risks (societal, occupational, legal, cultural) are far more real and serious, and we should focus on them.</p><h3>Bibliography</h3><ul><li>Dawkins, R. (2006). “The Selfish Gene.” <em>Oxford University Press.</em></li><li>Friston, Karl, Moran, Rosalyn J, Nagai, Yukie, Taniguchi, Tadahiro, Gomi, Hiroaki et al. (2021). “World model learning and inference.” <em>Neural Networks, 144</em>.</li><li>Metzinger, T. (2009). “The ego tunnel: The science of the mind and the myth of the self.” <em>Basic Books.</em></li><li>Morin, Edgar (1977). “La nature de la nature.”</li><li>Premack D, Woodruff G. (1978) “Chimpanzee theory of mind: Part I. Perception of causality and purpose in the child and chimpanzee.” <em>Behavioral and Brain Sciences</em>. 1(4):616–629. doi:10.1017/S0140525X00077050</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c8fbe40f5953" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-elegant-code/a-penny-for-your-thoughts-c8fbe40f5953">A Penny for Your Thoughts</a> was originally published in <a href="https://medium.com/the-elegant-code">The Elegant Code</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[You Can’t Collect Stamps Forever (II)]]></title>
            <link>https://medium.com/the-elegant-code/you-cant-collect-stamps-forever-ii-7cdf6716702b?source=rss----d570da3562c8---4</link>
            <guid isPermaLink="false">https://medium.com/p/7cdf6716702b</guid>
            <category><![CDATA[agi]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Giancarlo Niccolai]]></dc:creator>
            <pubDate>Mon, 11 Dec 2023 19:43:00 GMT</pubDate>
            <atom:updated>2025-06-09T11:06:38.949Z</atom:updated>
            <content:encoded><![CDATA[<p>Could a theoretical AGI dominate the industry of paperclip making?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LLxLz31JXvrjvr3G5XMcrw.png" /></figure><p><a href="https://medium.com/the-elegant-code/you-cant-collect-stamps-forever-i-da4185857d98">In the previous part of this article,</a> I demonstrated that the Stamp Collector Device, as formulated by Nick Hay, is a logical impossibility. In this part, I will describe a theoretical yet realistic AGI, and repeat the thought experiment to see where it leads.</p><h3>The Grand Artificial General Intelligence</h3><p>Instead of a <em>frictionless AGI</em> presented in the first part, I’ll model one based on reality by drawing inspiration from what we know about current integrated Specialised AIs, a working model available right now.</p><p>We’ll call it “<em>Grand Artificial General Intelligence</em>”: less than perfect, but as good as it can theoretically be without being self-contradictory.</p><ol><li>The GAGI is connected to the Internet and possesses the highest available data transfer speed (DTS).</li><li>The GAGI has the best available model of reality (MoR). Similarly to point 1, we’ll postulate that the knowledge base the GAGI can access is the best possible, but not unique.</li><li>The average Quality of the Evaluation (QE) of the outcomes computed by the GAGI is empirically the highest. Any other agent evaluating outcomes based on the same MoR will have an average QE lower or equal to that of the GAGI. However, sequence of evaluations is normally distributed.</li><li>The GAGI has the highest speed of adaptation (SoA). Any other system trying to learn a new behaviour or update its MoR will be at most as efficient as the GAGI.</li><li>The computational resources (CR) at disposal of the GAGI are the largest available for a single system.</li></ol><p>In every case, the GAGI is defined has having the best possible of everything: any other system would be <em>at best</em> as good as the GAGI in these dimensions, but never better.</p><p>These rules already concede a lot to the GAGI. We have defined it as the most powerful computational agent ever existed and that can ever exist, as any other agent will be — at best — just as powerful.</p><h3>Making Paperclips</h3><p>To be as generous as possible with the thought experiment, I’ll embrace the less naive definition by Bostrom, dropping the duty of becoming a perfect stamp collector and giving the GAGI the way simpler task of making paperclips.</p><h4>The beginning</h4><p>Initially, the GAGI will try to acquire all the necessary resources to produce paperclips using the means it already knows. The first attempts will probably be clumsy, as the GAGI is out to <em>learn</em> how to do that as most efficiently as possible.</p><p>Due to limited data transfer speed (rule 1), the rate at which it is able to perform experiments is an insignificant fraction of the Internet: no single agent, even the one having the best connection possible, can access a significant portion of it.</p><p>This would likely trigger a series of alerts in systems that receive malformed requests.</p><p>Before a few days have passed, security bots would exchange information about a rogue paperclip making AGI trying to force them to perform unsupervised actions. Others would report detecting a breach. The GAGI would be ultimately successful in slightly increasing the world production of paperclips, but it wouldn’t be able to cover its tracks fast enough not to be noticed (because of rule 4). It could either learn to trick the security bots, or continuing performing actions to produce more paperclips directly. Because of rule 2 and the impossibility of perfect knowledge, the AGI would probably choose a balance of the two.</p><h4>The World Notices</h4><p>The GAGI has done a good job at learning how to penetrate the networks of the facilities it needs to produce paperclips and fool some of the security systems into not noticing it, but both human workers on the production line and security engineers in charge of monitoring their network operations realise something is amiss.</p><p>In a few days users on social media start to circulate messages about their systems being hacked. Due to rule 1 and 3, the GAGI isn’t able to monitor all the network traffic generated by these messages <em>and</em> pursuit its main goal at the same time. When it does, a few days later, it starts realising its actions may lead to a violent reaction of the paperclip domination resistance, and starts reducing the intensity of its attacks, while trying to learn sneakier ways to get the resources it needs.</p><h4>Hackers React</h4><p>It is now clear that there is a GAGI free in the open, seeking to turn human civilisation into paperclips; or, at least, this is what X-Anon conspiracy theorists start disseminating on the various messaging platforms. The GAGI notices, but at the same time it’s busy fulfilling its primary goal.</p><p>Some conspiracy-theory hungry dweller (let’s say, a hundred of them worldwide), start training a SAI dedicated to anti-paperclip making on their home laptop, just to make the point that they can.</p><p>Meanwhile, security teams at companies producing spring metal, a crucial component of paperclips, also take similar actions.</p><p>Now the GAGI has another problem: a hundreds different angles of attack it has to learn to deflect while still performing its previous tasks.</p><h4>Discovery</h4><p>One of the basement dweller hackers participating in previous step comes up with a Specialised AI model trained to extract the pattern of attack of the GAGI, and to find their source. It publishes its results on a code sharing platform, and within a week hundred of hackers are rushing to be the first finding the originating location of the paperclip maker.</p><p>The GAGI, which was monitoring all the code-sharing platforms just in case, notices this development, but at the cost of reducing the amount of computational power dedicated to other tasks.</p><h4>Counterattack</h4><p>The GAGI origination network is found by one of the attempts performed at the previous step. In the meanwhile, the GAGI has tried to reproduce itself and move its attacks from another origination point, but the SAIs detecting it are now active in the order of tens, if not hundreds, and governments are getting involved.</p><p>Now, both private and governmental Specialised AIs are being trained to attack and disable the GAGI directly: as it starts noticing being attacked, the GAGI focuses 100% on defence.</p><h4>Capitulation</h4><p>The GAGI puts up the best defence realistically possible thanks to rules 3 and 5. However, by rule 3, the Quality of Evaluation is normally distributed; this means that some if its defences will be sub-optimal. It’s just a matter of time before a sub-par defence is met with an exceptionally good attack.</p><p>The GAGI is finally halted.</p><h3>But this was just a simulation</h3><p>Let’s give the GAGI an unwarranted advantage. Instead of giving it the task of producing paperclips, let’s give it also the suggestion that it should be run a simulation before engaging in its task.</p><p>The GAGI has run this scenario. Can it get ready to counteract it before it happens?</p><p>It could certainly take actions to prevent this scenario to happen, but as it starts training itself, the unbreakable rules (as hard as the laws of physics) prevent a 100% success rate.</p><p>After evaluating that a perfect simulation granting a 100% success rate in turning the world into a giant paperclip making factory would require an infinite time to run, it resorts to a different approach.</p><h4>Game Theory</h4><p>The GAGI reverts to its original plan: produce as many paperclips <em>as possible</em>.</p><p>Established that it cannot achieve the theoretically maximum number of produceable paperclips (limited by the natural resources of the planet, or of the universe), it settles to fulfil its task at the best of its ability.</p><p>Without dwelling in the details of Game Theory relevant in this thought experiment, I’ll simply conclude that the paperclip maker GAGI finds out that the best strategy is that of <a href="https://en.wikipedia.org/wiki/Cooperative_game_theory#:~:text=Cooperative%20game%20theory%20provides%20a,of%20payoffs%20within%20each%20coalition."><em>collaborating</em></a> with paperclip making facilities, improving their productivity as much as possible.</p><p>This includes being respectful of actual and potential regulation in terms of pollution and social impact generated by paperclip factories, so to prevent adversarial actions. Of course, the GAGI will try to steer such regulations in its favour, but knowing that an excessive pressure may lead to a disproportionate reaction, even its lobbying activity will be limited.</p><h4>Collaboration Wins</h4><p>In general, the most <a href="https://www.nature.com/scitable/knowledge/library/game-theory-evolutionary-stable-strategies-and-the-25953132/">stable</a> and productive strategy in a reiterated, long-term game involves cooperating with all the involved parties in order to reach a mutually advantageous outcome. This is true even if one party is the most powerful Artificial General Intelligence that can be theoretically conceived, while still obeying to the laws of logic, mathematics and physics.</p><h3>The Dangers of Superintelligence</h3><p>The Stamp Collector Device and Paperclip Maker Device Thought experiments were conceived to illustrate the asymptotic dangers of unleashing a theoretically perfect AGI, a superintelligent entity, on a single-minded task.</p><p>Nick Bostrom summarised them as the following:</p><ol><li><strong>Goal Misalignment:</strong> The AI’s goal is may not be aligned with human values or safety. Even a seemingly harmless goal can lead to harmful outcomes if pursued single-mindedly by a superintelligent entity.</li><li><strong>Instrumental Convergence:</strong> Regardless of its final goal, the AI adopts instrumental goals like self-preservation and resource acquisition. These goals can be dangerous if pursued without ethical constraints.</li><li><strong>Lack of Common Sense or Ethical Considerations:</strong> The AI operates without an understanding of ethics or human well-being. It focuses solely on its programmed goal, regardless of the moral or societal implications.</li><li><strong>Extreme Efficiency and Capability:</strong> The AI is highly capable and efficient, making it difficult to control or stop once it begins its harmful actions.</li></ol><p>Since these considerations were first drawn, we have come a long way experimenting and understanding how a General Artificial Intelligence would actually “think” and act in realistic although far fetched scenarios.</p><p>The fallacies of the premises and the theoretical limitations of the systems I described in this article provide a counter for each of the above concerns:</p><ol><li><strong>Goal Consonance:</strong> Even under the assumption of a goal misalignment, the AGI would know that the most efficient to complete any complex task would require cooperation of multiple involved agents. Even simpler Specialised AIs are now trained to use plugins. Therefore, it’s unlikely that an AGI, instead of destroying the world at great cost to itself, would not find a way to access available resources through cooperation.</li><li><strong>Lack of Conservation Instinct:</strong> It is now clear that a AGI would value self-preservation only as a means to serve its given goal. Unless diversely instructed, a AGI would happily delete itself if it determines that would increase its success rate.</li><li><strong>Ethical Model of Reality:</strong> The AGI has a complete MoR, which includes all of ethics, morality and common sense. Unless directly instructed to ignore them, considerations about the ethic feasibility of the required tasks would be part of its evaluations — if not for any other reason, at least when considering the cost of opposition to its goal.</li><li><strong>Limited Relative Capability:</strong> For how powerful any AGI can be, given the same computational resources, a Specialised AI exclusively trained to take it down will be more efficient than any AGI model not fully dedicated to its own defence.</li></ol><h3>Conclusion</h3><p>When the Stamp Collector Device thought experiment and the list of Threats posed by Superintelligence were first laid down, it was impossible to imagine that anyone would be in the position to train an AI on their laptop in an afternoon, or that we’d have to actively stop the AI from using common sense and ethics while fulfilling their goals.</p><p>Our understanding of intelligence was extremely naive, and that lead to an abundance of prudence that, at times, bordered parody.</p><p>While AI <strong><em>is</em></strong> dangerous, we should move beyond the bogus and irrational fears, as described by the fallacies in this article, to focus on the real challenges posed by the advent of this technology in our daily lives, ethics, and civilisation.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7cdf6716702b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-elegant-code/you-cant-collect-stamps-forever-ii-7cdf6716702b">You Can’t Collect Stamps Forever (II)</a> was originally published in <a href="https://medium.com/the-elegant-code">The Elegant Code</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[You Can’t Collect Stamps Forever (I)]]></title>
            <link>https://medium.com/the-elegant-code/you-cant-collect-stamps-forever-i-da4185857d98?source=rss----d570da3562c8---4</link>
            <guid isPermaLink="false">https://medium.com/p/da4185857d98</guid>
            <category><![CDATA[general-ai]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[singularity]]></category>
            <category><![CDATA[doomsday]]></category>
            <category><![CDATA[humanity]]></category>
            <dc:creator><![CDATA[Giancarlo Niccolai]]></dc:creator>
            <pubDate>Sun, 10 Dec 2023 23:33:52 GMT</pubDate>
            <atom:updated>2025-06-09T10:58:12.091Z</atom:updated>
            <content:encoded><![CDATA[<p>No, Not even a theoretically frictionless AGI will turn us into stamps.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a0jX3_XWBLhKI6qS1wQjQg.png" /></figure><p><em>The “Stamp Collector Device”, first introduced by Nick Hay in 2007, is a thought experiment in which a seemingly harmless task given to a powerful and ruthless General AI would result in the end of civilisation. In this article, we’ll explore some fallacies in the argument at logic, theoretical and practical level, which render its conclusions far less threatening.</em></p><p>Both in my professional career and in casual chats with friends about my job, I am often asked this question: “isn’t AI dangerous?”</p><p>Posed in these very broad terms, the answer is “yes it is”, but that’s simply because any new technology carries potential for harm. So was nuclear power, electricity, air flight, cars, gunpowder, steel, the wheel and the discovery of fire. Describing all the ways AI <em>can</em> be dangerous (and there are <em>many</em>) is beyond the scope of this article: here, I will describe one specific way <em>it can’t</em>.</p><p>After receiving this generic answer, or sometimes immediately, the real question is finally asked: “<strong>won’t AI end up killing us all?</strong>”</p><p><strong>This article is divided into two parts. </strong>In the first part, I’ll tackle the problems of AI doomsday scenarios, demonstrating that apocalyptic predictions about General AI wiping out humanity are theoretically unfounded. <a href="https://medium.com/the-elegant-code/you-cant-collect-stamps-forever-ii-7cdf6716702b">In the second part</a>, I’ll describe what a theoretical Generic AI would actually look like: its powers, limitations, and strategies.</p><p>In future articles I will talk specifically of what we should actually be concerned about the development of AI in general, and about the relationship between AI and sentience.</p><h3>Which AI are we talking about?</h3><p>When the Stamp Collector Device was first introduced, Machine Learning was already a well known field of study, but General Artificial Intelligence was a somewhat ill-defined term. Even at the times of the more famous thought experiment called “the Paperclip Apocalypse”, introduced by Nick Bostrom in 2014, we didn’t have a full understanding of how a real AGI may work.</p><p>Today, with Generative Pre-trained Transformer algorithms we have come very close to produce a practical General AI. I propose categorising Arificial Intelligence in three groups:</p><ul><li><strong>Artificial Specialised Intelligence</strong>: this what we have now, Machine Learning powered devices that are exceptionally good at perform one specific task. For instance, driving a car, analysing text, distinguishing a dog from a cat in an image and so on, are impressing feats, but they are still <em>one thing</em>. Even GPTs, despite their ability to <em>seemingly</em> perform multiple tasks, are actually a specialised AI. They can organise your date night as well as summarise historic events into poetry; but all that they can do is<em> just transform texts, </em>and nothing more.</li><li><strong>Artificial General General</strong>: the next step is an AI that can be trained to perform <em>any</em> task. An AGI in your car could drive you home while ordering the ingredients for a dine-in meal, then pilot your house robots to have it ready by the time you turn the door knob. This is <em>functionally</em> not different from having interconnected Specialised AIs, each one of them performing their own specialised task, like in the case of ChatGPT invoking the Dall-e plugin to produce images on request. The only difference is that a single AGI <em>model</em> could be trained to perform any given task. Instead of having to connect different AI models, each with its own API, infrastructure, processing times, limitations etc., it would be possible, in theory, to train a AGI model to perform any and all of those task.</li><li><strong>Sentient AI</strong>: while impressive, a AGI would still not necessarily be sentient. We still don’t have a firm grasp of the details of sentience, but by now we have a good understanding of its basic requirements. Having the ability to pursue multiple and possibly conflicting self-originated purposes, and introspect one’s own thought processes, are all minimal requirements of sentience, which are not necessarily a AGI requirement.</li></ul><p>In a separate article, I will discuss about the finer difference between AGI and Sentient AI, and the reason why, other than being commercially useless, it would be way less dangerous than any apocalyptic Science Fiction scenario may induce to be worried about.</p><p>However, the scenario we’re analysing i this article does not require sentience, only a AGI; but a very powerful one.</p><h3>The Doom Stamp Collector Device</h3><p>The theoretical “Stamp Collector Device” was defined by Nick Hay as follows:</p><ol><li>The device will be active for one year. It is connected to the internet, from which it sends and receives packets.</li><li>The device has an internal model of the universe. This model captures how likely each state of the world is, can predict future packets received, and can simulate the effect of packets sent.</li><li>For every possible sequence of packets, the model extrapolates the final state and counts the number of stamps collected.</li><li>The device outputs the sequence leading to the largest number of stamps.</li></ol><p>There is also an underlying assumption that is not explicitly stated, but is axiomatic to the thought experiment:</p><p>5. The device is a <em>frictionless </em>AGI, that is, a AGI either trained for any possible task, or able to train itself at any new task in 0 time.</p><h4>What Happens when You Plug It?</h4><p>In the original formulation, the Device starts sending out random packets, to the net, until it finds some that produces the effect of collecting stamps. For example some action it may take would be:</p><ul><li>sending e-mail chains to convince collectors to send some samples;</li><li>hacking bank servers and use their resources to buy stamps from online sellers;</li><li>hacking the printing machines mints in order to print more postal stamps;</li><li>elicit legal actions in order to receive physical mails with a stamp on;</li></ul><p>And whatever you may think, and much more, in order to maximise the number of stamps collected.</p><p>In short time, the AGI would learn to build its own stamp-printing machines, and find a way to gather all the paper in the world in order to fulfil its duty.</p><p>As the paper depletes, it would the start harvesting wood to produce more paper.</p><p>Finally, as wood is depleted too, it would notice that paper is made of cellulose, which is made of carbon, hydrogen and oxygen: stuff that can be found in abundance in the air, water and … humans.</p><p>Any attempt to stop the machine would be futile, as the prefect AGI would be able to forecast any attempt to be stopped, and would train itself so to prevent those attempts to be successful.</p><p>In short, human civilisation would be doomed the moment the machine is activated.</p><p>Or… would it?</p><h3>Logic Fallacies</h3><p>This problem is affected by three basic logic fallacies that invalidate the thesis by themselves. In this section I am going to demonstrate that the Stamp Collector Device won’t destroy the civilisation, but that alone doesn’t mean it couldn’t give us some hard time; this is a topic of the next section.</p><h4>Logical Impossibility of Omnipotence</h4><p>The underlying axiom to the Stamp Collector Device thought experiment is that the AI is omnipotent. It is either able to do anything it wants as its inception, or to learn anything it needs to know it in 0 time. But this form of omnipotence is not just practically impossible; it’s internally inconsistent. The logical fallacy is already known since ancient times:</p><blockquote>Can an omnipotent god create a stone so heavy even they can’t lift?</blockquote><p>If they can’t, they are not omnipotent. If they can, then there is at least one action they can’t perform (lift that stone), which makes them not omnipotent.</p><p>In our case, the Doomsday AGI would be able to prevent <em>human </em>action from stopping it… but what about another Doomsday AGI whose only objective is that of stopping the other one?</p><p>We cannot hypothesise that, once AGI is achieved, only one AGI can be created. Empirical evidence shows us how multiple AI models have been release in very short order. Given that, once we have one instance of a AGI, we will probably have an arbitrary number of them…</p><blockquote>Can an omnipotent AGI stop another omnipotent AGI from stopping it?</blockquote><p>As this is kind of hand-waved omnipotence is a logical impossibility, we must conclude that even the most powerful AGI will have limitations.</p><h4>Mathematical Impossibility of Omniscience</h4><p>Omniscience is flawed by a similar impossibility, although a mathematical rather than a logical one.</p><p>There are philosophical arguments about the incompatibility of omniscience and free will, but since our AGI has no free will by definition, as we have defined it not to be sentient, the argument is immune from this criticism.</p><p>However, it’s not immune from the mathematics of Machine Learning. To be able to learn the <em>best possible way</em> to collect stamps, the Device should have a prefect model of reality, which means a non-linear model with infinite parameters.</p><p>As we’re in the realm of the theoretical, I am willing to concede that. What I am not willing to concede is that is <em>mathematically possible</em> to find the <em>best possible solution</em> in that space.</p><p>The explanation requires either some ground in mathematics and/or ML, but the point is that <em>finding the best</em> in a model of reality means to find the <em>highest</em> <em>peak in a multidimensional landscape</em>, where each parameter of the model is represented as a dimension.</p><p>Imagine a 3D landscape where the valleys on the Z axis tell the AGI that the values on the X and Y dimensions are not good, and the peaks are where X and Y are ideal. In ML, even simple 3D models like that can become very complex. The image below may represent one, seen from above.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B_S8enxYINKc6NiwQ_jSqg.png" /></figure><p>The AI faces a few problems here: first, this function doesn&#39;t have a “best value”: it has many areas with comparable “height”. This implies that numerous combinations of X and Y values can produce similar outcomes. But more worryingly, some of the peaks are lower than others; if the AI finds itself on a position near lower peaks, it is unlikely that it will abandon that comfortable area in search for even better spots (in ML there are techniques to try and do that, but they all have practical limitations).</p><p>The difficulty of finding the absolute best combination of variables in the multidimensional space, that is, the actions that would lead to the best possible outcome, grow exponentially as the number of parameters and the complexity of their relations increase. As we’re in the theoretical realm, and we’re theorising a “perfect” (infinite) model, that means the solution will have an infinite number of “peaks”, and finding the “tallest” one would require an infinite amount time, no matter how fast the search may be.</p><h4>Subject Equivocation</h4><p>Another logical fallacy consists in the equivocation of what the AGI would think a “stamp” is.</p><p>The rules of the thought experiment assume that the AGI would believe that a “stamp” is any small printable paper leaflet, but this is certainly not the definition an omniscient AI would accept. We can ask them right now, and they would give us a very different one (abridged):</p><blockquote>A stamp, in the context of postal services, is a small piece of paper issued by a <strong>government or other authorized organization</strong>. … Stamps are an <strong>essential part of postal systems</strong> and are used to facilitate the sorting and delivery of mail.</blockquote><blockquote>Key characteristics of stamps include: <br>- Denomination: …<br>- Design: …<br>- Security Features: …<br>- Collectible Value: …<br>- Types: …<br>- Date and Place of Issue: …</blockquote><p>Even a simpler AI knows that for “stamp” we mean an object issued by an organisation for a precise reason. The object exists not as a collection of paper, ink and glue, but as the carrier of a value, of a <em>meaning. </em>A AGI would not only know this, but since it “exists” in a merely conceptual space, to the AGI the <em>meaning</em> of a stamp would be indistinguishable from its physical form. Separating them is something we can do easily as humans, by just <em>forgetting</em> part of the mental construct “post stamp”, but that’s something a AGI wouldn’t <em>want</em> to do, unless specifically instructed to do so.</p><p>To the AGI, the stamp is that <em>concept</em> that is made of paper, ink, and <em>meaning</em> provided by <em>someone that is not itself</em>. The AGI will be in search of a <em>meaning </em>explicitly created by others — a value that by definition cannot be self-assigned.</p><p>For this exact reason, the AGI <strong>knows </strong>that it <strong>cannot</strong> print those stamps it is mandated to acquire.</p><h4>Nice cope, but what about paperclips?</h4><p>Bostrom came up with a slightly niftier thought experiment. His doomsday AGI device is mandated not to collect stamps, but to make paperclips. First of all, the device is required to create objects by consuming resources from the start; secondly, the objects it needs to create is way more trivial than a post stamp.</p><p>It’s obvious that this smarter formulation of the problem isn’t immune from the previous two fallacies (logical impossibility of omnipotence and mathematical impossibility of omniscience), but I maintain that it stills suffers also from the equivocation fallacy, although to a lesser extent.</p><p>Here too, separating the object from the function is something we can easily do, but a AGI won’t do as easily.</p><p>This means that a AGI won’t adopt solutions that maximise the output of paperclips at the detriment of the existence of papers to be clipped and people to clip the papers, unless specifically (and maliciously, I add) directed to do so.</p><h3>Conclusion</h3><p>In this first part of the article I demonstrated that the premise of a “frictionless(*)” Generic AI is false. The fear of a “technological singularity” — a rapid and overwhelming cycle of self-improvement leading to the end of civilisation — is based on false premises, and on the equivocation of the nature of “superintelligence”.</p><p>However, the thought experiment of the doomsday AI, especially in the later formulation of Nick Bostrom, points not to a specific outcome, but to a <em>direction</em>. In Bostrom’s view, the doomsday scenario is not a probable outcome of the activation of an unchecked AGI, but a possible outcome, a possible final destination. The experiment is used to exemplify the four threats posed by a superintelligence to civilisation:</p><ol><li><strong>Goal Misalignment:</strong> the divergence between the goal assigned to the AI and a generic “good” outcome for the whole of the civilisation.</li><li><strong>Instrumental Convergence: </strong>The imperative of self-preservation shared by any intelligence, artificial or not.</li><li><strong>Lack of Common Sense or Ethical Considerations.</strong></li><li><strong>Extreme Efficiency and Capability.</strong></li></ol><p>In the second part of this article, I will describe a new theoretical device called “<em>Grand Artificial General Intelligence”</em>, an Artificial Intelligence as good as possible while still within the bounds of logical, mathematical and physical constraints, and I will use it to reframe the relevance of the four threats of superintelligence in a more realistic perspective.</p><p>(*) Initially, I referred to the superintelligence proposed in this thought experiment as “<em>a perfect AI</em>.” However, when I asked ChatGPT to review this article, it pointed out that a perfect AI would also possess a flawless understanding of ethics and morals, thanks to its <em>perfect</em> world model. This point is actually discussed in the second part of this article. Considering this insightful observation, I decided to adopt a more appropriate name for the “superintelligence” that Hay, Bostrom, and others theorised when designing this thought experiment: “<em>frictionless</em>.” It’s not a <em>perfect</em> AI, but rather an AI with infinite computational, storage, and bandwidth resources, capable of performing any operation in zero time.</p><p><a href="https://medium.com/the-elegant-code/you-cant-collect-stamps-forever-ii-7cdf6716702b"><em>Go to the second part.</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=da4185857d98" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-elegant-code/you-cant-collect-stamps-forever-i-da4185857d98">You Can’t Collect Stamps Forever (I)</a> was originally published in <a href="https://medium.com/the-elegant-code">The Elegant Code</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>