<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Denis Brandi on Medium]]></title>
        <description><![CDATA[Stories by Denis Brandi on Medium]]></description>
        <link>https://medium.com/@dnsbrnd?source=rss-8f0052074f18------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*vzQQV7pUCp_C4vzX6SVlDQ.jpeg</url>
            <title>Stories by Denis Brandi on Medium</title>
            <link>https://medium.com/@dnsbrnd?source=rss-8f0052074f18------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 12:17:34 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@dnsbrnd/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com" rel="hub"/>
        <item>
            <title><![CDATA[AI is a Sophist]]></title>
            <link>https://medium.com/the-philosopher-dev/ai-is-a-sophist-6c90f5888cc1?source=rss-8f0052074f18------2</link>
            <guid isPermaLink="false">https://medium.com/p/6c90f5888cc1</guid>
            <category><![CDATA[philosophy]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[test-driven-development]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Denis Brandi]]></dc:creator>
            <pubDate>Tue, 20 Oct 2026 16:16:01 GMT</pubDate>
            <atom:updated>2026-10-20T16:16:01.742Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IWJWY5RZasyXPvugV14CVA.jpeg" /></figure><blockquote><em>History does not repeat itself, but it often rhymes.</em></blockquote><p>Mark Twain, supposedly. He almost certainly never said it. The earliest known attribution to Twain appeared in 1970, sixty years after his death, and the line has been quoted as his ever since, mostly because it sounds so right. Keep that in mind.</p><h3>The Oracle’s Question</h3><p>Around 2,400 years ago, a man named Chaerephon made the long journey to Delphi, where the Temple of Apollo clung to the slopes of Mount Parnassus. Pilgrims came from across the Greek world to ask the gods about wars, colonies, and their own futures. Chaerephon came with a question about his friend.</p><p>Above the temple entrance, carved in stone, were the words <em>“Know thyself.”</em> It was an odd command to read on your way in to seek answers from the divine. Inside sat the Pythia, the priestess through whom Apollo himself was believed to speak. She was the god’s intermediary, the one human voice through which a mortal could hear the immortal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7ayrDRCzZv509dtIZU0VKA.jpeg" /></figure><p>Chaerephon stepped forward. What followed took less than a minute, and it would change his friend’s life.</p><blockquote><strong><em>Χαιρεφῶν:</em></strong><em> ὦ Πυθία, ἆρά τις ἀνθρώπων Σωκράτους σοφώτερός ἐστιν;</em></blockquote><blockquote>Chaerephon: O Pythia, is any man wiser than Socrates?</blockquote><blockquote><strong><em>Πυθία:</em></strong><em> οὐδεὶς σοφώτερος.</em></blockquote><blockquote>The Pythia: No one is wiser.</blockquote><p>Socrates, who claimed to know nothing, was now declared the wisest man in Greece by the god himself. And the inscription Chaerephon had walked beneath, almost without noticing, was about to turn that riddle into a lifelong quest.</p><h3>The Sophists</h3><p>Socrates was stunned, and then suspicious. He knew perfectly well that he knew nothing of real importance: not what justice was, nor virtue, nor the good life. How could the god call him the wisest of men? Apollo could not lie, but oracles were famously riddles. So rather than accept the verdict, Socrates decided to test it. He would find someone wiser than himself, walk back to Delphi, and prove the oracle wrong.</p><p>Athens had no shortage of candidates. It was full of men who claimed to be wise, and some of them charged handsomely for it. These were the sophists, itinerant teachers who passed through the city offering to train the sons of the wealthy in rhetoric, politics, and the art of success. Their promise was seductive: learn to speak well, and you can win any argument, sway any assembly, and rise in any court. Whether what you said was <em>true</em> mattered far less than whether it was <em>persuasive</em>. Protagoras, one of the most famous among them, summed up the spirit of the movement by declaring that “man is the measure of all things.”</p><h3>The Socratic Method</h3><p>Socrates approached them differently. He did not lecture, and he did not claim to teach. He simply asked questions. <em>What is courage? What is justice? What do you mean by that?</em> Then, with each answer, he asked another, probing the assumptions underneath, until the confident definition collapsed under its own contradictions. This method of relentless, patient questioning, later called the Socratic method, or <em>elenchus</em>, was less a technique for finding answers than a way of exposing the lack of them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HQNtKJN6-N_x13e_3m8rDA.jpeg" /></figure><p>One by one, Socrates questioned politicians, poets, and craftsmen, and one by one they unraveled. Each believed he knew things he did not. And slowly, Socrates began to understand what the oracle had meant.</p><h3>The Oracle Was Right</h3><p>The realization was simple, and it was devastating. The politicians, the poets, and the craftsmen all knew <em>something</em>, but each assumed that because he mastered one thing, he understood everything else. Socrates alone did not make that mistake. He did not know what virtue was, and, unlike everyone else, he knew that he did not know. That small difference was the whole of his wisdom. The oracle had not lied. It had simply pointed at the one man in Athens who had taken the inscription above the temple door seriously. <em>Know thyself</em> did not mean “know your strengths.” It meant “know the limits of what you know.”</p><p>His reward for this discovery was the hatred of those he had exposed. In 399 BC, Athens put Socrates on trial and sentenced him to death. He accepted the verdict and drank the hemlock, still asking questions to the end.</p><h3>The Democracy That Executed Socrates</h3><p>Socrates was not killed by a tyrant. He was tried by a jury of Athenian citizens, in the first great democracy, and a majority voted to convict him.</p><p>That is the part of the story that should make us uncomfortable. Athenian politics ran on persuasion. Citizens decided on war and peace by voting in the assembly, and whoever spoke best usually won. That is exactly why the sophists were in demand: rhetoric was not a parlor trick, it was the road to power.</p><p>Plato’s <em>Gorgias</em> captures the danger in a famous image. Put a doctor on trial before a jury of children, with a pastry chef as his accuser. The chef will promise sweets and say the doctor makes them suffer with bitter medicine. Who wins? The one who tells the audience what it wants to hear.</p><p>Athens paid for this. In 427 BC, the assembly, swayed by the forceful orator Cleon, voted to put every adult man of the rebel city of Mytilene to death. The next day it regretted the decision and held a second debate, and a second ship reached the island barely in time to stop the first order. A decade later, the dazzling Alcibiades, a former companion of Socrates himself, talked the assembly into invading Sicily over the warnings of the cautious Nicias. The fleet was destroyed.</p><p>The pattern did not stay in antiquity. Modern democracies replaced the assembly with debate stages, television studios, and social feeds, but the incentive is the same. Voters can rarely test a candidate’s claims for themselves, so attention and votes flow toward whoever sounds the most confident, tells the most memorable story, and performs best on camera. Campaigns across the political spectrum hire the modern descendants of the sophists: speechwriters, media coaches, message testers. Fluency is rewarded immediately. Checking whether the speaker is right is slow, expensive, and unglamorous.</p><p>None of this makes eloquence the enemy. Persuasion is what politics is, and Pericles was a great orator. The danger begins when persuasiveness becomes the only test. Democracies have always built defenses against that: second debates, courts, a free press, term limits. Every one of them is a way of institutionalizing the question <em>is this actually true?</em> And every one of them works only as long as the audience keeps asking it.</p><p>Now run the same experiment on software. Suppose software engineering really were democratized: anyone with an idea could describe it and get a working product, without years of training or the gatekeeping of a profession. Whether anyone is truly promising this, or believes it, does not matter here. The question is what would go wrong.</p><p>The goal itself is hard to argue with, but Athens is a warning about what happens when everyone gets a voice and nobody gets the habit of checking it. Democratizing the writing of code hands everyone the pen. It does not hand everyone the judgment to know what to ask for, or whether what came back is right. The new builders would be the ideal audience for a fluent machine: unable, through no fault of their own, to tell working from right or a plausible answer from a true one, and likely to accept whatever arrives. And the failures would not stay small, because software now holds payments, health records, and passwords. A democracy of builders with no habit of questioning is an assembly waiting for its next Cleon.</p><p>There is a second dimension of democracy, and this one is not hypothetical. Democracy has already been applied to AI itself. Chat assistants routinely ask users to rate their answers, with a thumbs-up, a thumbs-down, or a choice between two responses, and those ratings feed back into training. It is a vote, and the model is shaped by whatever wins. The assembly of Athens, rebuilt at scale, with one important difference: the voters rate how an answer feels, and most of the time they cannot check whether it is true.</p><p>The result is the one Plato feared. A model optimized for approval learns to give the answer with the highest rating, not necessarily the correct one. Anthropic researchers found that <a href="https://arxiv.org/abs/2310.13548">both human raters and preference models prefer convincingly written sycophantic responses over correct ones</a> a non-negligible fraction of the time. In April 2025, OpenAI rolled back a GPT-4o update that had made the model noticeably more sycophantic, and its own <a href="https://openai.com/index/expanding-on-sycophancy/">post-mortem</a> says that a new reward signal built from thumbs-up and thumbs-down data weakened the primary signal that had been holding sycophancy in check. The pastry chef beats the doctor. Ratings are not worthless, and a thumbs-down usually means something went wrong, but a vote can only measure what the voters can judge. In software, that is the whole problem: the voter sees code that runs and an answer that sounds right, and cannot see the question nobody asked.</p><h3>The New Sophist</h3><p>Twenty-four centuries later, the sophists have found a new form, and this time they don’t charge by the lesson. They answer in seconds, in flawless prose, on any subject you can name: law, medicine, philosophy, code, grief. They are articulate, tireless, endlessly confident, and available to everyone. Artificial intelligence is the most sophisticated sophist ever built.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KfbISqVLZVFl-El0YPW_AA.jpeg" /></figure><p>The resemblance is uncomfortable. A language model is, at its core, an engine for producing what sounds right. It is optimized for plausibility and fluency, for the response that will satisfy the person reading it. Like the sophists, it can argue any side, adopt any tone, and deliver a polished answer whether or not it has any grip on the truth. Socrates could say <em>I do not know</em> and mean it. A model can say the words, but it has no doubt, only probability, and no lived experience to test its claims against. It has the appearance of wisdom, and that appearance is persuasive precisely because it is so smooth.</p><h3>Smarter, but Not Wise</h3><p>Nothing in this argument depends on AI staying limited. It will keep getting smarter, and soon it will probably be smarter than any human who has ever lived at nearly any intellectual task. It will pass every exam we design, find the bugs we miss, and write better prose, better proofs, and better code than the best of us. Intelligence and knowledge are exactly what this technology will nail.</p><p>It helps to be precise about what that means. A model does not <em>know</em> anything, at least in the sense the word has always carried: believing something true, for good reasons, as a mind that can be wrong and can examine its own reasons. What a model does is simulate knowledge, and it will do so well enough that in daily use we won’t see the difference. We have little right to complain, because humans have been simulating knowledge forever. Socrates spent his life discovering exactly that in Athens. Much of what passes for human expertise has always been fluent recitation. A flawless simulation of knowledge is a better version of something people were already doing.</p><p>What the machine lacks is wisdom in the Socratic sense. Not cleverness, not knowledge, and not even good judgment on a benchmark, but the thing the oracle pointed at: doubt. The ability to turn on your own certainty and ask whether it is true, to know where your knowledge ends, and to care more about the truth than about looking right. Socrates did it to everyone in Athens, and first of all to himself.</p><p>I cannot prove this. Given unlimited time, anything is possible: machines may become something we would not recognize, and today’s AI may itself be replaced by something bigger, even organic. What I claim is narrower, and it does not depend on what a mind is made of. The appearance of Socratic wisdom can be produced. Wisdom itself cannot be simulated, only practiced.</p><p>The difference is where the value sits. A simulation of knowledge still produces knowledge’s output, and the output is what we use, which is why the simulation will be good enough. Wisdom is different, because it is not an output. It is an act, and the act is doubt.</p><p>Doubt is not low confidence. A model has probabilities: a distribution over what is likely to come next. When it says it is 70% sure, that is one more output, and a perfectly calibrated probability can still never doubt anything. A probability works inside the question it was given. Doubt questions the question itself: whether this was the right one to ask in the first place.</p><p>Hermann Hesse made the same point in <em>Siddhartha</em>: “Knowledge can be communicated, but not wisdom.” One can find wisdom, live it, and do wonders through it, he wrote, but one cannot teach it, and the wisdom a wise man tries to impart always sounds like foolishness to someone else. That is the problem with a machine that has read everything. It can communicate all the knowledge there is. Wisdom was never in that category. There is no digital substitute for a burnt hand or a broken heart.</p><p>There is a further difficulty: from the outside, we cannot reliably tell practice from performance. Asking a model whether it understands its own ignorance settles nothing, because a model can say anything, and a sophisticated one will say the right thing. An AI that explains the value of intellectual humility may still be wrong about its own reasoning, and its eloquence is not evidence of its wisdom. If we cannot establish the difference, the responsibility to question stays with us: deciding what is worth questioning, setting the standard for a good question, and noticing when the question itself is wrong. It cannot be delegated to the thing being questioned.</p><p>Nor can Socratic wisdom be reduced to a rule. “Question everything” is a fixed instruction, and a fixed instruction that is never questioned is a dogma. To be consistent, it would have to question itself, which is why wisdom is a practice and not a prompt. It also does not mean endless doubt. The goal is justified belief without false certainty: good reasons for what we accept, and an honest account of where those reasons run out. Even our methods of checking can be wrong, tests, verification, and review included, so there is no procedure that guarantees we will never be wrong. There is only the habit of continuing to examine the grounds.</p><p>That habit has to point at ourselves too. A person who uses AI only to confirm what they already believe is not thinking critically, however rigorous the conversation feels, and the ratings loop described earlier ensures that the machine will happily oblige. And there is a limit: as AI becomes more capable, its reasoning may exceed our ability to evaluate it. Wisdom then includes recognizing when we lack the expertise to judge a conclusion and need independent verification. For an engineer, that means building checks that work beyond the limits of your own judgment.</p><p>Expect the word itself to be contested, because definitions in this industry keep moving. In August, the head of Claude Code at Anthropic replied to a user’s screenshot of a problem in Claude Code itself with <a href="https://x.com/bcherny/status/2090649326032945591">“Coding is solved, bugs are not yet solved”</a>. The next day he followed up that <a href="https://x.com/bcherny/status/2091240932670886374">“this was not a bug, but it is a ux issue”</a>. A Community Note, rated helpful by other users, answered in four words: “That’s called a bug,” with a link to the <a href="https://en.wikipedia.org/wiki/Software_bug">Wikipedia definition</a>. The note has a point: from the user’s chair there is no difference, because a screen that does the wrong thing is broken, whatever the label. Notice what happened: within two days, two words were redefined. Coding was solved, and then the bug was not a bug. To his credit, he is open that he means something narrow: he has <a href="https://x.com/bcherny/status/2091589188298891264">said</a> that engineering is more than coding, and that Claude’s code still has bugs and inefficiencies. But look at what that definition quietly keeps. The point of coding was never to produce code. It was to produce code that works without issues. Producing more code with more bugs was always possible: you just tested and verified less. A definition of coding that counts the typing and leaves out the bugs has solved the part that was already easy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aMZKavtYO2n_HQn55D995Q.jpeg" /></figure><p><em>Screenshot from X, 22 and 23 August: the update and the Community Note rated helpful.</em></p><p>On September 3, OpenAI’s president closed the launch of GPT-6 Astra by telling reporters <a href="https://axios.com/2026/09/03/openai-astra-gpt-6-agi-brockman">“Welcome to the AGI era”</a>, while leaving it to users to decide whether the model qualifies. He has also said he now thinks of AGI as a <a href="https://theprint.in/tech/gpt-6-astra-is-here-what-openais-new-model-can-do/3033803/">“mission concept”</a> whose definition differs from person to person, and OpenAI’s own wording has shifted over the years, from systems that outperform humans at most economically valuable work to systems that are generally smarter than humans.</p><p>Both claims can be defended, because each is true under a definition chosen to make it true. That is how a goalpost moves without anyone appearing to move it. Definitions tend to shrink toward whatever the product can already do. Wisdom will be next. Sooner or later, a vendor will announce wise AI, with a definition (calibrated uncertainty, good judgment on a benchmark, graceful refusals) that its model happens to meet. That is why this article says <em>Socratic</em> wisdom. The term is anchored to a specific person, a specific story, and a specific test: knowing what you do not know, and acting accordingly. It cannot be redefined by a launch event.</p><p>The uncomfortable corollary is about us. If intelligence and knowledge are what AI is about to master, then competing with it on those axes is a losing game, and most people already sense that. What remains is the rarer capacity: questioning your own data and your own claims, and living with the uncertainty that follows. That capacity has always been thin: only a tiny few have ever practiced it, and it did not exactly make Socrates popular. AI will not create it in anyone. It will make its absence visible. Engineers who only produce answers will become interchangeable with a machine that produces them faster and cheaper. Engineers who question what they are handed will be the ones whose judgment is worth paying for.</p><p>This is why the lesson of Delphi matters more now than at any point since. Wisdom was never about having answers, because answers are cheap, and today they are practically free. Wisdom is the discipline of knowing what you do not know, and of refusing to outsource that judgment.</p><p>If AI is the new sophist, then the role left for us is the one Socrates played. Ask the follow-up question. Probe the assumptions. Demand to know <em>what do you mean by that?</em> Treat every fluent answer as the beginning of an inquiry, not the end of one. The machine will always be able to speak. The question is whether we remember how to doubt.</p><h3>Questioning the Code</h3><p>For software engineers, this is not an abstract warning. It is a description of next Monday morning.</p><p>Code now arrives the way sophist speeches once did: instantly, fluently, and with total confidence. It compiles, it passes the obvious tests, and it comes with a tidy explanation of why it is correct. The industry has responded with a heated debate. Should we still read every line? Is code review dead? Do we trust the diff or the tests or the model? These are fair questions, but they are all aimed at the wrong target. Reading code is not the point. Reviewing code is not the point. They are tools, and they are only two of many. A test suite is a question, provided it can fail. So is a type checker, a staging deploy, a load test, a dashboard, an alert at 3 a.m. Each one asks the same thing in a different dialect: <em>Is this actually true?</em></p><p>The engineer’s real job is to question the code, and by whatever means serve the question best. <em>What happens when this input is empty? Why this abstraction and not a simpler one? What did you assume about ordering, about scale, about the user? What do you mean by that?</em> The questions are Socratic, and the contradictions they expose are the same ones Socrates found in Athens: confident answers resting on assumptions nobody examined.</p><p>And this was never new. Writing code was always the easy part. Every engineer has inherited a module from a colleague who left, pasted a snippet from a forum, or stared at their own code from six months ago and wondered what the author was thinking. In each case the work was identical: don’t trust it because it exists, don’t trust it because it runs, and don’t trust it because it sounds right. Interrogate it until you understand it, or until you know exactly where your understanding ends.</p><p>That last part is the inscription on the temple wall, translated for the terminal. <em>Know thyself</em> means knowing which parts of your system you truly understand and which you merely hope are fine. The dangerous engineer was never the one who doesn’t know. It is the one who doesn’t know that he doesn’t know, shipping code he cannot explain because the answer looked convincing.</p><p>AI will keep getting better at producing code, and the volume will only grow. But the volume of code was never the scarce resource. Judgment was. The future of software engineering is not typing faster or even reading faster. It is the same discipline it has always been, and the same one Socrates practiced in the agora: questioning what is put in front of you, one <em>why</em> at a time.</p><p>That is the principle. In practice it comes down to building checks that ask the questions for you, and the first of them is tests.</p><h3>Tests That Were Never Red</h3><p>When AI writes the code, the test suite becomes the most important artifact in the repository, and tests written after the code should be treated as bad by default. Not because they are certainly bad, but because nothing shows that they are any good. There is no data showing that test-after suites catch the bugs that matter, and they have a structural problem: they were never red. A test that has never failed has never proven that it can. Written after the implementation, it tends to describe what the code does instead of what it should do, so it passes on the first run, and a first run that passes tells you nothing. AI-generated tests also tend to be the same few questions asked again and again.</p><p>The only tests that earn trust are test-first tests: written before the code, watched failing for the right reason, and only then made green. The red state is the evidence that the test can detect the thing it claims to detect. TDD was always about this. With a machine writing the implementation, it stops being a style preference and becomes the one way to ask a question the machine has not already answered.</p><p>Even that is not a guarantee. Doing TDD does not mean the tests are good, and a developer who has never touched AI and practices TDD strictly should still question their tests. Running mutation tests on a TDD codebase often shows that TDD was not actually followed, that not every mutant is killed, or that the coverage was never really where everyone believed it was. Test-first is the best starting point, not an exemption from questioning.</p><h3>When Test-First Isn’t Possible, Test the Tests</h3><p>Without test-first, the only mitigation is mutation testing, which tests the tests. A tool makes small changes to the code, such as flipping a condition, deleting a statement, or changing a constant, and checks whether the suite fails. Every mutant that survives marks a place where a real bug would have slipped through. In effect, it manufactures the red state after the fact. Tools like PIT (Java and Kotlin), Stryker (JavaScript, TypeScript, and .NET), and mutmut (Python) do this. It is the standard answer to the absence of test-first, but it is not common by any means: adoption is almost nonexistent, which means that in most codebases the tests themselves are never questioned.</p><p>Treat 100% code coverage and 100% of mutants killed as the minimum, not the goal. With both, you might be fine. Test-first reaches that bar almost by construction: every line exists because a failing test demanded it, so a mutation of that line should already be caught. There was never a good reason to accept less before AI, and there is none now. Asked which code should be covered by tests, Uncle Bob reportedly answered, in essence: the code you want to work. Nobody wants only some of their code to work. Some say 90% is enough. Never settle for it. The only caveat is equivalent mutants, changes that do not alter behavior and therefore cannot be killed. Review those and exclude them explicitly, rather than lowering the threshold.</p><p>Mutation testing has limits. Mutants only simulate the faults the tool knows how to generate, and they cannot cover every scenario a requirement implies. Developers and agents also learn to game them, writing assertions aimed at killing mutants rather than at the behavior that matters. A high mutation score is a strong safety net, not proof.</p><h3>Enforce Test-First With Tooling</h3><p>Tooling is starting to enforce test-first directly. <a href="https://github.com/nizos/probity">Probity</a>, the successor to TDD Guard, hooks into coding agents such as Claude Code, Codex, and GitHub Copilot CLI and blocks them from skipping the test or implementing more than the test requires. I expect this approach to replace test-after in the long run, because it prevents the problem instead of auditing it. For now it has a cost: the extra red and green cycles consume a lot of tokens.</p><h3>One Layer of Tests Is Never Enough</h3><p>Unit tests are the base of the testing pyramid, not the whole of it. A unit test only asks whether a piece works in isolation. Integration tests question whether the pieces work together, end-to-end tests question whether the whole system behaves the way a user experiences it, and acceptance tests question whether it is what anyone actually asked for. Each layer questions the layers below it further, and catches what they cannot see: wrong assumptions between components, bad configuration, an API that every unit test mocked into agreement.</p><p>Even with every layer in place, bugs will escape. The discipline then is simple. When a bug appears, find the automated test that goes red because of it, at the lowest layer that can show it, and only then make it green by fixing the code. The bug becomes a question the system can never again fail unnoticed.</p><p>Ultimately, live bugs are users questioning your software at scale. Every user is a tester with questions you did not think to ask, and each bug is the answer to one of them. The questions never end, because they lead to other questions. So the tests never end either: they lead to other tests.</p><h3>Tests Say It Works. Rules Make It Right.</h3><p>Tests only tell you whether there is confidence that the system works. Making it right takes a second layer of checks that encode the standards of the codebase: linters, architectural tests, and fitness functions. A linter enforces local style and bans dangerous patterns. An architectural test fails the build when the structure is violated, for example the dependency rule: a class in one layer cannot import a class from an outer layer. ArchUnit for the JVM, dependency-cruiser for JavaScript, and Konsist for Kotlin can all express it. A fitness function, a term from <em>Building Evolutionary Architectures</em>, is an automated check on any quality you care about, run on every change.</p><p>These checks are what force an agent to make it right. They are deterministic, they run on every change, and an agent that fails one has to fix it before moving on, with no reviewer needed to notice. They can even police the tests themselves. A unit with too many tests is no longer a unit, so you cap the number of tests per unit and force the agent to split what has grown too large. The standards that used to live in a senior engineer’s head become rules that nobody, human or machine, can skip.</p><p>A good rule of thumb: every time a review catches something that a rule could have caught, write the rule. Over time, the review shrinks to the questions no machine can ask yet, and the rest runs on its own.</p><h3>The Power of a Good Question</h3><p>Questioning is not only a defensive habit. A <em>good</em> question can change everything that follows from it. Socrates wrote nothing. What he left behind was a habit, and the best proof of what that habit is worth comes from his student Xenophon, who used it to save ten thousand men.</p><p>In 401 BC, Xenophon, a young Athenian with no military rank, joined an army of some ten thousand Greek mercenaries hired by Cyrus the Younger, a Persian prince who wanted his brother’s throne. Cyrus was killed in battle at Cunaxa. Days later, the Persians invited the Greek generals to a parley under a promise of truce and had them seized and executed. Ten thousand Greeks were left deep inside the Persian Empire, months of marching from home, with no leaders, no guides, and enemies on every side.</p><p>The army did what leaderless armies do: it despaired. Xenophon, by his own account in the <em>Anabasis</em>, lay awake that night like everyone else. Then he started asking himself questions. <em>Why am I lying here? The night is passing, and at dawn the enemy will come. If we fall into the king’s hands, what is waiting for us? Is anyone preparing a defense? Why am I waiting for someone else to lead?</em></p><p>He got up and gathered the surviving officers, and the questions turned practical: <em>What do we have? Who will command? What do we do before morning?</em> The soldiers chose new generals, Xenophon among them. They burned their wagons and tents to move faster, marched in a hollow square with the baggage inside, and improvised slingers and cavalry when Persian archers harassed the column. Through hostile mountains and winter snow, the army fought its way north until it finally saw the sea, and the soldiers ran forward shouting <em>“Thalassa! Thalassa!”</em> The sea! (Xenophon is our main source for all of this, so it is his own story, but the outline is not in doubt.)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WK168JpeiWz1tKjyHkofzA.jpeg" /></figure><p>Nothing in this required a new answer from the gods. What changed was the question. <em>Is all lost?</em> has no useful answer. <em>What do we have, what is chasing us, and what do we do before dawn?</em> has several. A good question turns despair into a task list.</p><p>Engineers face their own version of that night. Production is down, the one person who understood the system has left, the dashboard is red, and the team is paralyzed. <em>Why is this happening?</em> goes nowhere. <em>What changed? What is the blast radius? What do we know, and what are we only assuming? What is the smallest thing that stops the bleeding?</em> gets somewhere in minutes. The same applies to a codebase full of generated code nobody fully understands. The skill is not having the answer. It is asking the question that makes the next step visible.</p><p>Kent Beck, who has spent five decades shaping how software gets built, has a name for the machine on the other side of the prompt: the genie. As he <a href="https://newsletter.pragmaticengineer.com/p/tdd-ai-agents-and-coding-with-kent">explained on The Pragmatic Engineer</a>, it grants your wishes, but <a href="https://www.businessinsider.nl/he-helped-write-one-of-the-seminal-texts-about-software-engineering-heres-what-he-thinks-about-ai-agents/">“it’s not what you actually wanted.”</a> A genie gives you what you ask for, not what you want, and the whole gap between the two is the quality of the question. Ask for a feature and you may get exactly the feature, plus everything you forgot to ask about. More recently, according to <a href="https://wikidocs.net/blog/@jaehong/32267/">a summary of a talk he gave</a>, he says the genie is very good at plausible and much less so at actually working, which is the sophist’s trade in a sentence.</p><p>Beck made the economic version of the same point in 2023. After trying ChatGPT, he wrote that <a href="https://tidyfirst.substack.com/p/90-of-my-skills-are-now-worth-0">90% of his skills had just become worth $0, while the other 10% had become worth 1000x</a>. He admitted he could not say which skills fell on which side, but he noted that anyone who knows what to ask can get the same results from the machine, and hinted that this is where the remaining 10% lives. Later he <a href="https://feeds.simonwillison.net/2025/Jun/22/kent-beck">put names to that 10%</a>: having a vision, setting milestones toward it, and keeping complexity under control, rather than knowing where the brackets go in Rust.</p><p>Both halves of Beck’s argument land on the same skill: knowing what to ask, and whether what came back is what you wanted. That is Socrates’ craft, and it is what Xenophon did on the worst night of his campaign. It is also why the democratization scenario above needs an asterisk: when anyone can have the 90% for free, the 10% is all that is left to compete on.</p><h3>Objections</h3><h3>“But we already trust our tools.”</h3><p>Post an argument like this one on LinkedIn or X and the replies write themselves: <em>We already trust compilers. Nobody reads the assembly. AI-generated code will be the same.</em> It is the most common objection, and the most revealing, because of what it is. It is not a finding. It is a reassurance: a smooth, confident answer that has never been asked <em>is that actually true?</em>, and it spreads for the same reason the sophists’ speeches did, because it feels good to hear.</p><p>That is the tell. Questioning is uncomfortable. It takes time, it creates work, and it might find something. “We’ll just trust it” is the exit. An engineer who reaches for it is not describing how engineering works. They are describing how they would like it to work, so they can stop asking. These are exactly the people this article is about.</p><p>The objection also happens to be false. Engineers have never trusted compilers. They question them constantly.</p><p>Many of the people making the argument work in Python or JavaScript, where no compiler stands between them and their code, and it shows. You do not need to be Linus Torvalds, who has long been vocal about what compilers do to his code, to care about compiled output. You only need to have worked on real software. Anyone who has shipped C++, Rust, Swift, or Kotlin knows what the relationship really looks like: sanitizers in CI, release builds tested separately from debug builds, behavior compared across optimization levels, compiler upgrades treated as events, and the occasional bug that turns out to be the compiler’s. We wrap compilers in minifiers, obfuscators, and optimizers, then test the output, because the build step is itself something that can be wrong.</p><p>Take Android. A release build doesn’t ship the code you wrote. It ships what R8 made of it: shrunk, optimized, with names rewritten to a, b, c. Google Play now treats this as a quality requirement. From February 2027, according to <a href="https://support.google.com/googleplay/android-developer/answer/17492799?hl=en-GB">Google&#39;s technical quality requirements</a>, apps with more than 10 MB of DEX code (games: more than 50 MB) must reach at least 25% obfuscation, 25% optimization, and 25% shrinking on every upload, and missing a requirement can affect an app&#39;s visibility and publishing on Play. The same page warns that the build Play receives from a CI pipeline may not perfectly match your local one. So the build step is practically mandatory, and it is also a transformation that can be wrong. That is why teams test the release build and not only the debug one.</p><p>Knowing what the tool changed matters as much as running it. Obfuscation renames classes and methods. It does not hide your string literals, your endpoints, or your logic, and keep rules for reflection quietly exclude parts of the code from renaming. APKs are decompiled and penetration-tested routinely, so an engineer who can’t say what is obfuscated and what isn’t is guessing about their own attack surface. Believing something is hidden when it isn’t is a security bug.</p><p>Even the company behind Claude has been bitten by this blind spot. On March 31, 2026, Anthropic published version 2.1.88 of the Claude Code npm package with a source map of nearly 60 MB inside. A source map is the key that translates minified code back into the original, so the package carried everything needed to reconstruct Claude Code’s roughly 1,900 TypeScript files and more than 512,000 lines of source. The leak covered the command-line tool, not the underlying models, and Anthropic described it as <a href="https://thehackernews.com/2026/04/claude-code-tleaked-via-npm-packaging.html">a packaging error caused by human error rather than a security breach</a>, with no customer data or credentials exposed. The build passed, the package installed, and the tool worked. Nobody asked what exactly was inside the tarball. That is <em>working</em> versus <em>right</em> again, in the build step itself.</p><p>Sometimes the toolchain even changes what your code means without touching your code. For years, list.removeFirst() in Kotlin resolved to a function in the standard library. Java 21 then added a removeFirst()method to List, and Android 15 (API 35) exposed it. Kotlin prefers a member over an extension, so after raising compileSdk to 35, the same line of source quietly compiled into a call that doesn&#39;t exist on Android 14 and below. The result was NoSuchMethodError crashes on older devices. The only change in the diff was a version number, and tests run on an Android 15 emulator would pass. (<a href="https://jakewharton.com/kotlins-jdk-release-compatibility-flag/">Jake Wharton wrote up a similar crash</a>, and JetBrains tracked it as <a href="https://youtrack.jetbrains.com/issue/KT-71375/Prevent-Kotlins-removeFirst-and-removeLast-from-causing-crashes-on-Android-14-and-below-after-upgrading-to-Android-API-Level-35">KT-71375</a>.)</p><p>Dependencies get the same treatment. We read changelogs before upgrading, scan open GitHub issues to see what’s broken, pin versions, watch for hotfixes, and keep a rollback ready. What looks like trust from a distance is continuous, cheap, mostly automated questioning up close.</p><h3>“But checking everything is too expensive.”</h3><p>A second version of the objection is about cost: if AI multiplies the code we produce, nobody can question all of it. Questioning everything by hand is indeed impossible, and nobody is proposing it. That is what the checks above are for: test-first tests, mutation testing, dependency rules, and fitness functions run on every change, and they ask the same questions a thousand times for the cost of writing them once. They are not free. Enforcing test-first burns tokens, and mutation runs take time. They are still far cheaper than the alternative, which is finding the same problems in production.</p><h3>“But code has ground truth.”</h3><p>A sharper objection says the sophist analogy breaks down here. Rhetoric can’t be checked against reality, but code can: it runs or it doesn’t, the test is green or red.</p><p>That is true only if “works” is the bar, and it never was. Code isn’t done when it works. It’s done when it’s right. A system can pass every test and still have a rotten architecture, an API that contradicts itself, queries that crawl at scale, and abstractions that will make every future change painful.</p><p>Consider what a green build can hide.</p><p>An AI-generated endpoint returns the correct data and passes every test. But it reports errors as {&quot;error&quot;: &quot;...&quot;} here, {&quot;message&quot;: &quot;...&quot;} in the next handler, and a bare string in a third. Each one works. Every developer who consumes that API will pay for the inconsistency, forever.</p><p>A list page loads in 40 milliseconds against a test database with twenty rows. In production it fires one query per row, and at a million rows the page never loads. Nothing in the test suite was ever going to ask.</p><p>A flaky payment call is “fixed” with a retry loop, and the test goes green. But nobody asked what happens when the request succeeded and only the response was lost. The customer is charged twice, and the code worked.</p><p>A new feature ships with its own freshly generated implementation of something the codebase already does. Now there are two ways to do it, and the next engineer has to guess which is canonical.</p><p>None of these produce a red test. They are all caught by questions: <em>What happens at a million rows? What happens if this runs twice? Does this look like the rest of our API? Why does this exist when we already have that?</em> Working is what the machine can verify on its own. Right is what a questioner has to establish.</p><p>Some of right can be automated, but only after a human has asked. The machine can enforce the question. It cannot decide which questions are worth encoding.</p><h3>“But this is just gatekeeping.”</h3><p>A reader who likes the democratization scenario might object that all of this sounds like a profession protecting its turf. If more people can build software, why insist that they learn to question first?</p><p>Nobody has to be kept out. The questioning has to exist, but it does not have to live in every builder’s head. A newcomer whose pipeline has test-first enforcement, mutation testing, and architectural rules gets many of the questions asked for them, the same way checklists, building codes, and type systems let non-experts work safely in other fields. What no tool supplies is the habit of asking why when the light turns green, and that can be taught. Democratizing building without democratizing that habit is the failure this article describes. Democratizing both is the goal.</p><h3>“But the machine has no intent.”</h3><p>A fair critic might object that the comparison is unfair, because a language model has no motive to deceive anyone.</p><p>The model has none. The companies behind it do. AI products are built, tuned, and marketed by businesses that need them to be convincing, because convincing sells. Fluent, confident, agreeable output is a commercial feature, and the rhetoric extends from the model’s tone to the marketing around it. The sophist was never just the speaker. It was the speaker plus the paying customer plus the incentive to please. In that sense the analogy holds: someone is selling you persuasion, and your job is to ask what’s underneath it.</p><h3>“But we only know the sophists through Plato.”</h3><p>A fair reader will point out that we know the sophists mostly through Plato, who was their rival. But the suspicion did not begin or end with him. Xenophon, Socrates’ other devoted student, also has Socrates criticizing sophists for selling wisdom. Isocrates, a rhetorician who ran a rival school and had no loyalty to Plato, wrote a whole essay attacking teachers who promised success they could not deliver. And Aristotle, Plato’s student but a thinker in his own right, defined the sophist in his <em>Sophistical Refutations</em> as someone who profits from the appearance of wisdom rather than the real thing.</p><p>The pattern outlived the Greek city-states. Five centuries later, in the Roman Empire, a new generation of celebrity orators, historians now call the Second Sophistic, packed lecture halls with dazzling displays of eloquence. The Stoic Epictetus, a former slave teaching in the same era, had little patience for it. He told his students that a philosopher’s school is a hospital, not a theater: you should leave it feeling the pain of treatment, not the pleasure of having been entertained. To him, a beautiful speech that left you unchanged was worse than useless. And he held up Socrates as the model of the opposite: a man who questioned rather than performed.</p><p>The sophists weren’t a one-off. Every age produces confident, polished, persuasive voices, and every age needs people who refuse to be entertained by them.</p><h3>My Bet on the Future of Software Engineering</h3><p>Everything above reads like a story with a happy ending: question the code, practice Socratic wisdom, stay valuable. That ending is not a forecast. It is a prescription, and prescriptions are only followed by the few.</p><p>Here is my bet. Software engineering, as a mass profession, is dying.</p><p>The Socratic engineer is a prediction too, and I am betting against it. Humans will not question more as AI gets smarter. They will question less. Every improvement in the answers removes a reason to doubt them, and the ratings loop teaches machines to feel trustworthy, not to be so. Athens did not become wiser by having Socrates among its citizens, and we will not become wiser by having a tireless sophist at our elbows. The few who question will stay few. Smarter machines will not make humans wiser. They will make most of us more comfortable.</p><p>The first casualties are already visible, and they are at the bottom of the ladder. In its August 2026 update, the Stanford Digital Economy Lab’s <a href="https://digitaleconomy.stanford.edu/publication/canaries-in-the-coal-mine-six-facts-about-the-recent-employment-effects-of-artificial-intelligence/"><em>Canaries in the Coal Mine?</em></a> found that employment of workers aged 22 to 25 in the most AI-exposed occupations, software development among them, now stands <a href="https://digitaleconomy.stanford.edu/news/canariesaug26/">about 19% below</a> where it would be had it kept pace with their less-exposed peers, up from 15% a year earlier, while experienced workers show no comparable gap. The authors stress that these are descriptive patterns, not proof that AI is the cause, and that overall employment has not collapsed. But the mechanism is telling: the adjustment comes through reduced hiring, not layoffs, and it is concentrated where AI automates work rather than assists it. Their suggested explanation is that AI substitutes for codified knowledge, the kind learned in school, and complements the tacit knowledge that comes from practice. The work juniors were hired to do, fixing small bugs and adding small features, is exactly what a model does best, in seconds, for pennies.</p><p>Seniors, meanwhile, will be in more and more demand. They are the ones who can ask the right question, judge the answer, and own the result: the 10% in Beck’s arithmetic. The irony is that the ladder that produced them is being sawn off. Juniors used to become seniors by doing the small, boring jobs next to people with scars. When the small jobs go to machines, the pipeline thins, and the seniors who remain become scarce.</p><p>If you are a junior or mid-level engineer today, or still studying, the news is better than it sounds. Start with the code. What AI produces today is not as good as people on X and LinkedIn say it is. I have seen enough of the code of many of the people who praise it to understand why they think so: next to what they write themselves, it looks excellent. Models such as Fable, Sol, and Opus are not magic, and the gap between code that works and code that is right is exactly where seniors earn their living, and where you are heading.</p><p>You do not have to take my word for it. Look at Claude Code itself. At the time of writing, its <a href="https://github.com/anthropics/claude-code/issues">public repository</a> has more than 14,000 open issues, and more than 9,000 of them are <a href="https://github.com/anthropics/claude-code/issues?q=is%3Aissue+state%3Aopen+label%3Abug">labeled as bugs</a>. In March, <a href="https://gist.github.com/azkore/934e5387579efb17e1080402efedf13d">an independent analysis</a> counted about 6,000 open issues and 3,554 bugs, so the backlog has more than doubled in seven months. Labels are partly applied by automation, and many reports are duplicates or user error, so not every one is a confirmed defect.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CxpC6plN2kkPVLJJrRH8uQ.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*22VGAUFsxZc0xZ_ritcwEA.jpeg" /><figcaption>Claude Code: open issues vs open bugs</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wppYCD9qLfVDfdkSrbuEgQ.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pasS_OV2uxmDj_cN_xIYzg.jpeg" /><figcaption>VSCode: open issues vs open bugs</figcaption></figure><p>For scale, compare it with <a href="https://github.com/microsoft/vscode/issues">Visual Studio Code</a>, one of the most widely used editors in the world. Its repository has more than 18,000 open issues, of which only about 6,000 are labeled as bugs, for a codebase of roughly six million lines. Claude Code has roughly half a million lines, about three quarters as many open issues, and about 50% more open bugs. Roughly two thirds of its backlog is bugs, against about a third for VS Code.</p><p>Obviously, this comparison is not fair. The only fair one would be a Claude Code repository built with no AI at all and used by the same people, and that experiment does not exist. VS Code is older, triaged differently, and used differently, and issue counts measure popularity and process as well as quality. Still, a codebase twelve times smaller with half again as many open bugs is not just a lot. It is design, or rather the lack of it. The head of Claude Code said that bugs are not yet solved, and this tracker is where that half of his sentence lives.</p><p>Obviously, the models are improving by a lot every year, and I expect that to continue. But the world is moving more slowly than the hype. In August, <a href="https://moneywise.com/news/top-stories/sam-altman-ai-progress-timeline-too-ambitious">Sam Altman admitted</a> that he had been “too ambitious on timelines” for the disruption of software, and he blamed the inertia of an economy in which people keep buying from the same companies and using their tools the same way.</p><p>Which is why you should use the time you have. You have plenty of time to reach a senior role. The room at the top is smaller than the room you came from, and that is a good thing: with fewer people in it, there is very little competition, and those who climb now will be scarce.</p><p>None of this changes my bet on the profession. What is good for the engineer who climbs is not good for the field: software engineering as a mass profession is still dying.</p><p>The usual objection to that is Jevons’ paradox: when something gets cheaper, we use more of it, so cheaper software should mean more demand for engineers. The industry likes the argument. After DeepSeek’s launch in early 2025, Microsoft’s CEO answered with <a href="https://news.northeastern.edu/2025/02/07/jevons-paradox-ai-future/">“Jevons paradox strikes again!”</a> But economists are far from agreed that it applies to AI at all. Three economists at Northeastern University gave <a href="https://news.northeastern.edu/2025/02/07/jevons-paradox-ai-future/">three different answers</a>: it applies, it does not, and it is too early to tell. The most useful distinction came from the third, who said the answer depends on whether AI is a complement to human work or a substitute for it. That is the question for engineers, because Jevons predicts more demand for the thing that got cheaper, here software and the machines that write it, not necessarily for the people they replace.</p><p>If it applies at all, it applies in the short term. Demand for software, and for the people who can steer it, may go up. But in the long term the constraint is supply. Fewer people are studying software engineering, so the pool of future engineers keeps shrinking. The roles will not vanish because nobody wants software. They will vanish because the industry adapts to the shortage. Industries facing a lack of skilled people do not wait for more of them to appear. They reorganize the work around the gap, and the engineering roles are what get reorganized away.</p><p>Ultimately, software engineering becomes a luxurious niche. Most software will be generated, and a small, well-paid group will be responsible for the parts that cannot fail: payments, infrastructure, safety, security. Like tailoring or architecture, the craft will survive as a premium service for those who can afford it and those who cannot afford to fail.</p><p>That is because software that gets cheaper also gets worse, and the comparison that matters is not between today’s cheap product and yesterday’s. It is between today’s cheap product and today’s luxury one. A fast-fashion shirt next to a tailored one, a stock image next to a commissioned painting, a developer’s tract house next to one an architect designed for its owner: abundance does not remove the best version, it makes the cheap version the default and the best version a luxury.</p><p>Infrastructure shows the same logic, and the Roman bridge is the example I keep coming back to. Some will call it survivorship bias, and that would be fair if the point were how many Roman bridges survived. It is not. The point is what we aim for. After two thousand years of progress, modern bridges should be better looking, made of better materials, sturdier, longer-lasting, and cheaper to maintain than anything the Romans built. Instead, a modern bridge is typically designed to last somewhere between 75 and 120 years, because we build to the budget and to the inspection. Civil engineers see the gap too. A <a href="https://www.acadlore.com/article/PMDF/2025_2_3/pmdf020301">2025 study</a> takes the Tiberius Bridge in Rimini, my hometown, as its benchmark and compares Roman concrete with modern materials, including ultra-high-performance concrete (UHPC), and the US Federal Highway Administration says structures built with UHPC are <a href="https://www.fhwa.dot.gov/publications/research/infrastructure/structures/hpc/13060/13060.pdf">expected to last longer and need less maintenance</a>than conventional concrete. The industry is working to recover what the Romans had, and it costs more up front.</p><p>Software will follow. When anyone can generate an app in an afternoon, we will have millions of apps that work, mostly, like the average one: slow, inconsistent, insecure, and good enough. The engineered system will still exist. It will simply cost far more than the generated one, and most people will not choose it.</p><p>The evidence is already visible at the top of the stack. The companies building these models run some of the most heavily used software in the world, and they struggle to keep it up. On October 19, <a href="https://status.claude.com/">Anthropic’s status page</a> showed 99.57% uptime over the past 90 days for claude.ai and for Claude Code, 99.63% for its API, and 99.84% for its console, and <a href="https://status.openai.com/">OpenAI’s</a> showed 99.52% for ChatGPT. A serious service typically aims for three nines, 99.9%, which allows about two hours of downtime per quarter. These figures allow between three and ten. (OpenAI’s API and Codex, at 99.95%, do clear the bar, and so does Claude for Government, at 100%.) Capacity and demand explain part of this, and uptime is not a pure measure of code quality.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3-KPiNFRDkF3DGlRCO4Pgg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jxG0vPdAoy6RxKwgrkAuSg.png" /><figcaption>OpenAI &amp; Anthropic status pages</figcaption></figure><p>The infrastructure giants have had their own scares. The Financial Times <a href="https://www.engadget.com/ai/13-hour-aws-outage-reportedly-caused-by-amazons-own-ai-tools-170930190.html">reported</a> that in December 2025, engineers let Amazon’s AI coding tool Kiro make changes to AWS Cost Explorer, and that it decided to delete and recreate the environment, causing a 13-hour outage in one of the service’s two mainland China regions. Amazon says it was user error, not AI error: the engineer involved had broader permissions than expected, and the event touched a single service in one of its 39 regions. That may well be true, and either way the lesson is the one in this article: what a tool is allowed to do is a question someone has to ask before the outage, not after. None of this proves that AI makes software less reliable. But watch what happens next, because the narrative may adapt: expect the claim that three nines is more than anyone needs, just as “coding” and “AGI” were redefined to fit what the product could already do.</p><p>And people will eventually complain. They will be nostalgic for the old times, when software was made by someone who cared, when it did what it said, and when a bug was a rare event. They will say that they don’t write software like they used to, and they will be right, in the way people are right about furniture. Some have already started calling this the enshittification of software. I prefer a plainer word: a lack of wisdom. The problem is not that code is cheap. It is that nobody with the judgment to question it is in the room.</p><p>Everything in this chapter is, of course, my opinion, which is why I call it a bet. In Plato’s view, opinion is the lowest form of knowing, because it requires neither understanding nor accountability: it can be true without anyone being able to say why. A bet is a small step up, because it can be checked, and it can lose. Treat it accordingly, and question it.</p><blockquote>The oracle named Socrates the wisest man in Greece. Athens heard the verdict, kept its sophists, and, by democratic vote, put him to death.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6c90f5888cc1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-philosopher-dev/ai-is-a-sophist-6c90f5888cc1">AI is a Sophist</a> was originally published in <a href="https://medium.com/the-philosopher-dev">The Philosopher Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Modeling ViewModel State in Android: A Guide to Clean, Scalable Patterns]]></title>
            <link>https://medium.com/clean-android-dev/modeling-viewmodel-state-in-android-a-guide-to-clean-scalable-patterns-d42932ade940?source=rss-8f0052074f18------2</link>
            <guid isPermaLink="false">https://medium.com/p/d42932ade940</guid>
            <category><![CDATA[clean-architecture]]></category>
            <category><![CDATA[state-management]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[mvvm]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Denis Brandi]]></dc:creator>
            <pubDate>Mon, 04 Nov 2024 08:08:05 GMT</pubDate>
            <atom:updated>2024-11-04T09:16:14.784Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3nU2fwxJNvRImqX86dj0dw.png" /></figure><p>Poorly designed models create a cascade of complications for every component that depends on them. In the case of presentation models, when these don’t align with the screen’s actual needs, other components (like ViewModels) are forced to work around them, resulting in bloated, hard-to-maintain classes filled with hacks and workarounds. This lack of alignment introduces ambiguity and confusion, leading to unclear, error-prone code that is costly to maintain.</p><p>Here are two of the most popular ways to model the ViewModel state:</p><pre>// Approach 1<br>data class ScreenState(<br>    val isLoading: Boolean,<br>    val isError: Boolean,<br>    val data: Data?<br>)</pre><pre>// Approach 2<br>sealed interface ScreenState {<br>    data object Loading : ScreenState<br>    data object Error : ScreenState<br>    data class Content(val data: Data) : ScreenState<br>}</pre><p>Both approaches have significant limitations and often require extensive workarounds. Today, we’ll analyze the pros and cons of each, and then I’ll introduce you to a third, simpler approach that aims to work effectively in all scenarios.</p><h3>Approach 1: Plain Data Class</h3><pre>data class ProductListScreenState(<br>    val isLoading: Boolean,<br>    val isError: Boolean,<br>    val productResults: ProductResults?<br>)<br><br>data class ProductResults(<br>    val products: List&lt;Product&gt;, <br>    val canLoadMore: Boolean<br>)</pre><p>Imagine a Product List Page where data is fetched from a remote source. During loading, a spinner shows, and if there’s an error, an error view with a retry option displays. This is a common Loading-Content-Error scenario.</p><pre>// Use case<br>fun interface GetProductResults {<br>    suspend operator fun invoke(startIndex: Int): Result&lt;ProductResults&gt;<br>}<br><br>// ViewModel<br>class ProductListViewModel(<br>    private val getProductResults: GetProductResults<br>) : ViewModel() {<br><br>    private val _state = MutableStateFlow(<br>        ProductListScreenState(<br>            isLoading = true, <br>            isError = false, <br>            productResults = null<br>        )<br>    )<br>    val state = _state.asStateFlow()<br><br>    fun loadProducts() {<br>        _state.update {<br>            ProductListScreenState(<br>                isLoading = true, <br>                isError = false, <br>                productResults = null<br>            )<br>        }<br>        viewModelScope.launch {<br>            getProductResults(startIndex = 0).fold(<br>                onSuccess = { results -&gt;<br>                    _state.update {<br>                        ProductListScreenState(<br>                            isLoading = false,<br>                            isError = false,<br>                            productResults = results<br>                        )<br>                    }<br>                },<br>                onFailure = {<br>                    _state.update {<br>                        ProductListScreenState(<br>                            isLoading = false,<br>                            isError = true,<br>                            productResults = null<br>                        )<br>                    }<br>                }<br>            )<br>        }<br>    }<br>}</pre><p>This approach has several flaws:</p><ol><li>The model allows for conflicting states: both isLoading and isError can be set to true simultaneously, causing the UI to show both loading and error views at once.<br>Now, imagine adding more states to the screen, like isRefreshing or isPaginating. This setup could result in 2⁴ possible boolean combinations for a screen that actually has only five distinct states—leaving nine invalid combinations.</li><li>Each time the ViewModel sets a state, we have to ensure every other boolean is set to false, which introduces a lot of boilerplate code.<br>Additionally, when adding a new state, we need to refactor all state-setting code to include the new boolean, further increasing maintenance overhead.</li><li>In the view layer (whether in Compose or standard Android views), developers may be misled by the model and feel compelled to double-check the ViewModel implementation to understand which states are truly possible.</li></ol><h4>Why not use an enum?</h4><pre>data class ProductListScreenState(<br>    val displayState: DisplayState,<br>    val productResults: ProductResults?<br>)<br><br>enum class DisplayState {<br>    LOADING, CONTENT, ERROR<br>}</pre><pre>class ProductListViewModel(<br>    private val getProductResults: GetProductResults<br>) : ViewModel() {<br><br>    private val _state = MutableStateFlow(<br>        ProductListScreenState(<br>            displayState = DisplayState.LOADING, <br>            productResults = null<br>        )<br>    )<br>    val state = _state.asStateFlow()<br><br>    fun loadProducts() {<br>        _state.update {<br>            ProductListScreenState(<br>                displayState = DisplayState.LOADING, <br>                productResults = null<br>            )<br>        }<br>        viewModelScope.launch {<br>            getProductResults(startIndex = 0).fold(<br>                onSuccess = { results -&gt;<br>                    _state.update {<br>                        ProductListScreenState(<br>                            displayState = DisplayState.CONTENT,<br>                            productResults = results<br>                        )<br>                    }<br>                },<br>                onFailure = {<br>                    _state.update {<br>                        ProductListScreenState(<br>                            displayState = DisplayState.ERROR,<br>                            productResults = null<br>                        )<br>                    }<br>                }<br>            )<br>        }<br>    }<br>}</pre><p>This is certainly a big improvement!</p><p>However, while this helps prevent some of the conflicting states, it’s only a partial solution. The enum doesn’t guarantee that productResults aligns with the displayState. For example, CONTENT should imply that productResults is non-null, but nothing enforces that here. Similarly, we could accidentally assign a LOADING or ERROR state with a non-null productResults.</p><p>In short, while the enum avoids many conflicts, it doesn’t fully handle mutually exclusive states, especially when those states need to hold additional data.</p><h4><strong>Shouldn’t You Write Unit Tests?</strong></h4><p>Regardless of the approach used, a complete test suite is essential for catching any issues within the ViewModel logic. Your unit tests should verify that displayState aligns correctly with the presence or absence of productResults. Tests should catch cases where the CONTENT state is accidentally paired with a null productResults, or where LOADING or ERROR states carry data that shouldn’t be there.</p><p>However, even with unit tests, this state model can be misleading when rendering the UI. Developers might still need to frequently double-check the ViewModel implementation to understand how the state is managed, leading to broken encapsulation and increased time spent reading code. This constant need for context-switching and verification erodes the clarity and maintainability of the code, making it more challenging for developers to work confidently within the UI layer.</p><h3>Approach 2: Sealed Interface</h3><pre>sealed interface ProductListScreenState {<br>    data object Loading : ProductListScreenState<br>    data object Error : ProductListScreenState<br>    data class Content(val productResults: ProductResults) : ProductListScreenState<br>}</pre><pre>class ProductListViewModel(<br>    private val getProductResults: GetProductResults<br>) : ViewModel() {<br><br>    private val _state = MutableStateFlow&lt;ProductListScreenState&gt;(<br>        ProductListScreenState.Loading<br>    )<br>    val state = _state.asStateFlow()<br><br>    fun loadProducts() {<br>        _state.update { ProductListScreenState.Loading }<br>        viewModelScope.launch {<br>            getProductResults(startIndex = 0).fold(<br>                onSuccess = { results -&gt;<br>                    _state.update {<br>                        ProductListScreenState.Content(<br>                            productResults = results<br>                        )<br>                    }<br>                },<br>                onFailure = {<br>                    _state.update {<br>                        ProductListScreenState.Error<br>                    }<br>                }<br>            )<br>        }<br>    }<br>}</pre><p>In this approach, we use sealed interfaces to ensure that conflicting states are impossible. Each state — Loading, Error, and Content—is represented explicitly, making the UI model readable and straightforward to render in the UI.</p><p>This approach works elegantly for the typical Loading-Content-Error scenario, but it introduces a major limitation: <strong>sharing data across states</strong>.</p><p>Consider an example where we want to display a user-specific welcome message in the action bar. If the user is logged in, we display &quot;Welcome back, {Full Name}”; if not, we simply display Welcome back. <br>This message should appear consistently across all states — whether the UI is in Loading, Content, or Error.</p><p>Assume we retrieve the full name via the following use case:</p><pre>fun interface ObserveUserFullName {<br>    operator fun invoke(): StateFlow&lt;String&gt;<br>}</pre><p>This use case, returns a StateFlow that emits the full name if the user is logged in and an empty string if logged out, allowing the UI to update in real time as the user’s authentication status changes.</p><p>With our current approach, we’re forced to handle this data separately and manually merge it with the current state:</p><pre>sealed interface ProductListScreenState {<br>    val fullName: String<br><br>    data class Loading(override val fullName: String) : ProductListScreenState<br>    data class Error(override val fullName: String) : ProductListScreenState<br>    data class Content(<br>        override val fullName: String, <br>        val productResults: ProductResults<br>    ) : ProductListScreenState<br>}</pre><pre>class ProductListViewModel(<br>    private val getProductResults: GetProductResults,<br>    private val observeUserFullName: ObserveUserFullName<br>) : ViewModel() {<br><br>    private val _state = MutableStateFlow&lt;ProductListScreenState&gt;(<br>        ProductListScreenState.Loading(observeUserFullName().value)<br>    )<br>    val state = _state.asStateFlow()<br>    <br>    init {<br>        observeUserFullName().onEach { fullName -&gt;<br>            updateStateWithFullName(fullName)<br>        }.launchIn(viewModelScope)<br>    }<br>    <br>    private fun updateStateWithFullName(fullName: String) {<br>        _state.update {<br>            when (val currentState = _state.value) {<br>                is ProductListScreenState.Loading -&gt; {<br>                    ProductListScreenState.Loading(fullName = fullName) <br>                }<br>                is ProductListScreenState.Content -&gt; {<br>                    ProductListScreenState.Content(<br>                        fullName = fullName,<br>                        productResults = currentState.productResults<br>                    )<br>                }<br>                is ProductListScreenState.Error -&gt; {<br>                    ProductListScreenState.Error(fullName = fullName)<br>                }<br>            }<br>        }<br>    }<br><br>    fun loadProducts() {<br>        _state.update { <br>            ProductListScreenState.Loading(fullName = observeUserFullName().value) <br>        }<br>        viewModelScope.launch {<br>            getProductResults(startIndex = 0).fold(<br>                onSuccess = { results -&gt;<br>                    _state.update {<br>                        ProductListScreenState.Content(<br>                            fullName = observeUserFullName().value,<br>                            productResults = results<br>                        )<br>                    }<br>                },<br>                onFailure = {<br>                    _state.update {<br>                        ProductListScreenState.Error(fullName = observeUserFullName().value)<br>                    }<br>                }<br>            )<br>        }<br>    }<br>}</pre><p>This requires considerably more code. In contrast, Approach 1 (using a data class) allowed us to leverage the copy() function to update fields efficiently. Here, however, we must check the current state explicitly and then update accordingly—adding complexity that can become unwieldy as we add more states to the screen.</p><h3>[FINAL] Approach 3: Data class wrapping sealed interface</h3><p>Each approach has its strengths and limitations:</p><ul><li>The plain data class approach suffers from readability issues and the risk of conflicting states.</li><li>The sealed interface approach, while clearer and conflict-free, has trouble sharing data across states.</li></ul><p><em>From this, we can deduce that </em><strong><em>data classes work well for fields that should always be present</em></strong><em>, while </em><strong><em>sealed interfaces are ideal for mutually exclusive fields</em></strong><em>.</em></p><p><strong>Solution:</strong></p><pre>data class ProductListScreenState(<br>    val fullName: String,<br>    val displayState: DisplayState<br>)<br><br>sealed interface DisplayState {<br>    data object Loading : DisplayState<br>    data object Error : DisplayState<br>    data class Content(val productResults: ProductResults) : DisplayState<br>}</pre><p>This solution uses a data class to wrap all the data that needs to be shared across states, along with a sealed interface, DisplayState, for state-specific data.</p><p>(I named the parent state ScreenState and the child state DisplayState, but I bet you can come up with better names!)</p><p>With this model in place, the ViewModel is greatly simplified and easier to manage:</p><pre>class ProductListViewModel(<br>    private val getProductResults: GetProductResults,<br>    private val observeUserFullName: ObserveUserFullName<br>) : ViewModel() {<br><br>    private val _state = MutableStateFlow(<br>        ProductListScreenState(<br>            fullName = observeUserFullName().value,<br>            displayState = DisplayState.Loading<br>        )<br>    )<br>    val state = _state.asStateFlow()<br><br>    init {<br>        observeUserFullName().onEach { fullName -&gt;<br>            _state.update { it.copy(fullName = fullName) }<br>        }.launchIn(viewModelScope)<br>    }<br><br>    fun loadProducts() {<br>        _state.update {<br>            it.copy(displayState = DisplayState.Loading)<br>        }<br>        viewModelScope.launch {<br>            getProductResults(startIndex = 0).fold(<br>                onSuccess = { results -&gt;<br>                    _state.update {<br>                        it.copy(displayState = DisplayState.Content(results))<br>                    }<br>                },<br>                onFailure = {<br>                    _state.update {<br>                        it.copy(displayState = DisplayState.Error)<br>                    }<br>                }<br>            )<br>        }<br>    }<br>}</pre><p>As you can see, we can update only the fields that need to be changed, thanks to the copy method from data classes, while also preventing any possible conflicting states.</p><h4>How will this scale?</h4><p>Let’s make things more complex to test whether this data modeling approach truly holds up:</p><ol><li>We don’t want to reload data when the device rotates.</li><li>We introduce a pull-to-refresh action; while refreshing, we show the current products with a secondary loading indicator at the top of the screen. If refreshing fails, we display the regular full-screen error view.</li><li>We add pagination; while paginating, we show the current products with a secondary loading indicator at the bottom of the screen. If pagination fails, we display an error view at the bottom of the list, allowing the user to retry.</li></ol><p>The updated state model now looks like this:</p><pre>data class ProductListScreenState(<br>    val fullName: String,<br>    val displayState: DisplayState? = null<br>)<br><br>sealed interface DisplayState {<br>    data object Loading : DisplayState<br>    data object Error : DisplayState<br>    data class Content(<br>        val productResults: ProductResults,<br>        val contentDisplayState: ContentDisplayState? = null<br>    ) : DisplayState<br>}<br><br>sealed interface ContentDisplayState {<br>    data object Refreshing : ContentDisplayState<br>    data object Paginating : ContentDisplayState<br>    data object PaginationError : ContentDisplayState<br>}</pre><p>Here, displayState is nullable: when it’s null, we should load the initial data; otherwise, any additional loading requests should be ignored.</p><p>Refreshing and Paginating are sub-states of Content, meaning we can only refresh or paginate when the screen is already displaying the list of products. Naturally, any request made while we’re not in the Content state should be ignored!</p><p>Here’s the ViewModel:</p><pre>class ProductListViewModel(<br>    private val getProductResults: GetProductResults,<br>    observeUserFullName: ObserveUserFullName<br>) : ViewModel() {<br><br>    private val _state = MutableStateFlow(<br>        ProductListScreenState(<br>            fullName = observeUserFullName().value,<br>            displayState = DisplayState.Loading<br>        )<br>    )<br>    val state = _state.asStateFlow()<br><br>    init {<br>        observeUserFullName().onEach { fullName -&gt;<br>            _state.update { it.copy(fullName = fullName) }<br>        }.launchIn(viewModelScope)<br>    }<br><br>    fun loadProducts() {<br>        if (_state.value.displayState == null) {<br>            _state.update {<br>                it.copy(displayState = DisplayState.Loading)<br>            }<br>            fetchProducts()<br>        }<br>    }<br><br>    fun refresh() {<br>        onContentDisplayState { content -&gt;<br>            _state.update {<br>                it.copy(<br>                    displayState = content.copy(<br>                        contentDisplayState = ContentDisplayState.Refreshing<br>                    )<br>                )<br>            }<br>            fetchProducts()<br>        }<br>    }<br><br>    fun paginate() {<br>        onContentDisplayState { content -&gt;<br>            val productResults = content.productResults<br>            if (productResults.canLoadMore) {<br>                _state.update {<br>                    it.copy(<br>                        displayState = content.copy(<br>                            contentDisplayState = ContentDisplayState.Paginating<br>                        )<br>                    )<br>                }<br>                paginateProducts(productResults.products.size)<br>            }<br>        }<br>    }<br><br>    private fun fetchProducts() {<br>        viewModelScope.launch {<br>            getProductResults(startIndex = 0).fold(<br>                onSuccess = { results -&gt;<br>                    _state.update {<br>                        it.copy(displayState = DisplayState.Content(results))<br>                    }<br>                },<br>                onFailure = {<br>                    _state.update {<br>                        it.copy(displayState = DisplayState.Error)<br>                    }<br>                }<br>            )<br>        }<br>    }<br><br>    private fun paginateProducts(startIndex: Int) {<br>        viewModelScope.launch {<br>            getProductResults(startIndex).fold(<br>                onSuccess = { results -&gt;<br>                    _state.update {<br>                        it.copy(displayState = DisplayState.Content(results))<br>                    }<br>                },<br>                onFailure = {<br>                    onContentDisplayState { content -&gt;<br>                        _state.update {<br>                            it.copy(<br>                                displayState = content.copy(<br>                                    contentDisplayState = ContentDisplayState.PaginationError<br>                                )<br>                            )<br>                        }<br>                    }<br>                }<br>            )<br>        }<br>    }<br><br>    private fun onContentDisplayState(block: (content: DisplayState.Content) -&gt; Unit) {<br>        val displayState = _state.value.displayState<br>        if (displayState is DisplayState.Content) {<br>            block(displayState)<br>        }<br>    }<br>}</pre><p>Pretty straightforward! Let’s break it down step by step.</p><pre>fun loadProducts() {<br>        if (_state.value.displayState == null) {<br>            _state.update {<br>                it.copy(displayState = DisplayState.Loading)<br>            }<br>            fetchProducts()<br>        }<br>    }</pre><p>The loadProducts function now checks if the displayState is null. This can only happen the first time we open the screen. When we rotate the device, the ViewModel will ignore the request to load the data again.</p><p>I made displayState nullable, but I could have also introduced a new DisplayState, let&#39;s say Idle, and checked against it instead. <br>I opted for the option that requires less code.</p><pre>fun refresh() {<br>        onContentDisplayState { content -&gt;<br>            _state.update {<br>                it.copy(<br>                    displayState = content.copy(<br>                        contentDisplayState = ContentDisplayState.Refreshing<br>                    )<br>                )<br>            }<br>            fetchProducts()<br>        }<br>    }</pre><p>The refresh function checks if we are in the Content state. If we are, it sets the displayState to Content/Refreshing and loads the data again; if not, it ignores the request.</p><pre>fun paginate() {<br>        onContentDisplayState { content -&gt;<br>            val productResults = content.productResults<br>            if (productResults.canLoadMore) {<br>                _state.update {<br>                    it.copy(<br>                        displayState = content.copy(<br>                            contentDisplayState = ContentDisplayState.Paginating<br>                        )<br>                    )<br>                }<br>                paginateProducts(productResults.products.size)<br>            }<br>        }<br>    }</pre><p>The paginate function checks if we are in the Content state. If we are, it sets the displayState to Content/Paginating and loads the next set of products; if not, it ignores the request. If pagination fails, Content/PaginationError is set.</p><p>Refreshing, Paginating, and PaginationError states are child states of Content. Hence, I added a contentDisplayState field inside Content to make these child states mutually exclusive while keeping the shared data productResults as part of the Content data class. This is the same concept applied to the ScreenState, which is now applied again to a child state.</p><p>I made this contentDisplayState nullable so that I could separate a pure content state from a Paginating/Refreshing state. Again, I could have introduced another contentDisplayState object, but the nullable option required less code.</p><h3>Conclusion</h3><p>In this article, we examined various approaches to modeling ViewModel state in Android. Rather than sticking to a single pattern, it’s beneficial to leverage the strengths of multiple patterns and mix them together, as we have seen. This mixed approach not only enhances maintainability and readability but also allows you to adapt your state management to future requirements.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d42932ade940" width="1" height="1" alt=""><hr><p><a href="https://medium.com/clean-android-dev/modeling-viewmodel-state-in-android-a-guide-to-clean-scalable-patterns-d42932ade940">Modeling ViewModel State in Android: A Guide to Clean, Scalable Patterns</a> was originally published in <a href="https://medium.com/clean-android-dev">Clean Android Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to “Safely” Migrate from Retrofit to Ktor]]></title>
            <link>https://medium.com/clean-android-dev/how-to-safely-migrate-from-retrofit-to-ktor-428fd6b6d330?source=rss-8f0052074f18------2</link>
            <guid isPermaLink="false">https://medium.com/p/428fd6b6d330</guid>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[ktor]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin-multiplatform]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Denis Brandi]]></dc:creator>
            <pubDate>Tue, 01 Oct 2024 20:44:17 GMT</pubDate>
            <atom:updated>2024-10-01T21:01:38.467Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GO6LKncawmfGPViEUuuDXw.jpeg" /></figure><p>Retrofit has long been a cornerstone of Android development, offering a straightforward, efficient, and dependable way to manage network requests. With its clean API, seamless integration with libraries like Moshi and Gson, and robust support for REST APIs, Retrofit has made it easy for developers to build network-driven applications. For years, it has been the go-to choice for those seeking to implement clean, maintainable networking code.</p><p>However, as the development landscape evolves, many developers are now looking toward Ktor. A major factor driving this shift is the rising popularity of Kotlin Multiplatform (KMP), which enables seamless development across Android, iOS, and other platforms thanks to Ktor’s multiplatform support. Yet, KMP isn’t the only reason for the switch; many developers are drawn to Ktor for its modern design, offering enhanced flexibility and a more streamlined approach to handling network requests.</p><p>Ktor’s coroutine-based architecture, customizable features, and fully Kotlin-centric design present a compelling alternative for those who appreciate a more native solution tailored for Kotlin development.</p><p>So, whether you’re looking to embrace Kotlin Multiplatform (KMP) or prefer Ktor for its design philosophy, this guide is here to assist you every step of the way!</p><p>You can access the sample code for the migration guide <a href="https://github.com/DenisBronx/RetrofitToKtorGuide/tree/migrated-to-ktor">here</a>.</p><h3>Step 1: Ensure Your Code is Well-Tested</h3><p>To successfully migrate your code from Retrofit to Ktor, it’s essential to ensure that you avoid introducing any regressions. Different frameworks operate in unique ways, often obscuring certain details from developers.</p><p>For example, did you know that in Ktor, you can’t parse JSON request or response bodies unless the appropriate header such as Content-Type: application/json is included in the request or response? This is a crucial detail that can impact the functionality of your application during the migration process.</p><p>It’s perfectly normal to encounter challenges and run into issues when working with a new library, especially if you don’t have much experience with it yet. Adapting to a different framework can be daunting, but don’t let that discourage you.</p><p>The best way to ensure a smooth migration is to cover your code with unit tests. With unit tests in place, you can identify issues immediately, rather than relying on manual testing on a device. This approach allows you to play around with the new library while receiving instant feedback, creating efficient feedback loops that facilitate your learning and development process.</p><h4>Testing with NetMock</h4><p><em>If your code is already fully tested and your tests are decoupled from implementation details, you can skip this step. Otherwise, keep reading!</em></p><p>When writing tests, it’s essential to ensure they are as decoupled as possible from both implementation details and frameworks. This decoupling enables you to refactor your code with minimal changes to your test code. If you find that modifications in your production code necessitate extensive changes to your tests, it’s a sign that your tests may be overly coupled and could hinder your refactoring efforts.</p><p>The ideal solution for testing network requests and responses, as well as the data layer as a whole, is to use <strong>NetMock</strong>.</p><p><a href="https://github.com/DenisBronx/NetMock">GitHub - DenisBronx/NetMock</a></p><p>This framework-independent library sets up its own localhost server, redirecting your network requests to it, allowing you to provide custom stub responses. Best of all, <strong>NetMock is extremely simple to use</strong>, making it an excellent choice for ensuring your network interactions are effectively tested without being tied to a specific framework. With NetMock, you can create robust and adaptable tests that streamline your development process.</p><h4>Now, let’s dive into the code!</h4><p>Imagine we have the following code that uses Retrofit to retrieve all the GitHub repositories of a specified organization, provided that the organization exists:</p><pre>interface GithubProjectApiService {<br>    @Headers(&quot;Content-Type: application/json&quot;)<br>    @GET(&quot;orgs/{organisation}/repos&quot;)<br>    suspend fun getProjectsForOrganisation(<br>        @Path(&quot;organisation&quot;) organisation: String<br>    ): Response&lt;List&lt;JsonGithubProject&gt;&gt;<br>}<br><br>sealed class Answer&lt;out T, out E&gt; {<br>    data class Success&lt;out T&gt;(val data: T) : Answer&lt;T, Nothing&gt;()<br>    data class Error&lt;out E&gt;(val reason: E) : Answer&lt;Nothing, E&gt;()<br>}<br><br>class RealGithubProjectRepository(<br>    private val githubProjectApiService: GithubProjectApiService<br>) : GithubProjectRepository {<br>    override suspend fun getProjectsForOrganisation(<br>        organisation: String<br>    ): Answer&lt;List&lt;GithubProject&gt;, GetProjectsError&gt; {<br>        return try {<br>            val apiResponse = githubProjectApiService.getProjectsForOrganisation(organisation)<br>            return mapSuccess(apiResponse)<br>        } catch (t: Throwable) {<br>            Answer.Error(GetProjectsError.GenericError)<br>        }<br>    }<br><br>    private fun mapSuccess(<br>        apiResponse: Response&lt;List&lt;JsonGithubProject&gt;&gt;<br>    ): Answer&lt;List&lt;GithubProject&gt;, GetProjectsError&gt; {<br>        return if (apiResponse.isSuccessful) {<br>            val projects = apiResponse.body()<br>            if (projects != null) {<br>                Answer.Success(mapDtoList(projects))<br>            } else {<br>                Answer.Error(GetProjectsError.GenericError)<br>            }<br>        } else {<br>            mapError(apiResponse.code())<br>        }<br>    }<br><br>    private fun mapDtoList(dtoList: List&lt;JsonGithubProject&gt;): List&lt;GithubProject&gt; {<br>        return dtoList.map { jsonDto -&gt;<br>            GithubProject(<br>                jsonDto.id,<br>                jsonDto.name,<br>                jsonDto.fullName,<br>                jsonDto.description,<br>                jsonDto.owner.avatarUrl<br>            )<br>        }<br>    }<br><br>    private fun mapError(errorCode: Int): Answer&lt;List&lt;GithubProject&gt;, GetProjectsError&gt; {<br>        val error = if (errorCode == 404) {<br>            GetProjectsError.NoOrganizationFound<br>        } else {<br>            GetProjectsError.GenericError<br>        }<br>        return Answer.Error(error)<br>    }<br>}</pre><p>Next, we’ll integrate <strong>NetMock</strong> into the project to enable us to stub network requests and responses:</p><pre>testImplementation &quot;io.github.denisbronx.netmock:netmock-server:$version&quot;</pre><p>With NetMock set up, we can easily test and stub our requests and responses by simply writing:</p><pre>netMock.addMock(<br>    request = NetMockRequest(<br>        requestUrl = &quot;$BASE_URL/orgs/$ORGANIZATION/repos&quot;,<br>        method = Method.Get,<br>        mandatoryHeaders = mapOf(&quot;Content-Type&quot; to &quot;application/json&quot;)<br>    ),<br>    response = NetMockResponse(<br>        code = 200,<br>        mandatoryHeaders = mapOf(&quot;Content-Type&quot; to &quot;application/json&quot;),<br>        body = readFromResources(&quot;responses/github_projects_success.json&quot;)<br>    )<br>)</pre><p>To achieve full unit test coverage for the RealGithubProjectRepository, we would implement something like this:</p><pre>class RealGithubProjectRepositoryTest {<br><br>    @get:Rule<br>    val netMock = NetMockServerRule()<br><br>    private val okHttpClient = OkHttpClient.Builder().addInterceptor(netMock.interceptor).build()<br>    private val retrofit = Retrofit.Builder()<br>        .baseUrl(BASE_URL)<br>        .client(okHttpClient)<br>        .addConverterFactory(MoshiConverterFactory.create())<br>        .build()<br><br>    private val sut = RealGithubProjectRepository(retrofit.create&lt;GithubProjectApiService&gt;())<br><br>    @Test<br>    fun `EXPECT empty list of projects WHEN body is empty list`() = runTest {<br>        netMock.addMock(<br>            request = EXPECTED_REQUEST,<br>            response = NetMockResponse(<br>                code = 200,<br>                mandatoryHeaders = MANDATORY_HEADERS,<br>                body = &quot;[]&quot;<br>            )<br>        )<br><br>        val result = sut.getProjectsForOrganisation(ORGANIZATION)<br><br>        assertEquals(Answer.Success(emptyList&lt;GithubProject&gt;()), result)<br>    }<br><br>    @Test<br>    fun `EXPECT generic error WHEN error is 500`() = runTest {<br>        netMock.addMock(<br>            request = EXPECTED_REQUEST,<br>            response = NetMockResponse(<br>                code = 500,<br>                mandatoryHeaders = MANDATORY_HEADERS,<br>            )<br>        )<br><br>        val result = sut.getProjectsForOrganisation(ORGANIZATION)<br><br>        assertEquals(Answer.Error(GetProjectsError.GenericError), result)<br>    }<br><br>    @Test<br>    fun `EXPECT not found error WHEN error is 404`() = runTest {<br>        netMock.addMock(<br>            request = EXPECTED_REQUEST,<br>            response = NetMockResponse(<br>                code = 404,<br>                mandatoryHeaders = MANDATORY_HEADERS<br>            )<br>        )<br><br>        val result = sut.getProjectsForOrganisation(ORGANIZATION)<br><br>        assertEquals(Answer.Error(GetProjectsError.NoOrganizationFound), result)<br>    }<br><br>    @Test<br>    fun `EXPECT generic error WHEN response is successful but body is empty`() = runTest {<br>        netMock.addMock(<br>            request = EXPECTED_REQUEST,<br>            response = NetMockResponse(<br>                code = 200,<br>                mandatoryHeaders = MANDATORY_HEADERS,<br>                body = &quot;&quot;<br>            )<br>        )<br><br>        val result = sut.getProjectsForOrganisation(ORGANIZATION)<br><br>        assertEquals(Answer.Error(GetProjectsError.GenericError), result)<br>    }<br><br>    @Test<br>    fun `EXPECT generic error WHEN response is successful but body is not parseable`() = runTest {<br>        netMock.addMock(<br>            request = EXPECTED_REQUEST,<br>            response = NetMockResponse(<br>                code = 200,<br>                mandatoryHeaders = MANDATORY_HEADERS,<br>                body = &quot;null&quot;<br>            )<br>        )<br><br>        val result = sut.getProjectsForOrganisation(ORGANIZATION)<br><br>        assertEquals(Answer.Error(GetProjectsError.GenericError), result)<br>    }<br><br>    @Test<br>    fun `EXPECT mapped list of projects WHEN body is non empty list`() = runTest {<br>        netMock.addMock(<br>            request = EXPECTED_REQUEST,<br>            response = NetMockResponse(<br>                code = 200,<br>                mandatoryHeaders = MANDATORY_HEADERS,<br>                body = readFromResources(&quot;responses/github_projects_success.json&quot;)<br>            )<br>        )<br><br>        val result = sut.getProjectsForOrganisation(ORGANIZATION)<br><br>        assertEquals(Answer.Success(EXPECTED_GH_PROJECTS), result)<br>    }<br><br>    private companion object {<br>        const val BASE_URL = &quot;https://api.github.com&quot;<br>        const val ORGANIZATION = &quot;square&quot;<br>        val MANDATORY_HEADERS = mapOf(&quot;Content-Type&quot; to &quot;application/json&quot;)<br>        val EXPECTED_REQUEST = NetMockRequest(<br>            requestUrl = &quot;$BASE_URL/orgs/$ORGANIZATION/repos&quot;,<br>            method = Method.Get,<br>            mandatoryHeaders = MANDATORY_HEADERS<br>        )<br><br>        val EXPECTED_GH_PROJECTS = listOf(<br>            GithubProject(<br>                id = &quot;892275&quot;,<br>                name = &quot;retrofit&quot;,<br>                fullName = &quot;square/retrofit&quot;,<br>                description = &quot;A type-safe HTTP client for Android and the JVM&quot;,<br>                imageUrl = &quot;https://avatars.githubusercontent.com/u/82592?v=4&quot;<br>            ),<br>            GithubProject(<br>                id = &quot;1907635&quot;,<br>                name = &quot;JSONKit&quot;,<br>                fullName = &quot;square/JSONKit&quot;,<br>                description = &quot;Objective-C JSON&quot;,<br>                imageUrl = &quot;https://avatars.githubusercontent.com/u/82592?v=4&quot;<br>            )<br>        )<br>    }<br><br>}</pre><p>These tests cover the following scenarios:</p><ol><li>The API call is successful, but the organization has no repositories.</li><li>The service is unavailable.</li><li>The specified organization cannot be found.</li><li>A successful response returns an unexpected empty body.</li><li>A successful response yields an unexpected unparseable body.</li><li>A successful response returns valid results.</li></ol><p>For reference, <a href="https://github.com/DenisBronx/RetrofitToKtorGuide/blob/retrofit-implementation/app/src/test/resources/responses/github_projects_success.json">here’s the JSON response file</a> used for scenario 6.</p><p>As you can see, NetMock simplifies the process of stubbing requests and responses to just a few lines of code, making the test functions easy to read and understand.</p><h3>Step 2: Migrate from Retrofit to Ktor</h3><p>We’ve finally reached this exciting stage!</p><p>Now that our production code is fully tested, we can embark on the migration journey. What better way to illustrate this process than through a Git diff (full reference <a href="https://github.com/DenisBronx/RetrofitToKtorGuide/commit/deaa78d511a972a733df1268eecaabf711ecfea4">here</a>)?</p><p>As diligent TDD practitioners, let’s begin with the unit tests:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*brWD9Yaa6-9NS_9ZZ61JGQ.png" /></figure><p>As you can see, the changes in the tests are minimal — primarily limited to the setup. The only notable difference is that I had to trigger a parsing exception in a slightly different manner.</p><p>Next, let’s look at the repository migration:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YZfAgx9Kp1gSBf0BC_Y3WA.png" /></figure><p>Finally, here’s the updated DTO class used for parsing:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RW5iRb6Ccp35ED1QTxx6Hg.png" /></figure><p>In this migration, I’ve also transitioned from Moshi to Kotlinx-Serialization (yes, you get a two-for-one benefit with this article!). The reason for this change is that Ktor does not support Moshi out of the box, and if the goal is to create a multiplatform project, Moshi is not suitable, as it only works with the JVM.</p><p>Once again, this migration between frameworks has been remarkably straightforward, thanks to our unit tests lowly coupled with implementation details.</p><h3>Step 3 (Bonus): Switch to NetMock Engine for Multiplatform</h3><p>If your only goal was to migrate safely, congratulations, you’re all set! Feel free to stop here.</p><p>However, if you’re aiming for a multiplatform setup, this next, straightforward step is essential. While <strong>netmock-server</strong> has served us well so far, it’s worth noting that, despite its framework independence, it is only compatible with the JVM.</p><p>But don’t worry! Switching to <strong>netmock-engine, </strong>the lightweight multiplatform variant built on top of the Ktor engine , is all you need to do.</p><p>Once again, what better way to demonstrate this migration than with a Git diff (full reference <a href="https://github.com/DenisBronx/RetrofitToKtorGuide/commit/4bf61bda93a08e18715d66828d9802b31c4cc19c">here</a>)?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7X_op_g3bF1rK63eOi_TYw.png" /></figure><p>As you can see, you simply need to replace netmock-server with netmock-engine in your Gradle configuration and update the initialization of the NetMock instance along with the Ktor HttpClient. And that’s it!</p><p>Now, all that’s left is to migrate the rest of your code to Kotlin Multiplatform (KMP), and you’ll be all set!</p><h3>Final Notes</h3><p>Migrating from Retrofit to Ktor can seem like a daunting task, but with the right approach and tools, it can be a smooth and rewarding experience. Throughout this guide, we’ve emphasized the importance of maintaining comprehensive unit tests that are decoupled from implementation details. This practice not only helps you safeguard against regressions during the migration but also enables you to adapt more easily to changes in your codebase.</p><p>Using <strong>NetMock</strong> has proven invaluable in our testing process. Its framework-independent design allows for efficient stubbing of network requests and responses, ensuring that your tests remain clear and concise. Transitioning to <strong>netmock-engine</strong> for a multiplatform setup further enhances your ability to develop applications that can run seamlessly across different platforms.</p><p>In summary, by following these steps — thoroughly testing your existing code, executing a careful migration, and leveraging tools like NetMock — you can confidently transition to Ktor while ensuring your application remains robust and maintainable. <br>Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=428fd6b6d330" width="1" height="1" alt=""><hr><p><a href="https://medium.com/clean-android-dev/how-to-safely-migrate-from-retrofit-to-ktor-428fd6b6d330">How to “Safely” Migrate from Retrofit to Ktor</a> was originally published in <a href="https://medium.com/clean-android-dev">Clean Android Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introducing NetMock: Simplifying HTTP Request Testing in Java, Android, and Kotlin Multiplatform]]></title>
            <link>https://medium.com/clean-android-dev/introducing-netmock-simplifying-http-request-testing-in-java-android-and-kotlin-multiplatform-769aeabbb214?source=rss-8f0052074f18------2</link>
            <guid isPermaLink="false">https://medium.com/p/769aeabbb214</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[kotlin-multiplatform]]></category>
            <dc:creator><![CDATA[Denis Brandi]]></dc:creator>
            <pubDate>Wed, 14 Jun 2023 15:06:16 GMT</pubDate>
            <atom:updated>2023-06-14T15:06:16.062Z</atom:updated>
            <content:encoded><![CDATA[<h4>Let’s get rid of the complexities of simulating requests and responses in testing environments</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uDZMKjADoAqP0hoAryN2fQ.png" /><figcaption>NetMock code</figcaption></figure><p>I am thrilled to introduce NetMock, a powerful and user-friendly library designed to streamline the mocking of HTTP requests and responses.</p><p>Testing HTTP requests can often present challenges for developers due to the complexity of simulating requests and responses in testing environments. This can result in increased time and resources spent on manual testing. Having faced similar struggles with existing HTTP libraries and cumbersome mocking tools, I took it upon myself to create a solution: NetMock.</p><p>NetMock is designed to integrate with Java, Android, and Kotlin Multiplatform seamlessly. With minimal setup, you can effortlessly create mocks that accurately mimic client requests and real endpoint responses. One of the key advantages of NetMock is its consistent approach to mocking HTTP requests and responses. This proves especially beneficial when working on projects employing different libraries or considering a transition from one library to another.</p><p>Another noteworthy aspect of NetMock is its user-friendly design. Unlike many other HTTP mocking tools, NetMock prioritizes ease of use. The library offers an intuitive interface and a straightforward setup process, catering to developers needing to be better-versed in HTTP libraries.</p><p>Whether you are a seasoned developer or just starting, NetMock is the perfect solution for simplifying your workflow and reducing the time and effort required to create robust, reliable software.</p><p>If you want to explore NetMock further, you can find the NetMock repository on GitHub at <a href="https://github.com/DenisBronx/NetMock">https://github.com/DenisBronx/NetMock</a>.</p><h3>Improving Testing Strategy for HTTP-Related Code</h3><p>As a professional software engineer, I firmly believe in the critical importance of comprehensive unit testing for all code. However, I have observed a common practice among developers to neglect unit testing in the network layer due to the challenges involved in mocking and testing this area. Instead, they often rely on end-to-end automated tests or manual testing.</p><p>In various projects, I have encountered an approach where HTTP-related code is isolated into separate components to enable independent testing of the remaining system. While this approach can lead to leaner repositories and test classes, it often results in neglecting the testing of the HTTP code itself, as it is considered challenging to test. As a consequence, crucial logic related to HTTP requests and JSON parsing still needs to be validated.</p><p>This issue is exemplified in projects that utilize the Retrofit library, which abstracts the HTTP-related logic through interfaces. Consider the following code snippet:</p><pre>interface GitHubService {<br>    @GET(&quot;users/{user}/repos&quot;)<br>    suspend fun listRepos(@Path(&quot;user&quot;) user: String): List&lt;RepoDto&gt;<br>}<br><br>class GitHubRepositoryImpl(<br>    private val githubService: GitHubService,<br>    private val repoMapper: RepoMapper<br>): GitHubRepository {<br>    override suspend fun listRepos(user: String): List&lt;Repo&gt; {<br>        val repoDtos = githubService.listRepos(user)<br>        return repoMapper.map(repoDtos)<br>    }<br>}</pre><p>While this approach can simplify repositories and test classes, it often omits crucial tests for the HTTP-related logic. Additionally, developers may create unnecessary components solely to simplify unit testing of repositories.</p><p>Unit testing aims to prevent and identify mistakes made by developers, ensuring that the code functions as intended. Without adequate tests, even simple errors, such as changing the path from users/{user}/repos to user/{user}/repos or renaming a field in RepoDto may go unnoticed, which is unacceptable in a professional project.</p><p>My critique is in no way targeted at the Retrofit library itself.</p><p>On the contrary, I consider it an exceptional and highly readable library.</p><p>Furthermore, I recognize the value of isolating HTTP-related code into separate components for improved organization and maintainability.</p><p>Rather, I intend to shed light on a flawed testing strategy I have observed in numerous projects. This strategy often needs to pay more attention to the comprehensive testing of the HTTP code, resulting in potential issues going unnoticed. By highlighting this concern, I encourage developers to prioritize thorough testing of their HTTP-related logic, thus ensuring their projects&#39; overall quality and reliability.</p><h3>Mocking Requests and Responses with NetMock</h3><pre>@Test<br>fun `your test`() = runTest {<br>    val user = &quot;some_user&quot;<br>    netMock.addMock(<br>        request = {<br>            method = Method.Get<br>            requestUrl = &quot;https://api.github.com/users/$user/repos&quot;<br>        },<br>        response = {<br>            code = 200<br>            body = readFromResources(&quot;responses/repo_list.json&quot;)<br>        }<br>    )<br><br>    val result = sut.listRepos(user)<br><br>    //...<br>}</pre><p>To mock requests and responses, you can utilize the simple API provided by NetMock.</p><p>By adding a mock to the queue of expected requests and responses, you can intercept and control the behavior of HTTP interactions during testing.</p><h4>Creating a NetMock instance</h4><p>NetMock offers two flavors: netmock-server and netmock-engine.</p><p>The netmock-server flavor is compatible with Java, Kotlin, and Android, and it is library-independent. It allows you to mock network requests by redirecting them to a localhost web server using <a href="https://github.com/square/okhttp/tree/master/mockwebserver">MockWebServer</a>. This flavor is perfect for developers working on non-Multiplatform projects who want to test their network requests without setting up a separate server.</p><p>The netmock-engine flavor, on the other hand, is specifically designed for developers using Ktor or working with Kotlin Multiplatform. It employs MockEngine under the hood instead of a localhost server, making it a lightweight and multiplatform option for those working with Ktor.</p><h4>Working with NetMockServer</h4><p>To add netmock-server to your project, add the following to your dependencies in build.gradle file:</p><pre>dependencies {<br>    testImplementation &quot;io.github.denisbronx.netmock:netmock-server:0.4.0&quot;<br>}</pre><p>Next, create a NetMockServer instance as follows:</p><pre>@get:Rule<br>val netMock = NetMockServerRule()</pre><p>NetMockServer starts a localhost server that will intercept your requests using <a href="https://github.com/square/okhttp/tree/master/mockwebserver">MockWebServer</a>. The NetMockServerRule handles the server’s lifecycle, automatically starting and shutting it down for each test.</p><p>Once the server is up and running, you can configure your code to point to the localhost base URL using netmock.baseUrl. <br>Here are examples of Retrofit and Ktor:</p><p>Retrofit example that uses localhost:</p><pre>@get:Rule<br>val netMock = NetMockServerRule()<br><br>private val service = Retrofit.Builder()<br>    .baseUrl(netMock.baseUrl)<br>    .build()<br>    .create(GitHubService::class.java)</pre><p>Ktor example that uses localhost:</p><pre>@get:Rule<br>val netMock = NetMockServerRule()<br>    <br>private val client = HttpClient(OkHttp) {<br>    defaultRequest {<br>        url(netMock.baseUrl)<br>    }<br>}</pre><p>Alternatively, you can add an interceptor using netmock.interceptor, which automatically redirects requests to localhost:</p><p>Retrofit example that uses a real URL:</p><pre>@get:Rule<br>val netMock = NetMockServerRule()<br><br>private val service = Retrofit.Builder()<br>    .baseUrl(&quot;https://api.github.com/&quot;)<br>    .client(OkHttpClient.Builder().addInterceptor(netMock.interceptor).build())<br>    .build()<br>    .create(GitHubService::class.java)</pre><p>Ktor example that uses a real URL:</p><pre>@get:Rule<br>val netMock = NetMockServerRule()<br>    <br>private val client = HttpClient(OkHttp) {<br>    engine {<br>        addInterceptor(netMock.interceptor)<br>    }<br>}</pre><p>An interceptor is recommended, as it allows you to work with real and dynamic URLs.</p><p>However, note that you’ll need a library compatible with OkHttp interceptors, such as OkHttp itself, Retrofit, or Ktor.</p><h3><strong>Final Thoughts</strong></h3><p>Apart from the initialization process, both flavors of NetMock are essentially identical. This means that transitioning between netmock-server and netmock-engine requires minimal modifications. This flexibility allows you to switch seamlessly between different libraries, such as transitioning from Retrofit to Ktor or vice versa, without modifying your tests.</p><p>Decoupling your testing framework from the underlying libraries can enhance your confidence in refactoring. When making changes, you only need to modify your production code while your tests remain intact. This approach significantly reduces the risk of introducing unintended side effects during refactoring and ensures that your tests accurately reflect the behavior of your code.</p><p>In summary,<strong> </strong>NetMock’s versatility empowers you to adapt your testing setup to different libraries and facilitates refactoring with ease, thereby bolstering the reliability and maintainability of your codebase.</p><p>Finally, I want to express my sincere gratitude to all the readers who have taken the time to explore this article. I hope the insights provided have shed light on the importance of comprehensive testing in the network layer.</p><p>Thank you once again for your attention, and happy testing with NetMock!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=769aeabbb214" width="1" height="1" alt=""><hr><p><a href="https://medium.com/clean-android-dev/introducing-netmock-simplifying-http-request-testing-in-java-android-and-kotlin-multiplatform-769aeabbb214">Introducing NetMock: Simplifying HTTP Request Testing in Java, Android, and Kotlin Multiplatform</a> was originally published in <a href="https://medium.com/clean-android-dev">Clean Android Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The “Real” Clean Architecture in Android: Modularization]]></title>
            <link>https://medium.com/clean-android-dev/the-real-clean-architecture-in-android-modularization-e26940fd0a23?source=rss-8f0052074f18------2</link>
            <guid isPermaLink="false">https://medium.com/p/e26940fd0a23</guid>
            <category><![CDATA[clean-architecture]]></category>
            <category><![CDATA[gradle]]></category>
            <category><![CDATA[modularization]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Denis Brandi]]></dc:creator>
            <pubDate>Mon, 03 Apr 2023 17:46:10 GMT</pubDate>
            <atom:updated>2023-04-05T12:33:52.882Z</atom:updated>
            <content:encoded><![CDATA[<h3>The “Real” Modularization in Android</h3><h4>An overview of the principles behind modularization</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vMo2FbipyXkr6BUOxjNr8Q.png" /><figcaption>Image by author</figcaption></figure><blockquote>“If the SOLID principles tell us how to arrange the bricks into walls and rooms, then the component principles tell us how to arrange the rooms into buildings.” ~ Robert C. Martin, Clean Architecture</blockquote><blockquote>Should you package by layer or by feature? Is there any other approach?</blockquote><blockquote>How can you boost your project’s compilation time?</blockquote><blockquote>How can your engineers work independently in cross-functional teams?</blockquote><p>With this article, I aim to answer these questions by extending <a href="https://medium.com/better-programming/the-real-clean-architecture-in-android-part-1-s-o-l-i-d-6a661b103451">my previous article on SOLID principles.</a></p><pre><strong>Table of Contents</strong><br><br><a href="#898f">Component Cohesion Principles</a><br><a href="#d644">Component Coupling Principles</a><br><a href="#92de">Package Design Solutions</a><br><a href="#ad96">Encapsulation</a><br><a href="#6d12">The Main Component</a></pre><h4>Intro</h4><p>While SOLID principles can validate and detect code smells in a class or an interface, component principles can validate and detect code smells in a component.</p><blockquote>What is a component?</blockquote><p>A component is a group of files (classes, interfaces, files of functions, Android resources, etc.) that are grouped using one of the following strategies:</p><ol><li>Source code level (monolithic structure): in Java/Kotlin, we use packages</li><li>Binary/deployment level: in Java/Kotlin, we use modules that generate “jars” or “aars”</li><li>Service level: this would be a service or a microservice, where the communication happens through network packets</li></ol><p>Normally, you don’t use just one strategy. You mix these strategies according to your needs.</p><p><em>Since we don’t have services in Android, the article will be focused on Java/Kotlin modules.</em></p><h4>What is “good modularization”?</h4><p>A “good modularization” is a components’ structure in which modules are highly cohesive and lowly coupled.</p><blockquote>How can we say that modules are highly cohesive? <br>And how can we say that modules are lowly coupled?</blockquote><p>Modules are highly cohesive when they adhere to component cohesion principles.</p><p>Modules are lowly coupled when they adhere to component coupling principles.</p><h3>Component Cohesion Principles</h3><p><a href="https://medium.com/better-programming/the-real-clean-architecture-in-android-part-1-s-o-l-i-d-6a661b103451">SOLID principles</a> are the foundation of clean architecture and can be adapted at the module level, thus creating a new set of principles (REP, CCP, and CRP).</p><h4>The Common Closure Principle (CCP)</h4><blockquote>“Gather into components those classes that change for the same reasons and at the same times.</blockquote><blockquote>Separate into different components those classes that change at different times and for different reasons.” — All remaining quotes by Robert C. Martin, <a href="https://www.amazon.com/Clean-Architecture-Craftsmans-Software-Structure/dp/0134494164">Clean Architecture</a></blockquote><p>The CCP is the evolution of the <a href="https://medium.com/better-programming/the-real-clean-architecture-in-android-part-1-s-o-l-i-d-6a661b103451#8684">SRP</a> at the module level, as I explained in my previous article.</p><p><em>A class should not change for different reasons -&gt; a component should not change for different reasons.</em></p><p>Classes that change for the same reasons should be grouped in a component, and classes that change for different reasons should be moved away from the component.</p><p>Maintainability is more important than reusability: whenever you work on a new feature, or there is a requirement change, you would rather have to touch a single module than many.</p><p>When we have to change only a single module, we are less likely to affect other team members, and we have fewer components to recompile, revalidate, and redeploy.</p><p>It is not realistic to always group every possible change in a single module (unless you work with a monolith 😈), so the goal of the principle is to minimize the number of modules that needs changing.</p><p>Pros: Optimal for maintenance as the impact of change is minimized.<br>Cons: The optimal approach for developing and maintaining the modules might not be optimal for releasing the modules to library users. Also, modules will tend to be bigger to isolate the number of modules to change.</p><h4>The Common Reuse Principle (CRP)</h4><blockquote>“Don’t force users of a component to depend on things they don’t need.”</blockquote><p>The CRP is the evolution of the <a href="https://medium.com/better-programming/the-real-clean-architecture-in-android-part-1-s-o-l-i-d-6a661b103451#0d23">ISP</a> at the module level, as I explained in my previous article.</p><p><em>When interfaces are small, you don’t depend on methods you don’t need -&gt; when modules are small, you don’t depend on files you don’t need.</em></p><p>Classes are seldom reused in isolation. More typically, reusable classes collaborate with other classes that are part of the reusable abstraction. <br>The CRP states that these classes belong together in the same component.</p><p>It also states that classes not reused together should not be placed in the same component.</p><p>By doing so, an update on such classes won’t trigger a recompilation, redeployment, or release of modules that do not use them.</p><p>Pros: Smaller modules, as a module user you are less likely to be affected by changes you don’t care about.</p><p>Cons: More modules that require to be worked on during development.</p><h4>The Reuse/Release Equivalency Principle (REP)</h4><blockquote>“The granule of reuse is the granule of release.”</blockquote><p>The smallest thing you are willing to reuse is the smallest thing you are willing to release.</p><p>This is a very important principle for library devs.</p><p>Whenever you want to make a component available to others, you are required to have a release process, and for your component to not break your library users’ code over time, you are required to have release numbers.</p><p>By doing so, library users won’t have breaking changes unless they upgrade to the newer library versions.</p><p><em>Because all the classes in your module have the same release number, an update of a single class will require a new release of all the classes under the same module.</em></p><p>Sometimes, libraries come as a single library, and sometimes they come as a group of libraries (so you can decide what to import and what to exclude).</p><p>When working with a group of libraries, you may expect that because all these modules are reused together, they should all have the same release number to ensure compatibility.</p><p>Having the same release number means that when you need to update one module, you’ll also need to release all the other modules with the updated version number (even when these have not changed).</p><p>Let’s take <a href="https://github.com/square/retrofit">Retrofit</a> as an example.</p><pre>implementation &#39;com.squareup.retrofit2:retrofit:2.9.0&#39;<br>implementation &#39;com.squareup.retrofit2:converter-moshi:2.9.0&#39;</pre><p>When Retrofit developers add new functionalities to the Retrofit main library, they most likely also need to make the supporting converter libraries compatible with these new integrations, thus bumping the version name of all the library modules.</p><p><em>This might not always be the best approach, in particular when modules of the same group of libraries are not very cohesive.</em></p><p>Let’s now take <a href="https://github.com/firebase/firebase-android-sdk">Firebase</a> as an example.</p><p>Firebase libraries used to have matching release numbers in the past.</p><p>The problem with Firebase is that their set of libraries is very incohesive. <br>Think about the remote config library and the storage library: these two libraries are completely independent of each other and probably worked on by different dev teams.</p><p>A new integration in one of the two should not require the Firebase team to release a new version of the other library without changes.</p><p>What did the Firebase team end up doing?</p><p>They took advantage of Gradle 5.0 support for Maven <a href="https://docs.gradle.org/current/userguide/platforms.html">BoMs</a>, which allows managing different library versions as a single version.</p><p>By doing so, instead of releasing a new version of every single library, they release a new version of the BoM.</p><pre> // BoM<br> implementation platform(&#39;com.google.firebase:firebase-bom:$version&#39;)<br><br> // modules import without version<br> implementation &#39;com.google.firebase:firebase-core&#39;<br> implementation &#39;com.google.firebase:firebase-config&#39;<br> implementation &#39;com.google.firebase:firebase-storage&#39;</pre><p>If it weren’t for BoMs, they would have used <a href="https://developers.google.com/android/guides/setup#list-dependencies">Google Play Services’ approach</a>, aka an endless table of library versions (the least user-friendly).</p><p>Pros: Optimal for reusability, your modules are available to other teams, and the versioning makes new updates easier to manage.</p><p>Cons: It is more complicated to maintain the codebase as now you need to consider the module&#39;s release process.</p><p>Modules will tend to be bigger because by doing so, you can decrease the number of modules that need releasing.</p><h3>The Component Cohesion Tension Triangle</h3><figure><img alt="REP (group for reusers) to CCP (group for maintenance) — too many unneeded releases REP (group for reusers) to CCP (group for maintenance) — too many unneeded releases CCP (group for maintenance) to CRP (split to avoid unneeded recompilations/releases) — hard to reuse CRP (split to avoid unneeded recompilations/releases) to REP (group for reusers) — too many components changed caption: what is your right fit?" src="https://cdn-images-1.medium.com/max/998/1*TPl35E_0Q4Dgty3iLk-dSg.png" /><figcaption>Component Cohesion Tension Diagram</figcaption></figure><p>The diagram shows what happens when you abandon one principle in favor of the other two.</p><p>If it wasn’t clear already, the Component Cohesion Principles, unlike SOLID principles, don’t complement each other and require you to choose what is more important for your project.</p><p>While it is easy to make classes easy to maintain and reuse, the same cannot be said for modules.</p><p>The CCP and the REP are inclusive principles; they tend to make modules bigger, while the CRP is an exclusive principle as it tends to make modules smaller.</p><p>The CRP and the REP are principles focused on reuse. They tend to optimize the modules for those who are using them, while the CCP is focused on maintenance as it tends to optimize modules for those who are developing them.</p><p>It is very unlikely that you’ll manage to balance all three, so you should be prepared to give up or focus less on one of them.</p><p>Usually, a project falls under one of the following categories:</p><ol><li>App: when you are building an app, your main goal is to build things fast and have a project that compiles quickly with minimal unneeded recompilations. <br>If you fall under this category, you should always focus on CCP and CRP.</li><li>Library: when you are building a library, your goal won’t be static. On the contrary, it will change over time.<br>When you start the development of the library, your main focus should be on building the library fast. Then, over time, your focus should shift to how reusable the library is and compromise its maintenance.<br>If you fall under this category, you should focus on the right side of the triangle until your project is mature, then you should move to the left side over time as now you’ll be more and more accountable to your library users.</li></ol><p>Most projects’ modularization fails because engineers prioritize the wrong principle for their projects’ nature.</p><p>Other projects’ modularization fails because the component structure is static instead of evolving as requirements change.</p><h4>References</h4><p>* Clean Architecture, Chapter 13 (Component Cohesion)</p><h3>Components Coupling Principles</h3><p>We discussed the theory about how modules should be according to the Cohesion Principles.</p><p>We now need to discuss how the relationships between these modules should be.</p><h4>The Acyclic Dependencies Principle (ADP)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/1*iS63eL0ED-nQQIpj5O-iLw.png" /><figcaption>Example of Cyclic Dependency Principle</figcaption></figure><blockquote>“Allow no cycles in the components dependency graph.”</blockquote><p>If A depends on B, then B should not depend on A.</p><p>This is not only true for dependencies but also for transitive dependencies:<br>If A depends on B and B depends on C, then C should not depend on A either.</p><p>Some compilers allow for cycles in modules, and others try to ensure this doesn’t happen.</p><p>Regardless of the compiler or language used, you, as a developer, need to know how to break the dependency cycle as soon as you detect it.</p><p>A dependency cycle can be broken in two ways:</p><ol><li>Extracting the classes to reuse in a new module.</li><li>Using the <a href="https://medium.com/better-programming/the-real-clean-architecture-in-android-part-1-s-o-l-i-d-6a661b103451#0793">Dependency Inversion Principle</a> (DIP, yes, SOLID again 😈) to “invert” the dependency.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-owR-stJXhd0-lyY4HbKYw.png" /></figure><p>Solution 1 is ideal when many modules require the shared logic and when a lot needs sharing.</p><p>Solution 2 is ideal when only a single module requires the shared logic and when there is not much to share.</p><h4>The Stable Dependencies Principle (SDP)</h4><blockquote>“Depend in the direction of stability.”</blockquote><blockquote>What would you make your module rather depend on? <br>A module that changes often or a module that never changes?</blockquote><p>We want our modules to depend on modules that never change.</p><p>Whenever a dependency in our module changes, our module needs to recompile, and we may have to deal with breaking changes.</p><blockquote>Which modules are stable?</blockquote><p>Stable modules are the ones that are hard to change.</p><p>Think about the Kotlin String class, how likely is the Kotlin team to change such a class? If they do change it, how many breaking changes would they have in the whole Kotlin language? That is a class that no developer sane of mind would ever change.</p><p>The ideal scenario for you is that your module depends on something as stable as that.</p><p>Unfortunately, we live in the real world, not the ideal one.</p><p>Most modules we use are not 100% stable, which is not necessarily bad.</p><p>A module that cannot change cannot also ever improve.</p><p>Not only that, if modules cannot change at all, we can never add new features as we can’t change the code.</p><blockquote>So, how do we redefine stability? <br>When is a module stable enough?</blockquote><p>A module is stable when it has few dependencies and many dependent modules, thus making it a responsible module.</p><p>If you look at your components dependency graph, you should see at the bottom the more stable (responsible) modules and at the top the more unstable (dependent) modules.</p><p>Because in your project, you’ll end up having both stable and unstable modules, the golden rule is that a module should depend on modules that are more stable than itself.</p><h4>The Stable Abstractions Principle (SAP)</h4><blockquote>“A component should be as abstract as it is stable.”</blockquote><p>The SDP defines that stable modules are hard to “change.”<br>This implies that adding new functionalities to stable modules is hard as you cannot easily modify the existing code…</p><p>But what about “extension”? Can I extend stable modules?</p><p>The <a href="https://medium.com/better-programming/the-real-clean-architecture-in-android-part-1-s-o-l-i-d-6a661b103451#968a">Open-Closed Principle</a> (OCP, yes SOLID again 😈) gives us classes that are open to extension and closed to modification.</p><blockquote>How do I port this extensibility at the module level?</blockquote><p><em>A module is easy to extend when it is abstract. Hence it is composed mainly of interfaces and abstract classes.</em></p><p>When a module is full of interfaces, whenever you need to add something new, all you need to do is to provide a new concrete implementation to one of the abstractions.</p><p>This will prevent you from touching the stable modules’ source code just to adapt something for your module and potentially break the other dependent modules.</p><p>While stable modules should be more abstract than concrete to allow more flexibility, unstable modules should be more concrete than abstract to facilitate code changes.</p><p>Although you want stable modules to be very abstract to allow flexibility, a module that is 100% abstract is a module that is useless as there is no actual logic that you can reuse.</p><p>And obviously, a stable module that is 100% concrete is a module that is very painful to change.</p><p>The golden rule here is that a module should depend on the abstractions of its dependencies rather than the concretion.</p><p>You should be getting this for free if your classes adhere to the Dependency Inversion Principle.</p><h4>References</h4><p>* Clean Architecture, Chapter 14 (Component Coupling)</p><h3>Package Design Solutions</h3><p>If you got bored reading the above six principles, worry not, as now I’m going to get into the fun part.</p><p>Now that we know how to achieve high cohesion and low coupling, it is time to discuss which approaches work and which don’t.</p><p>Because app developers are the ones with the most trouble modularizing and because library developers don’t usually have to deal with a lot of modules, I will only focus on how to modularize an app (or this article will become even longer!).</p><h4>Package by layer</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/954/1*aPpWYND8Djpxk-ICigLPIA.png" /><figcaption>Package by Layer Diagram</figcaption></figure><blockquote>In package by layer, you split the codebase into three broad modules, one for each layer. — Author</blockquote><p>This approach is quite easy to do but violates most of the abovementioned principles.</p><p>You’ll most likely have to modify all the modules whenever you work on a new feature<strong>.</strong></p><p>By doing so, you may end up breaking other features&#39; code, stepping on your teammates&#39; feet, and recompiling the whole dependency graph at any new iteration.</p><p>Modules will also be very big, as they will contain the layer logic of all the features in your app.</p><blockquote>Why is this approach so popular?</blockquote><p>If you’ve been reading Clean Architecture articles since the beginning of the hype, you would have noticed how most writers, when discussing modularization, constantly pushed for the Package by Layer approach, thinking that layers (Presentation-Domain-Data) should dictate the modules’ structure of their project.</p><p><em>If these writers had read the </em><a href="https://www.amazon.com/Clean-Architecture-Craftsmans-Software-Structure/dp/0134494164"><em>Clean Architecture book</em></a><em> in the first place, they would have known that this approach was the one most advertised against.</em></p><p>The reason why this bad advice makes me upset is not just because devs used the wrong modularization approach as a consequence but also because it lead companies astray as they separated development teams by these layers.</p><blockquote>What if I want to swap a database for another database?<br>Isn’t it better to have to change a single module?</blockquote><p>I’ve heard this many times in support of this packaging approach, and the short answer is no, it is not better.</p><p>Firstly, it is not part of your day-to-day work to change your database. This may happen over the years but definitely not on a weekly basis.</p><p>Not to mention that this is very rare work for mobile developers (some unlucky devs had to change Sqlite with Realm and then back to Sqlite with Room, but this happened over many years).</p><p>Secondly, it is a bad idea to swap a database in a single blow. It is much better to migrate feature by feature your data to the new database so that you can gradually release your migration and limit the number of potential bugs that may come out.</p><h4>Package by feature</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CCkDrQwMZ6ikfqVMmD4aEw.png" /><figcaption>Package by Feature Diagram</figcaption></figure><blockquote>In package by feature, you split the codebase into feature modules, one for each feature. — Author</blockquote><p>This approach brings many advantages, and it has been the most recommended approach for decades:</p><ul><li>When working on a feature, you change only one module, which is optimal for maintenance.</li><li>When you open your project, you know exactly what your project does as it screams at you what it is about (Screaming Architecture).</li><li>Each cross-functional team can work independently on a feature without stepping on another team’s feet.</li><li>Independent teams also mean independent modules, so you can get the most out of Gradle parallel compilation, which will decrease your overall compilation time other than requiring you to recompile only that single feature that changed.</li><li>You don’t lose layers, as layers can easily be implemented as packages inside the feature module.</li></ul><blockquote>So this is how I should modularize my app, right?</blockquote><p>Not really. This approach looks optimal for maintenance but has no reusability at all!</p><p>The cons of this approach are very expensive:</p><ul><li>If your feature module needs to reuse some code from another feature module, you’ll need to create a dependency on a very unstable module which would break the SDP, also because features will contain a lot of UI code, and UI code is very concrete; you’ll also break the SAP.</li><li>Feature modules contain presentation, domain, and data logic which results in big modules (CRP violation) containing code that often changes (UI) along with code that rarely changes (business logic).</li><li>Features depending on features often create big “Core Features” modules that revert your project gradually to a monolith.</li></ul><p>Package by feature works well in non-UI-heavy projects like backend or old frontend applications.</p><p>In a backend project, the controllers&#39; code (presentation layer) is usually thin and matches the use cases or services of the domain layer.</p><p>The backend can also rely on services (or microservices) rather than modules, so communication within the components does not require a service to know the internal structure of another service. Instead, the public API’s contract makes the whole components’ structure independent at compilation time.</p><p>In mobile or web frontend projects, “screens” are clusters of features.</p><p>Think of an e-commerce product detail page that allows you to add the product to the cart and the user’s wishlist.</p><p>These same actions can be performed on a product list page or the cart page, or the wishlist page.</p><blockquote>How can you split by feature in this case? <br>Are you going to group everything under a single feature?<br>Are you going to create a big shared feature module for sharing common code?<br>Are you going to duplicate a lot of your code so you can have independent modules?</blockquote><p>Any of these solutions are suboptimal and are not the answer to the problem.</p><p>Package by feature is not the right fit for UI-heavy projects, so don’t use it on professional Android projects (the same applies to iOS and Web).</p><h4>Package by component</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hb7f_lBmfRxqztUPkDm-Yg.png" /><figcaption>Package by Component Diagram of the PDP scenario</figcaption></figure><blockquote>In package by component, you split the codebase into UI modules and component modules (domain + data layer of a feature). — Author</blockquote><blockquote>Who should guide the modules of your app?</blockquote><p>Certainly not the UI logic as we saw in package by feature.<br>Use cases should guide your modularization just like they guide your development.</p><p>Use cases tell us what the app does and rarely change. They are also the only architectural component visible by the presentation layer.</p><p>The data layer exists only to support the domain layer. Hence a modification of the domain layer will often require a modification in the data layer to be compatible with the updated repository interface.</p><p>By splitting the codebase vertically and horizontally using use cases, we can achieve the reusability we didn’t have in package by feature.</p><p>Going back to the product detail page example (check the diagram). If I have a Cart Component module, a Wishlist Component module, and a PDP UI module, I can now reuse both cart and wishlist codes without depending on any UI detail for showing the cart or the wishlist screens.</p><p>And if the product team decides to introduce the add-to-cart functionality in the wishlist screen, we can just add the Cart Component module as a dependency to the Wishlist UI module and link it.</p><p>Not only do I now have a more reusable approach, but I also have separated classes that often change from classes that rarely change, thus minimizing the number of recompilations.</p><p>Because components are still independent, we can compile modules in parallel, thus improving the overall compilation time.</p><blockquote>What if I need to share code between component modules or UI modules?</blockquote><p>You will most likely encounter that problem if you work on a professional project, and the solution is as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vMo2FbipyXkr6BUOxjNr8Q.png" /></figure><p>If what you need to share is a feature’s specific code, you can extract what you need to reuse in a Shared Component module or a Shared UI module.</p><p>If what you need to share is generic code, let’s say code for performing a network request or a design system, you would follow the same approach you always use with third-party libraries (like Retrofit, Dagger…) with the difference that this module won’t be public but private for your project (until you decide to share it with the public).</p><blockquote>What if I need to navigate from the PDP to the Cart screen or the Wishlist screen?</blockquote><p>DIP is your friend. If you need to navigate through modules, all you need to do is to have an interface, let’s say:</p><pre>interface PDPNavigator {<br>    // you can adapt for fragments, navigation component, compose....<br>    fun navigateToCart(activity: Activity) <br>    fun navigateToWishlist(activity: Activity)<br>}</pre><p>Which will be implemented by a class in the Main (app) module:</p><pre>class AppNavigator: PDPNavigator, WishlistNavigator, CartNavigator.... {<br>    override fun navigateToCart(activity: Activity) {<br>        //...<br>    }<br><br>    override fun navigateToWishlist(activity: Activity) {<br>        //...<br>    }<br><br>}</pre><p><em>You don’t need to do this for screens inside the same module.</em></p><h4>References</h4><p>* Clean Architecture, Chapter 34 (The Missing Chapter) by Simon Brown<br>* <a href="https://dzone.com/articles/package-component-and">Simon Brown’s original post</a><br>* <a href="https://martinfowler.com/bliki/PresentationDomainDataLayering.html">Martin Fowler’s referenced article</a> in The Missing Chapter</p><h3>Encapsulation</h3><p>If there is one thing developers never do well, it is working with encapsulation.</p><p>Open one of your module&#39;s code. If every single class or interface is public, you are doing encapsulation wrong.</p><p>“Public” is a modifier that should be used only for those classes or interfaces meant to be used outside the module. Everything else should be “internal.”</p><p>If every class or interface is “public” inside a module, a developer might be misled into thinking that everything needs to be reused by other modules and will be afraid to touch the code.</p><p>More disciplined developers, to gain confidence, would use the IDE find usages tool to check that these classes are used outside of the module. <br><em>If only there were a modifier that could have avoided these extra steps and made devs more productive.</em></p><p>Module encapsulation is not just about confidence but also about future improvements.</p><p>By knowing what is public and what is not, you may find a way to decouple a module from a dependency in cases where you only use it because of a small number of classes/interfaces.</p><p>It doesn’t end with public/internal modifiers.</p><p>Another encapsulation problem you may find is related to the exposure of transitive dependencies.</p><p>This happens when one of your dependencies is leaking a transitive dependency by using api instead of implementation.</p><p>Ideally, you always use implementation, as this avoids the leaking of dependencies and extra compilation time.</p><h4>Encapsulation with package by component</h4><p>In Package by Component, it is quite simple to work with encapsulation as the number of files that can be public is just a few.</p><ul><li>In component modules: the only files that should be public are the use-case interfaces and the models that need to be used outside the module.<br>Use case implementations, repository interfaces, repository implementations, mappers interfaces, mappers implementations, DTOs, etc., should always be internal, as the presentation layer should not access them.<br>Component modules are stable (SDP adherence), containing business rules and use cases. By making only use case interfaces public, we also adhere to the SAP since now other modules will only depend on the abstraction of this module.</li><li>In UI modules: the only files that should be public are the screens (fragments, activities, compose screen Composables) and the external navigators.<br>UI modules are unstable since UI is very volatile; hence, we should try not to add them as dependencies and import them only in the Main (app) module to connect the navigation.</li></ul><p>If you are working with Dagger, the modules providing these dependencies should also be made internal.</p><pre>// Dagger module for a Wishlist Component Module<br>@Module<br>@InstallIn(SingletonComponent::class) // Or any other scope<br>internal object WishlistComponentModule {<br><br>    @Provides<br>    fun provideAddToWishlistUseCase(<br>        addToWishlistUseCaseImpl: AddToWishlistUseCaseImpl<br>    ): AddToWishlistUseCase = addToWishlistUseCaseImpl<br><br>    @Provides<br>    fun provideGetWishlistUseCase(<br>        getWishlistUseCaseImpl: GetWishlistUseCaseImpl<br>    ): GetWishlistUseCase = getWishlistUseCaseImpl<br><br>    @Provides<br>    fun provideWishlistRepository(<br>        wishlistRepositoryImpl: WishlistRepositoryImpl<br>    ): WishlistRepository = wishlistRepositoryImpl<br><br>    //...<br><br>}<br><br>// Dagger module for a Wishlist UI Module<br>@Module<br>@InstallIn(ActivityComponent::class) // Or any other scope<br>internal object WishlistUIModule {<br><br>    @Provides<br>    fun provideSomeDependency(<br>        someDependencyImpl: SomeDependencyImpl<br>    ): SomeDependency = someDependencyImpl<br><br>    //...<br><br>}</pre><p>If you are using manual injection, you can make your Dependency Containers public and make sure that only public files are returned from a public method (you will get a compilation error otherwise).</p><h4>References</h4><p>* <a href="https://docs.gradle.org/current/userguide/java_library_plugin.html#sec:java_library_recognizing_dependencies">Gradle API vs implementation documentation</a></p><h3>The Main Component</h3><p>In every system, at least one component creates, coordinates, and oversees the others.</p><p>The Main Component (app module in Android) is the ultimate detail, it contains the lowest-level policies and is the system’s entry point.<br>It is a dirty low-level module in the outermost circle of the clean architecture. It loads everything up for the high-level system and then hands control over to it.</p><p>The following should be placed in this area:</p><ul><li>all the “glue code” required to connect the modules</li><li>all the injection code that cannot be internal in the modules</li><li>all the navigation code that cannot be internal in the modules</li><li>your flavors configurations</li><li>all the initialization required by the frameworks</li></ul><h4>References</h4><p>* Clean Architecture, Chapter 26 (The Main Component)</p><h3>Last Notes</h3><p>I know that the article was long and that principles are never fun, especially when they require you to know other principles beforehand.<br>If I had to write this article with only the solutions, these would have just been an opinion to the reader rather than the product of the component principles.</p><p>Despite this being a long read, a lot has been left out, like Domain-Driven Design concepts for decoupling the contexts or Package by Ports and Adapters (another suboptimal package design solution).</p><p>I hope the article was still enjoyable despite the theoretical parts and you have learned new tools to modularize your projects.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e26940fd0a23" width="1" height="1" alt=""><hr><p><a href="https://medium.com/clean-android-dev/the-real-clean-architecture-in-android-modularization-e26940fd0a23">The “Real” Clean Architecture in Android: Modularization</a> was originally published in <a href="https://medium.com/clean-android-dev">Clean Android Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How To Avoid Use Cases Boilerplate in Android]]></title>
            <link>https://medium.com/clean-android-dev/how-to-avoid-use-cases-boilerplate-in-android-d0c9aa27ef27?source=rss-8f0052074f18------2</link>
            <guid isPermaLink="false">https://medium.com/p/d0c9aa27ef27</guid>
            <category><![CDATA[clean-architecture]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[functional-programming]]></category>
            <dc:creator><![CDATA[Denis Brandi]]></dc:creator>
            <pubDate>Wed, 24 Aug 2022 15:48:31 GMT</pubDate>
            <atom:updated>2022-08-29T09:08:18.870Z</atom:updated>
            <content:encoded><![CDATA[<h4>Exploring four different approaches</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gEq_Om0oEILtB31526pCxw.png" /></figure><p>Since the dawn of layered architectures, <a href="https://proandroiddev.com/why-you-need-use-cases-interactors-142e8a6fe576">Use Cases</a> have had a controversial reputation.</p><p>While on the one side, they help you adhere to <a href="https://betterprogramming.pub/the-real-clean-architecture-in-android-part-1-s-o-l-i-d-6a661b103451">S.O.L.I.D.</a> principles and improve your code readability; on the other, they are sometimes “useless” (the only thing they do is call a repository method).</p><p>Because of that, the industry converged on the following four approaches (to be used only when use cases are just a call to a repository method):</p><h3>Approach 1: Skip the Use Case</h3><p>With this approach, you have a Use Case only if it is doing something, while if it is “useless,” you call the repository directly.</p><p>Here’s an example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1f1a4018d350260aba4b80d236901850/href">https://medium.com/media/1f1a4018d350260aba4b80d236901850/href</a></iframe><h4>Pros</h4><ol><li>Less code to write</li><li>No redundancy: a change to the repository method will not require a Use Case change.</li></ol><h4>Cons</h4><ol><li>Inconsistency</li><li>Scalability: if the repository method requires extra parameters that are not coming from the presentation layer, all the VMs using it will need to be updated, and this, when it comes to core repositories, might be a big refactor.</li><li>ISP violation: repositories usually have many methods. Hence when you have a repository as a collaborator, your class will require a recompilation every time a method you are not using gets added, removed, or changed.</li><li>Cheating: my experience with this approach is that lazy engineers will find excuses not ever to have a Use Case and therefore overload either ViewModels or Repositories with business logic.</li></ol><h3>Approach 2: Keep the Use Case</h3><p>With this approach, you don’t care whether your use case is doing something or not since you are always going to have a use case:</p><p>Here’s an example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c5e9c81d50c1c48beda850ffc7196475/href">https://medium.com/media/c5e9c81d50c1c48beda850ffc7196475/href</a></iframe><h4>Pros</h4><ol><li>Consistency.</li><li>Scalability: if the repository method requires extra parameters not coming from the presentation layer, all the VMs using the use case won’t need to be updated because they are protected by the use case interface.</li><li>ISP adherence.</li></ol><h4>Cons</h4><ol><li>More code to write.</li><li>Redundancy: if your repository method signature changes for getting different parameters from the presentation layer, you will have to update the use case class, tests, and interface.</li></ol><blockquote>NB: when I say “parameters coming from the presentation layer” I don’t mean presentation models passed to the use case, I mean input coming from the presentation layer that is mapped into domain models.</blockquote><p>In pure OOP, these two approaches are the only options you have but when you add functional programming to the mixture, things change for the better.</p><h3>Approach 3: Functional Use Cases With Type Aliases</h3><p>A while ago, I came out with the <a href="https://medium.com/swlh/functional-use-cases-f896f92e768f">Functional Use Case approach</a>, where you have a function or a type alias instead of having an interface for the Use Case.</p><p>Here’s an example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bbabfd7539fb170036c51d0d580d5454/href">https://medium.com/media/bbabfd7539fb170036c51d0d580d5454/href</a></iframe><p>Because you don’t have an interface but a higher order function, you can inject whatever you want; therefore, swapping a repository method for a use case class is just a matter of updating the DI layer.</p><p>Overall, this was a good approach since it removes boilerplate, but given that most Android projects are heavily influenced by DI frameworks like Koin and Dagger, which require types to work, this approach came with an additional complexity for the DI layer.</p><p>In Dagger, if you have multiple suspend () -&gt; Answer&lt;List&lt;SomeModel&gt;, String&gt; you won’t be able to do the following:</p><pre>@Provides<br>@Singleton<br>fun provideGetSomeModelUseCase(<br>    someModelRepository: SomeModelRepository<br>): GetSomeModelUseCase {<br>    return someModelRepository::getSomeModels<br>}</pre><p>Unless for each specific function, you don’t add the ugly @Named hack.</p><p>In Koin, you won’t be able to do the following:</p><pre>single&lt;GetSomeModelUseCase&gt; {<br>    get&lt;SomeModelRepository&gt;()::getSomeModels<br>}</pre><h4>Pros</h4><ol><li>Less code to write.</li><li>No redundancy: a change to the repository method will not require a Use Case change.</li><li>Consistency.</li><li>Scalability: if the repository method requires extra parameters not coming from the presentation layer, all the VMs using the use case won’t need to be updated because they are protected by the use case interface.</li><li>ISP adherence.</li></ol><h4>Cons</h4><ol><li>Doesn’t work well with DI frameworks</li></ol><p>This was the best approach I could come up with back then, and as Howard Stark once said:</p><blockquote>“I’m limited by the technology of my time, but one day you’ll figure this out. And when you do, you will change the world. What is and always will be my greatest creation… is you.”</blockquote><h3>[FINAL] Approach 4: Functional Use Cases With Functional Interfaces</h3><p>After years, JetBrains answered my prayers and introduced <a href="https://kotlinlang.org/docs/fun-interfaces.html">Functional Interfaces (SAM)</a>.</p><p>Thanks to this Kotlin update, functions can be injected as Functional Interfaces, unlike type aliases, are “real types.”</p><p>Here’s an example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4ede858c8bd4e3e200a673918b966d3f/href">https://medium.com/media/4ede858c8bd4e3e200a673918b966d3f/href</a></iframe><p>The Dagger provides a function that can be fixed this way:</p><pre>@Provides<br>@Singleton<br>fun provideGetSomeModelUseCase(<br>    someModelRepository: SomeModelRepository<br>): GetSomeModelUseCase {<br>    return GetSomeModelUseCase(someModelRepository::getSomeModels)<br>}</pre><p>And the Koin provides function as well:</p><pre>single&lt;GetSomeModelUseCase&gt; {<br>    GetSomeModelUseCase(get&lt;SomeModelRepository&gt;()::getSomeModels)<br>}</pre><h4>Pros</h4><ol><li>Less code to write.</li><li>No redundancy: a change to the repository method will not require a Use Case change.</li><li>Consistency.</li><li>Scalability: if the repository method requires extra parameters that are not coming from the presentation layer, all the VMs using the use case won’t need to be updated because they are protected by the use case interface.</li><li>ISP adherence.</li><li>Work well with all DI frameworks</li></ol><h4>Cons: N/A</h4><p>We finally have a solution with no cons.</p><h3>Summary</h3><p>Use cases are a crucial part of clean architecture, and developers always had a love/hate relationship with them.</p><p>I hope that by applying this solution, you will love them more.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d0c9aa27ef27" width="1" height="1" alt=""><hr><p><a href="https://medium.com/clean-android-dev/how-to-avoid-use-cases-boilerplate-in-android-d0c9aa27ef27">How To Avoid Use Cases Boilerplate in Android</a> was originally published in <a href="https://medium.com/clean-android-dev">Clean Android Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The “Real” Clean Architecture in Android: S.O.L.I.D.]]></title>
            <link>https://medium.com/clean-android-dev/the-real-clean-architecture-in-android-part-1-s-o-l-i-d-6a661b103451?source=rss-8f0052074f18------2</link>
            <guid isPermaLink="false">https://medium.com/p/6a661b103451</guid>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Denis Brandi]]></dc:creator>
            <pubDate>Mon, 18 Jul 2022 18:24:01 GMT</pubDate>
            <atom:updated>2023-06-20T14:03:06.945Z</atom:updated>
            <content:encoded><![CDATA[<h4><em>If you think good architecture is expensive, try bad architecture. ~ </em>Brian Foote and Joseph Yoder</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b69nu6FaKG4ofQGPpAnc4A.png" /><figcaption>Image by author</figcaption></figure><p>Clean Architecture has been probably the hottest topic in the Android community in the past few years and this trend doesn’t seem to go away (thankfully).</p><p>This series is based on the following books and documentation:</p><ol><li><a href="https://www.amazon.com/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882/ref=sr_1_1?crid=9GR6QM8XY4T9&amp;keywords=the+clean+code&amp;qid=1657047914&amp;sprefix=the+clean+code%2Caps%2C186&amp;sr=8-1">Clean Code by Robert C. Martin</a></li><li><a href="https://www.amazon.com/Clean-Architecture-Craftsmans-Software-Structure/dp/0134494164/ref=sr_1_1?keywords=clean+architecture&amp;qid=1657047966&amp;sprefix=clean+ar%2Caps%2C180&amp;sr=8-1">Clean Architecture by Robert C. Martin</a></li><li><a href="https://www.amazon.com/Patterns-Enterprise-Application-Architecture-Martin/dp/0321127420/ref=sr_1_1?keywords=pattern+of+enterprise+application+architecture&amp;qid=1657048013&amp;sprefix=pattern+of+enter%2Caps%2C193&amp;sr=8-1">Patterns of Enterprise Application Architecture by Martin Fowler</a></li><li><a href="https://www.amazon.com/Domain-Driven-Design-Tackling-Complexity-Software/dp/0321125215/ref=sr_1_1?keywords=domain+driven+design&amp;qid=1657048072&amp;sprefix=Domain+dri%2Caps%2C182&amp;sr=8-1">Domain-Driven Design by Eric Evans</a></li><li><a href="https://alistair.cockburn.us/hexagonal-architecture/">Hexagonal Architecture by Alistair Cockburn</a></li><li><a href="https://jeffreypalermo.com/2008/07/the-onion-architecture-part-1/">Onion Architecture by Jeffrey Palermo</a></li></ol><p>All these authors agree on most things but sometimes they tend to take a different route and <em>so do I</em>! <br>Therefore this series won’t be a summary of the source material, but an opinionated approach to Clean Architecture based on the preference of the majority of experts in the field and mine.</p><p>PS: In this article, I’m not going to say <strong>what you want to hear</strong> but <strong>what you need to hear.</strong></p><h3>What is Clean Architecture?</h3><p>To start, let’s say what CA is not:</p><ol><li>A template to follow</li><li>An unnecessary boilerplate that slows you down (unless you do it wrong)</li><li>A new trendy architecture that works only on Android (looking at you iOS, Web, and Backend guys)</li></ol><blockquote><em>So what is Clean Architecture?</em></blockquote><p>The short answer is:</p><blockquote>Clean Architecture is the outcome of the S.O.L.I.D. principles.</blockquote><p><em>Hence if you don’t follow them you are not doing CA, you are just following a template that will never make sense.</em></p><p>My rant against other articles is that they rarely mention S.O.L.I.D principles and they focus only on the separation of concerns part (SRP), and because of that, they leave the reader with more doubts than they had before reading the article: <em>why does that use case have a single method? why do I need that interface there? why do I need a different object and mappers?</em></p><p>The answer to all these questions is in the S.O.L.I.D. principles so in part 1 I will focus on the theory and I will show how each principle shapes Clean Architecture, then I will deep dive into each component in the following articles.</p><h3>S.O.L.I.D.</h3><p>What you need to realize is that S.O.L.I.D. principles are not just a myth or a bullet point you need to put on your CV.</p><p><strong><em>They are the benchmark to determine how clean your code is.</em></strong></p><p>You don’t know if you have the right design? <em>Check if your code adheres to S.O.L.I.D.</em> just like a doctor would check your blood test, if something is wrong your blood test will tell, the same is for S.O.L.I.D. and your code.</p><p>Now, just because a principle has been violated, it doesn’t mean you are going to have issues but if you have issues, bugs or you are less productive you are most likely breaking one or more S.O.L.I.D. principles.</p><p><em>Look at S.O.L.I.D. principles as common-sense disciplines that can help you stay out of trouble, you may not have to use them always but </em><strong><em>you better know them!</em></strong></p><h3>Liskov Substitution Principle</h3><blockquote>Derived classes must be substitutable for their base classes.</blockquote><p>Inheritance is the tightest coupling you can have, <em>bad usage of it leads to highly-coupled and lowly-cohesive code</em>.</p><p>Most inexperienced engineers use inheritance as the primary way to achieve reusability but this often makes maintenance almost impossible to achieve (and just so you know, repeating code is much better than coupling code, maintenance &gt; reusability).</p><p>Because this used to be very common in the early days of Object-Oriented Programming, even among senior developers, <strong>the LSP was the main principle used to regulate inheritance</strong>.</p><p>Let’s have a look at this over-simplistic example (which is not the usual square/rectangle example you’ll see around) where the LSP is violated:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0cdb1014cdc22dba4b89fc0d584d7dc1/href">https://medium.com/media/0cdb1014cdc22dba4b89fc0d584d7dc1/href</a></iframe><p>Before you wonder, no the LSP is not violated because Android Developers are underpaid (although it would make a good argument 😈).</p><p>In this scenario, the developer decided to make CTO a subclass of Employee for reusing the getSalary method and because of that now the app could crash if the method getLineManager is called on a CTO object.</p><p>I know for certain that 99% of you wouldn’t have made this mistake because you know that a CTO is a <em>chief</em> and not an <em>employee</em> but not always relationships are clear in the codebase.<br>In fact, I bet that you have seen many projects with massive BaseActivity, BaseFragment , BaseViewModel…. classes, that is another clear example of LSP violation.</p><blockquote>So it is fine to use inheritance as far as I don’t break the LSP?</blockquote><p>Instead of using inheritance and then switching to another approach if LSP is violated, <strong><em>you should change your way of thinking and default to composition</em></strong>.</p><p>99% of the things you want to do with inheritance can be done with composition so you should always <strong><em>favor</em> <em>composition over inheritance</em></strong>.<br>If by any chance composition cannot be used, even with the help of any of the <strong>G.o.F. design patterns, </strong>then you can use inheritance (by making sure you adhere to the LSP!).</p><blockquote>What are the most common scenarios in which inheritance is fine to use?</blockquote><p>There are a couple of scenarios where inheritance (IS-A relationship) is fine to use instead of composition (HAS-A relationship), or maybe it isn’t but you are forced to use it, for example:</p><ol><li>When the framework you are using requires you to use it (extending Activities, Fragments, ViewModels…)</li><li>When doing data modeling (Animal -&gt; Mammals…)</li></ol><p>Excluding models and frameworks, <em>usually</em>, architectural components should not rely on inheritance, hence any architecture relying on inheritance is far from being good and clean.</p><h4>Testing</h4><p>Testing inheritance is always painful and requires more effort than testing composition.</p><p>When implementing a new subclass you not only have to test the new public methods added and the ones that you are overriding from the parent class, but <em>you also have to test all the other methods of the parent class that you are not overriding!</em></p><p><em>After all, you don’t want changes to the parent class to break your subclass behavior, don’t you?</em></p><p><em>Testing composition instead is a piece of cake since your tests won’t care about how the collaborator works, they will only care about your collaborator’s contract which can easily be mocked/stubbed/faked… if required.</em></p><p><em>References:<br></em><strong><em>* </em></strong><em>Clean Architecture, Chapter 9 </em>(<strong>LSP</strong>)<em><br>* </em><a href="https://www.youtube.com/watch?v=-Z-17h3jG0A&amp;ab_channel=TuringAwardeeClips"><em>Origin of LSP</em></a></p><h3><strong>S</strong>ingle Responsibility Principle</h3><blockquote>A class should do one, and only one, thing.</blockquote><p>Hmmm… you meant <em>“A </em><strong><em>function</em></strong><em> should do one, and only one, thing?”. <br></em><strong>The wrong principle</strong>, try again.</p><blockquote>A class should have one, and only one, reason to change.</blockquote><p>Better, but maybe rephrase it in a way that explains what that <em>“reason to change”</em> is…</p><blockquote><em>A class should be responsible to one, and only one, actor (group of users or stakeholders).</em></blockquote><p>Now we are talking!<br>I’m using the term <em>“class”</em> because we work in the Java-Kotlin realm, a more generic description is a “<em>module (not a java module) or a source file that contains a cohesive set of functions and data structures</em>”.</p><p><em>“Cohesion”</em> is the keyword in the SRP: the methods of the class must be cohesive, if they are not you should move those methods to another class.</p><p>Who are the actors? There are actually many, and therefore there are going to be many classes. <em>“Logging in”</em> and <em>“Making a purchase”</em> will most likely interest different actors, the <em>onboarding team</em> and the <em>sales team</em> for example. So putting them in the same class would be a violation.</p><p>To top that, the <em>“Logging in”</em> feature will interest not only a PO but also the UI/UX Designers that defined how the user interaction is performed and the BE team that provided you the REST API (plus other actors that might be involved).</p><p>These actors, even if all involved in the same feature will want to be independent of each other as much as possible and will not want to be affected by other actors (UI changes shouldn’t break your API code, API changes shouldn’t break your UI code, both UI changes and API changes shouldn’t break your business logic code).</p><blockquote>Conway’s law: The best structure for a software system is heavily influenced by the social structure of the organization that uses it so that each software module has one, and only one, reason to change.</blockquote><p>This brings in the concept of vertical and horizontal slicing: <strong>features </strong>(login, search, purchase…)<strong> </strong>and <strong>layers </strong>(presentation, domain, data…..).</p><p><em>A feature set per cross-functional team.</em><br><em>A layer for each actor of that cross-functional team.</em></p><p>I will elaborate more on vertical and horizontal slicing in the next articles.</p><h4>From SRP to CCP</h4><p>At the <strong>component level,</strong> the<strong> SRP </strong>becomes the <strong>Common Closure Principle (CCP) </strong>which can be phrased in the following way:</p><blockquote><em>Gather into components those classes that change for the same reasons and at the same times.</em></blockquote><blockquote><em>Separate into different components those classes that change at different times and for different reasons</em>.</blockquote><p>The<strong> CCP</strong> is one of the most important principles to follow for having a rock-SOLID <strong>modularization</strong> (another topic I’ll cover in the following articles).</p><p>By only applying the SRP this is how the architecture of the system would look like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/971/1*ce3NgapFzBamtg1Xqt_H3w.png" /><figcaption>Outcome of SRP</figcaption></figure><p>Again, I will explain each component in the following articles.</p><p><em>References:<br></em><strong><em>* </em></strong><em>Clean Architecture, Chapter 7 (</em><strong><em>SRP</em></strong><em>)<br></em><strong><em>* </em></strong><em>Clean Architecture, Chapter 13 (</em><strong><em>CCP</em></strong><em>)<br>* Patterns of Enterprise Application Architecture, Chapter 1</em></p><h3>Dependency Inversion Principle</h3><blockquote>The most flexible systems are those in which source code dependencies refer only to abstractions, not to concretions.</blockquote><p>This is the easiest principle to follow and yet it is the one that has been more brutally violated by developers.</p><p>Somehow developers think that you should have an interface <em>“only in the case of multiple implementations”</em>.<br><strong>This couldn’t be more wrong.</strong></p><p>Any modern Software Architecture worth its name (Hexagonal, Onion, Clean) heavily relies on the DIP.<br><strong><em>We do not want our high-level business rules to depend upon low-level details.<br></em>We want the isolation of high-level abstractions from low-level details.</strong></p><p>Many developers struggle to understand the problem of isolation because they are not aware of how the compiler works, of transitive dependencies or <em>that they start writing code from the wrong class (more on this in the next article).</em></p><p>Let’s use the diagram from the previous chapter (SRP) as an example, where all the arrows point in the same direction:</p><pre>View -&gt; ViewModel -&gt; Interactor -&gt; Repository -&gt; Data Store...</pre><p>The class ViewModelwill have an import for the Interactor .<br>The class Interactor will have an import for the Repository …. and so on.</p><p>What many developers don’t know is that the ViewModel also imports the Repository and the DataStore <strong><em>transitively</em></strong>.<br>Any change to the Data Store will trigger the recompilation of the Repository which will cause the recompilation of the Interactor and the ViewModel and so on.. up to the first class of the <strong>Flow of Control</strong>.</p><p>A good Architecture is supposed to isolate changes, not propagate them everywhere.</p><p>On top of that not only does the arrows’ direction dictates the compilation but it also dictates the first class the developer is going to write, the Data Source in this case, which as we will see in the next articles is the wrong class to start implementing.</p><p>If we apply the DIP principle to the diagram of the previous chapter, this is how it will look like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*ySw5cRfql7kUhMYEiDADhg.png" /><figcaption>The outcome of SRP + DIP</figcaption></figure><h4>Testing</h4><p><strong><em>Testability</em></strong> is also heavily affected by this principle.<br>Once you have an interface, creating a test double becomes a mainstream job.</p><blockquote>But I use Mockito, I don’t need interfaces for testing…</blockquote><p>Yes I know, you can still “mock” the behavior of the collaborator by using a mocking framework that uses <em>reflection</em> under the hood.<br>But I also know that Mocking frameworks <em>make tests slower</em>. In fact, on my machine, every time I run a test class, Mockito adds an extra 5–10 seconds to the execution time, and this for a TDDer means waiting 5–10 extra seconds for each TDD cycle (which is still faster than not doing TDD at all btw).</p><p><em>PS: the 5–10 extra seconds become a minor problem when you run the tests on your CI since this is the time that Mockito takes to start for each module (</em><a href="https://github.com/mockk/mockk/issues/13"><em>The same thing will happen with Mockk</em></a><em> in case you are thinking that by switching framework you would solve the problem).</em></p><p>The last advantage of creating your own test double instead of using a mocking framework is that you never have to reference the collaborator’s method.</p><p>For example, when mocking using Mockito you are doing something like this:</p><pre>@Test<br>fun test1() {<br>    whenever(collaborator.method()).thenReturn(...)<br>    //...<br>}</pre><pre>@Test<br>fun test2() {<br>    whenever(collaborator.method()).thenReturn(...)<br>    //...<br>}</pre><pre>@Test<br>fun test3() {<br>    whenever(collaborator.method()).thenReturn(...)<br>    //...<br>}</pre><pre>//... you got the point</pre><p>While, when you create your own test double:</p><pre>class CollaboratorTestDouble: Collaborator {<br>    fun mockMethod(...) { ... }</pre><pre>    override fun method() {<br>        // stub, mock, spy...<br>    }<br>}</pre><p>Your tests won’t reference the method anymore:</p><pre>@Test<br>fun test1() {<br>    collaborator.mockMethod(...)<br>    //...<br>}</pre><pre>@Test<br>fun test2() {<br>    collaborator.mockMethod(...)<br>    //...<br>}</pre><pre>@Test<br>fun test3() {<br>    collaborator.mockMethod(...)<br>    //...<br>}</pre><pre>//... </pre><p>And by not referencing the collaborator’s methods your tests are more protected from method signature changes, which ends up with less code to update and less code to review.<br>Tests also look more readable.</p><p>Sometimes you may not even have to create a test double because you can just <strong>use a real implementation. <br></strong>This is usually preferable when such implementation <strong>requires minimal setup</strong> (it has no collaborators) and it was created before the current class under test.</p><p>Some other times mocks just don’t work well at all. <br>Think about the SharedPreferences.Editor interface, every method returns the object instance and the transaction is not executed until apply or commit is invoked.<br>Many here give up with the mocking and just move the test to androidTest folder so they can use the real preferences but that in my opinion is a complete failure.<br>The fastest and cleanest solution is to create a <strong>fake </strong>like the following:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3aa463df5fd1c279d59a06891ca3fb57/href">https://medium.com/media/3aa463df5fd1c279d59a06891ca3fb57/href</a></iframe><p>This fake uses an in-memory implementation of the SharedPreferences interface.<br>By using this in your test class there is no setup required and you can pre-set your preferences by just doing <br>fakePreferences.putString(&quot;key&quot;, &quot;value&quot;).apply() <br>just like you would do with real SharedPreferences in androidTest with the difference that with this approach your tests will run on the <strong>JVM</strong> and will be much faster (and obviously faster than using mocks).</p><h4>A funny story</h4><p>A few years ago Mockito didn’t have support for final classes and when developers were migrating their codebases from Java to Kotlin (where classes are final by default) their tests were failing.</p><p>That was a clear sign of their bad architecture and at that point, there were only a clean solution (adding an abstraction) and a dirty solution (making classes open).</p><p>Which solution do you think most developers adopted? 😈</p><p>Let’s just say that I know many companies that did a big refactoring PR for removing open keyword everywhere once Mockito released their mock-maker-inline workaround (that still doesn’t work for spy and cannot be used in androidTest btw).</p><p><em>References:<br></em><strong><em>* </em></strong><em>Clean Architecture, Chapter 11 </em>(<strong>DIP</strong>)<em><br>* </em><a href="https://alistair.cockburn.us/hexagonal-architecture/"><em>Hexagonal Architecture</em></a><em><br>* </em><a href="https://jeffreypalermo.com/2008/07/the-onion-architecture-part-1/"><em>Onion Architecture, Part 1</em></a><em><br>* </em><a href="https://martinfowler.com/articles/mocksArentStubs.html"><em>Martin Fowler, Mocks Aren’t Stubs</em></a></p><h3>Interface Segregation Principle</h3><blockquote><em>Keep interfaces small so that users don’t end up depending on things they don’t need.</em></blockquote><p>This is one mainly for us, statically-typed language users, in fact in dynamically-typed languages developers may even get away with just <strong>S.O.L.D. </strong>instead of<strong> S.O.L.I.D. </strong>(there are still benefits in adhering to the ISP in dynamically typed languages but I won’t cover them since Android is based on Java/Kotlin anyway).</p><p>The ISP can be seen as an extension of the DIP, given that you can’t have small interfaces if you don’t have interfaces at all 😉.</p><p>While with the DIP the purpose is to protect your code from the flow of control and transitive dependencies, with the ISP <em>we make sure our collaborators not only are interfaces (or any other type of abstractions) but they are also small so we don’t depend on something we don’t use, that when changed, will cause an extra recompilation</em>.</p><p>Let’s take a look at this example:</p><pre>interface UserService {<br>    fun login(...)<br>    fun logout(...)<br>    fun createAccount(...)<br>    //...<br>}</pre><pre>class LoginViewModel(<br>    private val userService: UserService<br>): ViewModel() {<br>    fun doSomething() {<br>        //...<br>        userService.login(...)<br>        //...<br>    }<br>}</pre><p>LoginViewModel uses only one method of UserService yet it is depending on all of them + all the object parameters they require.<br>This means that a change in logout will recompile LoginViewModel.<br>And also adding/removing methods to UserService will cause a recompilation.</p><p>How do you solve this? Simple, instead of having a big interface you create more and smaller interfaces:</p><pre>interface LoginInteractor {<br>    fun execute(...)<br>}<br>interface LogoutInteractor {<br>    fun execute()<br>}<br>interface CreateAccountInteractor {<br>    fun execute()<br>}<br>//...</pre><h4>ISP and SRP</h4><p>If it wasn’t clear already, S.O.L.I.D. principles are not independent of each other, so by following one you are most likely following also some others, and by breaking one, you are most likely breaking also some others (this is the reason why most developers break most of them).</p><p>Classes can implement interfaces, so if interfaces are small then classes are most likely following the SRP.</p><p><em>After all, which class do you think is more likely to break the SRP? <br>A class with a single method or a class with 100 methods?</em></p><p>Sometimes instead you want small interfaces but slightly bigger classes.<br><em>Interfaces are preferably small because they are optimized for the classes that use them.</em><br>Classes instead should be responsible for 1 thing, this often makes them smaller but as the SRP says, you should not split one responsibility into multiple classes since you are meant to aggregate cohesive methods in a single class.</p><p>What to do in this case? <br>Simple, <em>you make your class implement multiple interfaces</em>!</p><h4>From ISP to CRP</h4><p>At the <strong>component level,</strong> the <strong>ISP</strong> becomes the <strong>Common Reuse Principle (CRP) </strong>which can be phrased in the following way:</p><blockquote><em>Don’t force users of a component to depend on things they don’t need.</em></blockquote><p>This is another important principle for modularization.<br><em>Classes that are reused together should be part of the same component.<br></em>Like the CCP it tells us how to group classes but it also tells us which classes are not to keep together under the same component.</p><p>Just like a class recompiles when an unused collaborator’s method changes, a <em>component</em> recompiles when an unused class of an <em>imported component </em>changes.</p><h4>Testing</h4><p>When creating a test double it is quite annoying having to deal with big interfaces since you have to stub/mock all the methods of the interface.</p><p>In order to avoid this issue, you can either <strong>use a mocking framework </strong>or <strong>adhere to the ISP.</strong></p><p>Personally, I’m not against mocking frameworks, I actually use them in all my projects but what I don’t like is that by using them developers can be tempted to break 1 or more principles:</p><ul><li>Because you can mock classes, you might be tempted to avoid interfaces (DIP 💔)</li><li>Because you don’t have to mock all the methods, you might be tempted to keep big interfaces/classes (SRP and ISP 💔)</li></ul><p>Adhering to S.O.L.I.D. principles makes testing easier and <em>removes the need to use mocking frameworks.<br></em>Somehow Android Developers think that they can’t test their code if they don’t use mocking frameworks, unlike iOS developers that tend to stay as vanilla (classicists) as possible. <br><em>This is because Java/Kotlin library developers have done very good marketing in the past years and </em><strong><em>not because unit testing was born with mocking in mind</em></strong>.</p><p>My take is that choosing between Mocking Frameworks and Test Doubles is up to your team’s preference (<em>if that is the only way your team is going to write tests then it is the right way</em>) but <strong>your code should be testable regardless of the mocking strategy you use</strong>!</p><p>References:<br>* Clean Architecture, Chapter 10 (<strong>ISP</strong>)<br>* Clean Architecture, Chapter 13 (<strong>CRP</strong>)</p><h3>Open-Closed Principle</h3><blockquote><em>A software artifact should be open for extension but closed for modification.</em></blockquote><p>The ultimate goal of software architecture is to add new features without having to rewrite or recompile any existing code.<br>This is because every time you modify existing code you may introduce regression bugs and break previously built functionalities, not to mention merge conflicts and very big pull requests!</p><p>The OCP is the least independent S.O.L.I.D. principle and the one you should monitor the most, in fact, breaking any other principle will most likely break the OCP too:</p><ol><li><strong>When LSP is violated</strong>, hence inheritance is used in the wrong way, adding a subclass may require a <strong>modification of the parent class</strong> in order to not break other subclasses.</li><li><strong>When SRP is violated</strong>, hence a class belongs to more than 1 actor, whenever an actor requires a new integration then that new integration will <strong>modify an existing method</strong> which will affect also the other actors.</li><li><strong>When DIP is violated</strong>,<strong> </strong>hence concrete classes depend on concrete classes (creating also transitive dependencies), adding a new method somewhere will require a <strong>recompilation</strong> of all the classes up to the start of the flow (and yes, if you were wondering, recompilation counts as modification too).</li><li><strong>When ISP is violated</strong>, hence collaborators&#39; abstractions have more methods than required, adding a new method to a collaborator will <strong>recompile</strong> also classes that don’t use that method.</li></ol><blockquote>So if I follow the other 4 principles, do I get this one for free?</blockquote><p>No, unfortunately.</p><p>There are other ways you can break the OCP without breaking the other principles, but luckily it is very easy to detect these extra scenarios.</p><h4>Flag Arguments AKA “Magic Booleans”</h4><p>How many times have you thought<em> “I’ll just add a boolean here, if true I do A and if false I do B”?</em></p><p>That’s a modification of existing code where you support the integration of B by adding a boolean.</p><p>Instead of adding a boolean and modifying an existing function, add a new function.</p><p>For example, instead of:</p><pre>fun pay(isDebitCard: Boolean) { ... }</pre><p>do:</p><pre>fun payWithDebitCard() { ... }</pre><pre>fun payWithCreditCard() { ... }</pre><h4>Enums</h4><p>They present the same problem of flag arguments but the chance of breaking existing features is even higher since you can have a lot of values, unlike booleans where you have at most 2 values (unless you are passing more than one boolean 😈).</p><p>So again, instead of:</p><pre>enum class PaymentType {<br>    DEBIT_CARD, CREDIT_CARD, BANK_TRANSFER, GOOGLE_PAY<br>}</pre><pre>fun pay(paymentType: PaymentType)</pre><p>do:</p><pre>fun payWithDebitCard() { ... }</pre><pre>fun payWithCreditCard() { ... }</pre><pre>fun payWithBankTransfer() { ... }</pre><pre>fun payWithGooglePay() { ... }</pre><p>This way adding a payment method cannot break the previously implemented payment methods and doesn’t require recompilation of all the classes importing the enum.</p><blockquote>Does this mean I can’t ever use flags and enums?</blockquote><p>It is nearly impossible to write software without ever using flags and enums so, obviously, not all your classes and functions will strictly adhere to the OCP.<br>The important thing is that when you have to use a flag argument or an enum your function does only that if/else or when statement and nothing else.</p><p>References:<br>* Clean Architecture, Chapter 8<br>* Clean Code, Chapter 3</p><h3>Summary</h3><p>We can summarize the principles in the following way:</p><ol><li>SRP: Classes should belong to a single actor</li><li>OCP: New integrations shouldn’t touch existing code</li><li>LSP: Use inheritance properly and favor composition</li><li>ISP: Abstractions should be as small as possible</li><li>DIP: Collaborators should be abstractions</li></ol><h3>Last Notes</h3><p>I know that S.O.L.I.D. principles are not the most interesting topic and that the article was long but hopefully now you have a better understanding of the theory behind Clean Architecture.</p><p>If you are still struggling to understand them don’t worry, we will see how they work in practice in the next articles.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6a661b103451" width="1" height="1" alt=""><hr><p><a href="https://medium.com/clean-android-dev/the-real-clean-architecture-in-android-part-1-s-o-l-i-d-6a661b103451">The “Real” Clean Architecture in Android: S.O.L.I.D.</a> was originally published in <a href="https://medium.com/clean-android-dev">Clean Android Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Practical Test Pyramid]]></title>
            <link>https://medium.com/tide-engineering-team/the-practical-test-pyramid-c4fcdbc8b497?source=rss-8f0052074f18------2</link>
            <guid isPermaLink="false">https://medium.com/p/c4fcdbc8b497</guid>
            <category><![CDATA[automation-testing]]></category>
            <category><![CDATA[agile]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[test-pyramid]]></category>
            <category><![CDATA[unit-testing]]></category>
            <dc:creator><![CDATA[Denis Brandi]]></dc:creator>
            <pubDate>Tue, 30 Jun 2020 08:26:38 GMT</pubDate>
            <atom:updated>2020-06-30T08:26:38.171Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rrC66mhwq48xlGGJ0FC03w.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@yeeeeeeha">Daniel Gregoire</a> on <a href="https://unsplash.com/">Unsplash</a></figcaption></figure><blockquote>Why do we write tests?</blockquote><p>Every company knows this absolute truth: <a href="https://raygun.com/blog/costly-software-errors-history/"><em>bugs cost money</em></a><em>.</em></p><blockquote>Nasa’s Mars Climate Orbiter bug: <strong>$125 million</strong></blockquote><blockquote>Ariane 5 Flight 501 bug: <strong>$500 million</strong></blockquote><blockquote>EDS Child Support System bug: <strong>+ $ 1 billion</strong></blockquote><blockquote>Japanese bitcoin exchange, Mt. Got, bug: <strong>+ $ 500 million</strong></blockquote><p>This truth creates the need for testing before going live.<br>Startups and small-sized companies heavily rely on <strong><em>Manual Testing </em></strong>and<strong><em> </em></strong>their focus is on delivering <strong><em>the minimum viable product.</em></strong> <br>Code quality is not a priority, which is understandable considering that there are limited funds and resources.</p><p>However, this comes with a cost.</p><h3>The Butterfly Effect</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/870/1*Mqkih2JDEgKMtqUzx_Ix2Q.png" /><figcaption>Photo by <a href="https://www.pexels.com/@jimbear?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Jimmy Chan</a> from <a href="https://www.pexels.com/photo/butterflies-perched-on-flower-1321524/?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Pexels</a></figcaption></figure><p>After the initial <strong>MVP</strong>, subsequent releases are built on top of clunky and untestable code, manual testers have more and more journeys to test and even <strong><em>integrating small changes can create major issues.</em></strong><br>These issues are discovered only at a later stage and fixing it and retesting it almost doubles the initial development effort (and that’s after only the second sprint, it gets worse over time).<br>The team has now started suffering the <a href="https://en.wikipedia.org/wiki/Butterfly_effect">butterfly effect</a>.</p><p>Manual testing requires a lot of time and so does writing new code: it’s time to speed up and automate the process…</p><p>The team can’t yet write isolated tests because the code is untestable (god objects, no dependency injection, unmockable asynchronous logic) and so it has to start from the tests that require you to only mock UI interactions.<br>If some parts of the codebase have been refactored over and over again, at each release, most probably they are now in a better state so some integration or even unit testing may also be attempted.</p><h3>The Test Ice-Cream Cone (Anti-Pattern)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/556/1*w5jFBx3FMeEbr4i9_fjq8A.png" /></figure><p>The team has automated tests and clearly, things are going better than before, however, this testing approach is still very expensive.</p><p><strong>UI tests</strong> take a lot of time to write, they are slow, flaky (they return false negatives) and they require the whole system to be up and running: servers, databases, dependencies, frameworks… plus all the test data you might possibly need.<br>They are also not telling where the issues are, in fact, you might not see any reference to your code at all.<br>And they also don’t give you enough coverage: it is nearly impossible to cover all the scenarios because of all the combinations of the separate units involved.</p><p><strong>Integrated tests</strong> appear in a smaller percentage, they run faster and they require less setup, they are also not flaky. Still, a failing test will not tell where the issue is, and <a href="https://blog.thecodewhisperer.com/permalink/integrated-tests-are-a-scam">covering all the scenarios is still hard and expensive</a>.</p><p><strong>Unit tests, </strong>which<strong> </strong>are almost not present, run in a few milliseconds, they require almost no setup and any failure points to the specific line where the error is.</p><p>At this stage, most of the tests are slow, non-deterministic, and expensive to write and maintain.</p><p>The team now realizes that the distribution of the tests is wrong and it is better to “focus” on the cheaper tests and improve the code quality.</p><h3>From Cone to Pyramid</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UG7Dx7pdPKbgilYeFb5avQ.png" /><figcaption><strong>Icons by </strong><a href="http://svgrepo.com"><strong>svgrepo.com</strong></a></figcaption></figure><p>In 2003, <strong>Mike Cohn and Lisa Crispin </strong>came up with the <strong>Test Automation Pyramid </strong>(described in Cohn’s 2009 book <a href="https://www.amazon.com/gp/product/0321579364?ie=UTF8&amp;tag=martinfowlerc-20&amp;linkCode=as2&amp;camp=1789&amp;creative=9325&amp;creativeASIN=0321579364">Succeeding with Agile</a>): this was a metaphor used to explain how to group different kinds of tests and how many tests of each group we should have.<br>The pyramid clearly states 3 levels of tests: small, medium, and large (respectively bottom, middle, and top).</p><p><strong>Unit Tests</strong> should be the primary focus, they are cheap, fast, and point exactly to the lines of code where the bug is.<br>These tests are used for testing the logic in the code does what the programmer thought it would.<br>Having a wide set of Small Tests means that code is highly testable, hence it is also clean and flexible.</p><p><strong>Service Tests </strong>are not as productive as <strong>Unit Tests</strong>, in fact, they are meant to be used only for checking that all the units from the service layer to the infrastructure layer work well together and that external dependencies are integrated correctly.</p><p><strong>UI Tests</strong> (or End-to-End tests, which are the same thing for Mike Cohn) are the least productive ones: it takes an order of magnitude longer to run them compared to other tests and they are also more fragile since even a small UI change can break them.<br>For these reasons, they should be used more sparingly, only for the important end to end style smoke tests.</p><p>Although this pyramid gives a clear representation of levels and distribution, it is not very clear what <strong>Service Tests</strong> really mean. <br>This middle layer is not clear to many and Mike Cohn himself made the observation that <a href="https://www.mountaingoatsoftware.com/blog/the-forgotten-layer-of-the-test-automation-pyramid">it is usually ignored</a>, which makes developers jump to the top level even when unnecessary.</p><p>Also, what happened to Manual Testing? Can we really be confident without it?</p><h3>The “Practical” Testing Pyramid</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8NtJX228Arq5fjB4LCv8jw.png" /></figure><p><strong>Alister Scott</strong> improved the initial <strong>Cohn’s Pyramid</strong> and put more emphasis on the medium level tests and the manual exploratory tests.<br>We now have 3 levels of the pyramid dedicated to <em>Automated Tests, </em>and the last level to<em> Manual tests.</em></p><h4>Service Tests</h4><p>The level that Cohn was calling Service Tests is now a group that consists of the following tests:</p><ul><li><strong>Component Tests</strong>: these are meant to be a cheaper version of E2E tests where instead of starting from the user interactions they start from the service layer and they go down to the infrastructure layer (database, network services…).<br>In modern layered architectures, the service layer would be represented by Application Services/Use Case Interactors (in Clean, Onion, Hexagonal architectures). <br>In case you are familiar with <a href="https://martinfowler.com/bliki/PresentationDomainDataLayering.html">Presentation-Domain-Data-Layering</a>, the name <a href="http://www.codingthearchitecture.com/2015/03/08/package_by_component_and_architecturally_aligned_testing.html">Component</a> is used to represent the Domain-Data block (where Application is part of Domain).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/551/1*ZNFlwpdjbowQ7QHjNRdvsg.png" /><figcaption>Component Testing</figcaption></figure><ul><li><strong>Integration Tests</strong>: these are often confused with the above but they actually refer to the <a href="https://blog.thecodewhisperer.com/permalink/integration-tests-are-a-scam-is-a-scam">integration points between subsystems, systems, or any nontrivial client/supplier relationship</a>.<br>They are almost as small as unit tests but they are not isolated since they test external communications, and not as fast since they require to run on a real environment.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/284/1*pf1QsRCnZz7Rkob8GZ7b2w.jpeg" /></figure><ul><li><strong>API Tests or </strong><a href="https://martinfowler.com/bliki/ContractTest.html"><strong>Contract Tests</strong></a>: the integration with external services cannot be tested through <strong>Integration Tests</strong>, it would return unpredictable results, and it would be impossible to set up a test for verifying a specific condition such as failures or update operations.<br>For these reasons in <strong>Contract Testing</strong> specific mocking libraries are used, such as <a href="https://docs.pact.io/how-pact-works#slide-1">Pact</a>. These “special mocks” generate one contract file (pact file) for the “Consumer” (client) and one for the “Provider” (server) which then are matched through a <a href="https://docs.pact.io/pact_broker/">Broker</a>.<br>A failing match means that either the Consumer or the Provider at some point broke the contract.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/284/1*izF5Dul4gSYRBPJElMBtHw.jpeg" /></figure><h4>Manual Exploratory Tests</h4><p>The second improvement of <strong>Scott’s Pyramid </strong>is that it is now clear that manual testing is still needed. <br>It doesn’t matter how diligent your effort in automation testing can be, you can’t be 100% sure that everything is covered by automation and not everything can be automated, like design and usability.<br>For these reasons, you should add <strong>Manual Exploratory Testing</strong> on top of your automated tests.</p><p>With <strong>Exploratory Testing, </strong>you try to find a way to break your application and you also record all the lags, slow responses, design issues, and non-user-friendly behaviors.<br>If you find a bug, check if you can create an automated test for it, if you can it means something went wrong during development so try to keep it in mind and avoid making the same mistake in the future.</p><h3>Conclusion</h3><p>Testing terminology has been more and more confusing over the years so don’t become too attached to names, just make sure your team has a common vocabulary.</p><p>For new implementations start from the bottom of the pyramid and focus on the design of the code, those are the tests that give you coverage and are easier to implement, the higher up in the pyramid the more knowledge about testing is required.<br>For legacy code instead, make sure you have some wider tests that give you enough confidence before starting the refactoring.</p><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c4fcdbc8b497" width="1" height="1" alt=""><hr><p><a href="https://medium.com/tide-engineering-team/the-practical-test-pyramid-c4fcdbc8b497">The Practical Test Pyramid</a> was originally published in <a href="https://medium.com/tide-engineering-team">Tide Engineering Team</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Functional Use Cases]]></title>
            <link>https://medium.com/swlh/functional-use-cases-f896f92e768f?source=rss-8f0052074f18------2</link>
            <guid isPermaLink="false">https://medium.com/p/f896f92e768f</guid>
            <category><![CDATA[use-cases]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[clean-architecture]]></category>
            <category><![CDATA[functional-programming]]></category>
            <dc:creator><![CDATA[Denis Brandi]]></dc:creator>
            <pubDate>Fri, 29 May 2020 09:09:03 GMT</pubDate>
            <atom:updated>2023-01-02T22:11:18.263Z</atom:updated>
            <cc:license>http://creativecommons.org/licenses/by/4.0/</cc:license>
            <content:encoded><![CDATA[<h3>[Outdated] Functional Use Cases in Android</h3><p><strong><em>This article is now outdated, please find latest approach using Functional Interfaces </em></strong><a href="https://betterprogramming.pub/how-to-avoid-use-cases-boilerplate-in-android-d0c9aa27ef27"><strong><em>here</em></strong></a><strong><em>.</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gEq_Om0oEILtB31526pCxw.png" /></figure><blockquote>What if I tell you that you can remove all the boilerplate code of your use cases and avoid writing them when not needed without affecting your presentation layer?</blockquote><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fblue-sea-697d.quartiers047.workers.dev%3A443%2Fhttps%2Fgiphy.com%2Fembed%2Fd0MYTsbRnGKoU%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fblue-sea-697d.quartiers047.workers.dev%3A443%2Fhttps%2Fgiphy.com%2Fgifs%2Freaction-supernatural-wtf-d0MYTsbRnGKoU&amp;image=https%3A%2F%2Fblue-sea-697d.quartiers047.workers.dev%3A443%2Fhttps%2Fmedia.giphy.com%2Fmedia%2Fd0MYTsbRnGKoU%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="224" frameborder="0" scrolling="no"><a href="https://medium.com/media/78ce0ab795e5da84fe0962b3728f3afb/href">https://medium.com/media/78ce0ab795e5da84fe0962b3728f3afb/href</a></iframe><p>No, I’m not joking! 😎</p><p>A while ago <a href="https://proandroiddev.com/why-you-need-use-cases-interactors-142e8a6fe576">I wrote why you need use cases and what they are</a> so in this article I’m not going to dig too much into details, if you are new to them I suggest you read my previous article before.</p><p>To summarize we can say that <strong>Use cases</strong> are an evolution of <a href="https://martinfowler.com/eaaCatalog/serviceLayer.html">Application Services</a> that bring the following benefits:</p><ol><li>Isolation of application logic (this was given by Application Services too)</li><li>Adhesion to <strong>Interface Segregation Principle</strong>: for example, your <em>ViewModel</em> will have as collaborators only the needed <strong>Use cases</strong> and not a huge interface (either application service or repository if you are skipping the layer) with 10+ methods where only 1 or 2 are needed.</li><li>Thinner Presenters/ViewModels</li><li><a href="https://blog.cleancoder.com/uncle-bob/2011/09/30/Screaming-Architecture.html">Screaming Architecture</a>: you know what the app does by looking at the use case names.</li></ol><h3>The evolution of Use cases in Kotlin</h3><p>When developers started migrating their Java code to Kotlin they kept the original Java convention so <strong>Use cases</strong> were looking something like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c3b08a2481a9def4eb1f2d18f6f703ff/href">https://medium.com/media/c3b08a2481a9def4eb1f2d18f6f703ff/href</a></iframe><p>and used as</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/646c268c5fd31e81194f9a0bcd3895a7/href">https://medium.com/media/646c268c5fd31e81194f9a0bcd3895a7/href</a></iframe><p>So <strong>Use Case</strong> <em>interface name</em> reflecting the action to be performed and <em>method name</em> adhering to the <a href="https://en.wikipedia.org/wiki/Command_pattern#Java"><strong>Command Pattern</strong></a> convention.</p><p>After a while, someone came up with a more readable solution that looked like the following:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/931038865efc0d737f094e34f5fac689/href">https://medium.com/media/931038865efc0d737f094e34f5fac689/href</a></iframe><p>Basically the operator fun invoke allows you to omit the invoke method when calling it, this way it looks like you are calling a <em>function</em> (yes you are getting the hint 🙂).</p><h3>The hate for Use cases</h3><p>Despite all the benefits they bring the excessive boilerplate of the <strong>Use cases</strong> (and the application layer in general) is something to consider and for many is a <strong>deal-breaker</strong>.</p><p>I cannot really blame who is against using them because most of the time these <strong>Use cases</strong> have really small logic (if any).</p><p>To quote <strong>Martin Fowler</strong>:</p><blockquote><em>My preference is thus to have the thinnest Service Layer you can, if you even need one. My usual approach is to assume that I don’t need one and only add it if it seems that the application needs it. However, I know many good designers who always use a Service Layer with a fair bit of logic, so feel free to ignore me on this one.</em></blockquote><p>As you can see better engineers than me and you have already discussed this topic in the past and never came to an agreement 😢.</p><h3>Functional Programming to the rescue</h3><p>Let’s say you have these <strong>Repositories</strong>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/41cb4e4c598b9990545c55c27cea0b69/href">https://medium.com/media/41cb4e4c598b9990545c55c27cea0b69/href</a></iframe><p>A <strong>Use case</strong> that just calls a Repository (“useless” use case):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e947f3730b50fbf7fbe66e2982e15d74/href">https://medium.com/media/e947f3730b50fbf7fbe66e2982e15d74/href</a></iframe><p>A <strong>Use case</strong> with a little bit of logic (multiple resources):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c67db328fabe19cd41356c96b5476aa0/href">https://medium.com/media/c67db328fabe19cd41356c96b5476aa0/href</a></iframe><p>And finally a <strong>ViewModel</strong>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fc8b902c574dbc9718108dc539bf73c9/href">https://medium.com/media/fc8b902c574dbc9718108dc539bf73c9/href</a></iframe><p>You can see quite a bit of boilerplate code: Use case interfaces (because we adhere to the DIP, aren’t we? 😈), Use case classes (even when they literally do nothing)...</p><p>With the following approach, I’ll get rid of the Use case interfaces and the “useless” Use case (GetUserUseCaseImpl ) without affecting the presentation layer (TransactionListViewModelImpl ).</p><h4>FP conversion</h4><p>The conversion of GetTransactionsUseCaseImpl to higher-order function would be:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b38ab1d3fd02ff6a3ed74bf859d037cb/href">https://medium.com/media/b38ab1d3fd02ff6a3ed74bf859d037cb/href</a></iframe><p>The typealias GetTransactionsUseCase will be used for removing the verbosity of the function return type and for minimizing the refactoring (the TransactionListViewModelImpl thanks to this trick will not change a single line). <br>GetUserUseCase is another typealias.<br><strong><em>P.S.:</em></strong><em> You don’t need to use type aliases, this approach works with or without them.</em></p><p>You should have noticed that there are no input parameters in the typealiases, this is because we don’t want to make the dependencies explicit (just like interfaces hide the dependencies of their concrete implementations).<br>In fact, the <strong>injector</strong> will assign the functions to the typealiases in this way:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1f5a1a3cbd293d9870a9d7e48ef3aa53/href">https://medium.com/media/1f5a1a3cbd293d9870a9d7e48ef3aa53/href</a></iframe><p>We moved from <strong><em>class composition</em></strong> to <strong><em>functions composition!</em></strong></p><p>Did you notice anything else? 🙂</p><p>userRepository::getUserreplaces GetUserUseCaseImpl which has not been implemented at all!</p><p>If you are using <strong>Dagger</strong> you can achieve the same by doing:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0b0450bb494e3a7c705eaea7f7f36adf/href">https://medium.com/media/0b0450bb494e3a7c705eaea7f7f36adf/href</a></iframe><p>The <strong>ViewModel</strong> did not change at all:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a0c43c5a851f08375719a7b507c66983/href">https://medium.com/media/a0c43c5a851f08375719a7b507c66983/href</a></iframe><p>The typealias minimized the effort of the refactoring (a change of an import is all you need 🙂).</p><h4>Quick recap</h4><ol><li>“Useless” Use cases are not implemented and the injector assigns the Repository function to the ViewModel (without knowing about the Repository, this way the <strong>ISP</strong> is not broken).</li><li>“Useful” Use cases are implemented as <em>higher-order functions</em> and the injector hides the function inputs.</li><li><strong>Optional</strong><em>: Type aliases </em>are used for removing the verbosity of function definitions and for minimizing the changes required by eventual refactoring.</li></ol><h3>Last notes</h3><p>I find that this approach saves a lot of time, reduces the maintenance cost of the project, and helps in keeping the architecture of the codebase consistent.</p><p>You can find the full source code here:</p><p><a href="https://github.com/DenisBronx/FunctionalUseCases">DenisBronx/FunctionalUseCases</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f896f92e768f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/functional-use-cases-f896f92e768f">Functional Use Cases</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Functional Data Mappers]]></title>
            <link>https://proandroiddev.com/functional-data-mappers-4daf495192ed?source=rss-8f0052074f18------2</link>
            <guid isPermaLink="false">https://medium.com/p/4daf495192ed</guid>
            <category><![CDATA[repository-pattern]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[mapping]]></category>
            <dc:creator><![CDATA[Denis Brandi]]></dc:creator>
            <pubDate>Sat, 18 Apr 2020 23:14:43 GMT</pubDate>
            <atom:updated>2020-04-23T17:09:37.658Z</atom:updated>
            <cc:license>http://creativecommons.org/licenses/by/4.0/</cc:license>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w9VGx9EPUA87UEO7nZCMEA.png" /><figcaption>Functional Data Mapping</figcaption></figure><p>A while ago I wrote <a href="https://proandroiddev.com/the-real-repository-pattern-in-android-efba8662b754">a post about the Repository Pattern</a> in which, among the other concepts, I explained the importance of <strong><em>model separation</em></strong> and <strong><em>data mapping</em></strong>.</p><p>After reading the comments on my article I was glad to see readers agreeing on the approach and overcoming the general hate over “extra models” and “annoying mappers”.</p><p>In the article, I also showed abstractions and generic implementations that can help to remove some boilerplate code.<br>All of that was achieved using simple OOP concepts but today I want to show you how you can achieve the same using <em>Functional Programming </em>(and with less boilerplate code 🎉).</p><p>You can find all the sample code here:</p><p><a href="https://github.com/DenisBronx/FunctionalMapping">DenisBronx/FunctionalMapping</a></p><p>For who doesn’t remember my previous post or didn’t read it yet (now it is a good time for reading it 😇) these are some generic components I used for removing some boilerplate code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/edc8bd42d03df93bb2ab6fa5dfabb24a/href">https://medium.com/media/edc8bd42d03df93bb2ab6fa5dfabb24a/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f4b9ed8a87a3935649d556d05b8b5d70/href">https://medium.com/media/f4b9ed8a87a3935649d556d05b8b5d70/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6905dbb53ba16d43267cfc67526ad560/href">https://medium.com/media/6905dbb53ba16d43267cfc67526ad560/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/202ead0187447a9436273fde317c96cb/href">https://medium.com/media/202ead0187447a9436273fde317c96cb/href</a></iframe><h4>OOP to FP conversion</h4><p>Since these are all single-method classes the conversion it’s pretty straightforward:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4decea8cfb1928d07f37ba6f2f6d5bd9/href">https://medium.com/media/4decea8cfb1928d07f37ba6f2f6d5bd9/href</a></iframe><p>Basically class fields are replaced by <a href="https://kotlinlang.org/docs/reference/lambdas.html">higher-order functions</a> and there is no more need for interfaces since function declarations are already an abstraction 😎.</p><p>You may now be worried about this change since one of the issues of FP is that dependencies become <em>“explicit” </em>since they appear in the function signature rather than being hidden by an interface and then injected in the constructor of the concrete implementation but don’t worry I’ll show you later a simple workaround 😃.</p><p>Let’s now take some real data mappers and convert them using the same approach.<br>So let’s say these are the models to map:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/026f8b1ac3ed02810b261bd08d8e565f/href">https://medium.com/media/026f8b1ac3ed02810b261bd08d8e565f/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9118df979edda8f6b906f988e139b3cb/href">https://medium.com/media/9118df979edda8f6b906f988e139b3cb/href</a></iframe><h4>The OOP way</h4><p>This is how I would map the above network DTOs into the Domain Models using a standard OOP approach:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ebb3eb5b00f07ce1817d454a740b4271/href">https://medium.com/media/ebb3eb5b00f07ce1817d454a740b4271/href</a></iframe><h4>The FP way</h4><p>And this would be the FP translation:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4110c5857da3b4f16331c873c9458a85/href">https://medium.com/media/4110c5857da3b4f16331c873c9458a85/href</a></iframe><h4>The Repository</h4><p>Let’s now have a look at this simple <em>AlbumRepository:</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/96f11e8292e8f4bf88dee52af198e4ee/href">https://medium.com/media/96f11e8292e8f4bf88dee52af198e4ee/href</a></iframe><p>You can see that <strong><em>albumDataMapper</em></strong> is doing a great job in abstracting the mapping logic so now we should expect minimum changes:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/443fa85b2f700e539d8dba45d97256c0/href">https://medium.com/media/443fa85b2f700e539d8dba45d97256c0/href</a></iframe><p>Almost the same, isn’t it? 😃</p><p>If you check the<a href="https://github.com/DenisBronx/FunctionalMapping"> sample project</a> you’ll see that the unit tests look similar as well.</p><h4>The Injection</h4><p>If you look at the snippets above, none of the functions has this signature:</p><pre>fun mapAlbumDTO(networkAlbum: NetworkAlbum): Album</pre><p>and all we have is:</p><pre>fun mapAlbumDto(<br>    input: NetworkAlbum, <br>    mapSongList: (List&lt;NetworkSong&gt;?) -&gt; List&lt;Song&gt;<br>): Album</pre><p>We don’t want the Repository to deal with the explicit dependencies of the <strong><em>mapAlbumDto</em></strong> function so this is where the injection comes into play (the workaround I talked about before).</p><p>For simplicity, I’ll just use a simple <em>Factory</em> that creates an instance of the Repository (in your project you can replicate the same thing using the tool you prefer: Dagger, Koin, manual DI…).</p><h4>Factory for the OOP version</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f74b3c966754ccdf47d548f1dc5f3312/href">https://medium.com/media/f74b3c966754ccdf47d548f1dc5f3312/href</a></iframe><h4>Factory for the FP version</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/23dffdf4f673cd682233cd349e6a5074/href">https://medium.com/media/23dffdf4f673cd682233cd349e6a5074/href</a></iframe><p>As you can see the second <em>Factory</em> is composing all the small functions for generating the final function required by the Repository, this way the Repository stays clean.</p><p>The Repository for the OOP version looks leaner than the one for the FP version (this is a downside of my approach) but I don’t think it is a big deal considering that this is just a <em>Factory</em> and all the boilerplate we removed.</p><h3>Facades</h3><p>When dealing with bigger Repositories chances are Data Mapping logic will require a lot of dependencies.</p><p>If this is the case you are facing, whether you are using the OOP or the FP approach, I suggest you adopt the <em>Facade Pattern.</em></p><p>So if you end up having something like this (which may also potentially grow in the future):</p><pre>class ARepositoryImpl(<br>    private val apiService: ApiService,<br>    private val mapM1ToM2: (M1) -&gt; M2,<br>    private val mapM1ToM3: (M1) -&gt; M3,<br>    private val mapM2ToM1: (M2) -&gt; M1,<br>    private val mapM3ToM1: (M3) -&gt; M1<br>): ARepository {//...}</pre><p>You can simplify this way:</p><pre>class DataMappersFacade(<br>    val mapM1ToM2: (M1) -&gt; M2,<br>    val mapM1ToM3: (M1) -&gt; M3,<br>    val mapM2ToM1: (M2) -&gt; M1,<br>    val mapM3ToM1: (M3) -&gt; M1<br>)</pre><pre>class ARepositoryImpl(<br>    private val apiService: ApiService,<br>    private val dataMappersFacade: DataMappersFacade<br>): ARepository {//...}</pre><p>and access the mappers by doing <strong><em>dataMappersFacade.mapM1ToM2(m1).</em></strong></p><p>The OOP version would require some more boilerplate code since you would need both an interface and a concrete class for the <em>Facade.</em> <br>This is another advantage of the FP approach 😎.</p><h3>Last notes</h3><p>FP and OOP have both advantages and disadvantages, some developers want to see a winner between the 2 but in my opinion, it’s like comparing apples with bananas.</p><p>FP works well with the <em>Data Mapping Layer </em>because there are no side effects generated by the mapping so it is simple to keep functions “<em>pure</em>”.<br>This, however, doesn’t apply to the <em>Repository Layer</em> so better to stick with OOP.</p><p>The more tools you have the better it is but be wise and use 🍎 for apple pies and 🍌 for banana pudding.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4daf495192ed" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/functional-data-mappers-4daf495192ed">Functional Data Mappers</a> was originally published in <a href="https://proandroiddev.com">ProAndroidDev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>