<?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 Ken Miyashita on Medium]]></title>
        <description><![CDATA[Stories by Ken Miyashita on Medium]]></description>
        <link>https://medium.com/@ken.miyasita?source=rss-bad27daeb320------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*wF1WXdZb5f3JQiD8bmV42Q.png</url>
            <title>Stories by Ken Miyashita on Medium</title>
            <link>https://medium.com/@ken.miyasita?source=rss-bad27daeb320------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 05:04:15 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ken.miyasita/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[Anatomy of virtualization-related technologies]]></title>
            <link>https://medium.com/@ken.miyasita/anatomy-of-virtualization-related-technologies-01a2cee01448?source=rss-bad27daeb320------2</link>
            <guid isPermaLink="false">https://medium.com/p/01a2cee01448</guid>
            <category><![CDATA[virtualization]]></category>
            <category><![CDATA[emulation]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[qemu]]></category>
            <category><![CDATA[mac]]></category>
            <dc:creator><![CDATA[Ken Miyashita]]></dc:creator>
            <pubDate>Sun, 31 Dec 2023 07:38:13 GMT</pubDate>
            <atom:updated>2023-12-31T07:38:13.220Z</atom:updated>
            <content:encoded><![CDATA[<h3>Motivation</h3><p>I have been using MacBook Air with M1 Apple Silicon. Recently I tried <a href="https://mac.getutm.app/">UTM</a> since I wanted to play with Linux on my Mac. Yes, it worked very well and I felt no stress on using Linux on my Mac. But the following screen you encounter when you first create a virtual machine on UTM gave me an uneasy feeling. “Hmm… Do I really understand how virtualization and emulation are different, and how they are related to?” Then I started googling “virtualization” and “emulation”, and found many related technical terms. This article is my memorandum of those technical terms, and the biggest value to you would be a series of figures depicting those technical terms in a consistent style.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/899/1*MksQqefkFGsjlrHRS1wXtg.png" /></figure><p>Therefore you do not expect detailed information about those technologies nor detailed instructions about how to set up virtual machines. If you are looking for those information, I would like you to follow links in this article.</p><h3>Overview</h3><p>First let me show the overall tree structure of technical terms in my understanding.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/779/1*BHFWstd9jMV2vH-AJA0myg.png" /></figure><p>In the following sections, I will explain those terms one by one.</p><h3>Bare-metal hypervisor and hosted hypervisor</h3><p><em>Virtualization</em> refers to the creation of a <em>virtual machine</em> that acts like a real computer with an operating system. Software executed on these virtual machines is separated from the underlying hardware resources. The software or firmware that creates a virtual machine on the host hardware is called a <em>hypervisor</em>. [1]</p><p>Hypervisor can be categorized into two types. [2]</p><ul><li>Type 1: Bare-metal hypervisors<br>These hypervisors run directly on the host’s hardware to control the hardware and to manage guest operation systems.</li><li>Type 2: Hosted hypervisors<br>These hypervisors run on a conventional operating system as an ordinary process.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/816/1*v9yHXCZ3xra6A8NAvWXkSg.png" /></figure><p>These days we casually run different operating systems on virtual machines. For example, I run Linux virtual machine on macOS. Those cases are all categorized as Type 2. In the following sections, we assume our configuration is always Type 2.</p><h3>Full virtualization and paravirtualization</h3><p><em>Virtualization</em> can be categorized into two types focusing on necessity of modification on guest programs. [1]</p><ul><li>Full virtualization<br>Almost complete simulation of the actual hardware to allow software environments, including a guest operating system and its apps, to run <strong>unmodified</strong>.</li><li>Paravirtualization<br> The guest apps are executed in their own isolated domains, as if they are running on a separate system, but a hardware environment is not simulated. Guest operating systems need to be <strong>specifically modified</strong> to run in this environment.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/834/1*fLF0R0Qr-HAqwenUfHJBeA.png" /></figure><p>I am not sure how popular paravirtualization is these days. But I have a gut feeling that we usually use full virtualization with enough performance thanks to hardware-assisted virtualization technologies. See the next section for hardware-assisted virtualization.</p><h3>Hardware-assisted virtualization</h3><p>For full virtualization, we need to simulate the complete hardware including CPU, storage, and peripherals. The biggest challenge is to simulate CPU. And we can completely separate situations according to the requirement on CPU.</p><ul><li>If host system and guest system use the same CPU type:<br>We can utilize hardware assistance to (1) minimize the overhead of virtualization and (2) realize its safely . See the remaining of this section.</li><li>If host system and guest system use different CPU types:<br>We need to translate CPU instructions among different CPU types. See the next section for details.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZHH2m56kqEky0V0iiWAF8w.png" /></figure><p>Intel has introduced the technology called Intel VT as hardware assistance for x86 CPU [3]. For example, Intel VT introduced a new CPU mode called VMX (VMX stands for “Virtual Machine Extensions”) to realize safe virtualization efficiently.</p><p>On x86 CPU with ring protection [4], the operating system kernel runs at a higher privilege such as ring 0, and applications at a lower privilege such as ring 3. When applications want to access hardware resources managed by the operating system, applications issue special instruction to make CPU switch to ring 0 and run the operating system to handle the request.</p><p>Now we need to make hypervisor run at a privilege higher than ring 0. This is why new VMX root mode is introduced. The guest OS runs at ring 0 in VMX non-root mode. When the guest OS tries to execute any instructions related to virtualization, CPU switches to VM root mode and the hypervisor handles the instructions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/607/1*kTYKM59LbcZupEXeoIUvLQ.png" /></figure><p>Apple also provides hardware assistance for virtualization in Apple Silicon. They provides Virtualization framework [5] and let application programmers create virtual machines easily on macOS.</p><h3>CPU emulation</h3><p>When the host OS and guest OS run on different CPU types, CPU instructions need to be translated. QEMU is the most popular open-source implementation of CPU emulation.</p><p>QEMU has multiple operating modes: [6]</p><ul><li>System emulation<br>In this mode QEMU emulates a full computer system, including peripherals. In other words, guest operating system (OS-1 in the figure below) runs on virtual CPU (CPU-Y) while QEMU translates all CPU instructions to those of real CPU (CPU-X).</li><li>User-mode emulation<br>In this mode QEMU runs single Linux or Darwin/macOS programs that were compiled for a different CPU. That is, QEMU translates CPU instructions running in non-privilege mode (user mode) and also converts system calls of guest OS to those of host OS. This mode is not to be called as virtualization since it does not create any virtual machine that acts like a real computer with an operating system.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fmCW3cupFhBFr3yCuJzQew.png" /></figure><p>For Apple Silicon, Apple provides Rosetta [7] which translates x86 instructions to ARM instructions to let you run x86 applications on Apple Silicon Mac. This can be seen as another implementation of user-mode emulation.</p><h3>Use cases</h3><p>Now it’s time to try several configurations combining those technologies on my M1 MacBook Air with UTM, and see the performance.</p><p><strong>(1) Linux on ARM</strong></p><p>You can create Linux virtual machine on ARM with UTM. Thanks to Apple Silicon’s hardware-assisted virtualization, the performance is quite good. I can use this Linux in my daily development.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/608/1*aBLEWyv9yy9b51LysXrJ-Q.png" /></figure><p><strong>(2) Linux on x86</strong></p><p>You can create Linux virtual machine on x86 with UTM. It works, but quite slow. This slowness is easy to understand. All instructions in application and operating system are to be translated. Phew…</p><p>Since we have the third option, I don’t think this configuration is realistic for your daily usage.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/471/1*Bz2QodcvzovIAmla8uCJ7A.png" /></figure><p><strong>(3) Linux on ARM and applications with x86 instructions</strong></p><p>Compared to (2), this configuration is more feasible. Rosetta2 translates x86 CPU instructions into ARM (Apple Silicon) CPU instructions efficiently, and the performance is enough acceptable.</p><p>You can get <a href="https://mac.getutm.app/gallery/debian-12-rosetta">virtual machine with Debian12 and Rosetta2</a> from UTM’s gallery.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/626/1*ybsbrW7NXEJwYQ-jg3DzwQ.png" /></figure><p>(4) Performance comparison with <a href="https://www.geekbench.com/">Geekbench 6</a></p><p>Geekbench is a cross-platform benchmark that measures your system’s performance. It is available on <a href="https://www.geekbench.com/download/">macOS, Linux (x86)</a> and also on <a href="https://www.geekbench.com/preview/">Linux (ARM64) as preview</a> which is suitable for my cases.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dN-gJNeAzpfOHZ-iMWRBGA.png" /></figure><p>Here is the summary of CPU benchmark.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d5IFT_eqcdvQGfohQVOatA.png" /></figure><ul><li><a href="https://browser.geekbench.com/v6/cpu/4203872">macOS (ARM64)</a> is the baseline.</li><li><a href="https://browser.geekbench.com/v6/cpu/4205735">Linux (ARM64)</a> shows how hardware-assisted virtualization works efficiently. Surprisingly the Single-Core CPU performance of Linux (ARM64) defeats that of macOS. Wow…</li><li><a href="https://browser.geekbench.com/v6/cpu/4205683">Linux (ARM64) + Rosetta2</a> shows how efficient Rosetta2 is. It looks like Linux applications compiled for x86 CPU can run at ~40% performance with Rosetta2. Not so bad.</li></ul><h3>Conclusion</h3><p>In this article, I showed the overview of several technical terms related to virtualization and emulation. If you are interested in how those terms are related to each other, I hope my figures will help you.</p><h3>References</h3><ul><li>[1] <a href="https://en.wikipedia.org/wiki/Virtualization">Virtualization — Wikipedia</a></li><li>[2] <a href="https://en.wikipedia.org/wiki/Hypervisor">Hypervisor — Wikipedia</a></li><li>[3] <a href="https://en.wikipedia.org/wiki/X86_virtualization">x86 virtualization — Wikipedia</a></li><li>[4] <a href="https://en.wikipedia.org/wiki/Protection_ring">Protection ring — Wikipedia</a></li><li>[5] <a href="https://developer.apple.com/documentation/virtualization">Virtualization | Apple Developer Documentation</a></li><li>[6] <a href="https://en.wikipedia.org/wiki/QEMU">QEMU — Wikipedia</a></li><li>[7] <a href="https://developer.apple.com/documentation/apple-silicon/about-the-rosetta-translation-environment/">About the Rosetta Translation Environment | Apple Developer Documentation</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=01a2cee01448" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Validate Dependencies According To Clean Architecture]]></title>
            <link>https://medium.com/better-programming/validate-dependencies-according-to-clean-architecture-743077ea084c?source=rss-bad27daeb320------2</link>
            <guid isPermaLink="false">https://medium.com/p/743077ea084c</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[clean-architecture]]></category>
            <category><![CDATA[dependencies]]></category>
            <category><![CDATA[git-hooks]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Ken Miyashita]]></dc:creator>
            <pubDate>Wed, 01 Feb 2023 06:15:02 GMT</pubDate>
            <atom:updated>2023-02-03T18:04:24.947Z</atom:updated>
            <content:encoded><![CDATA[<h3>Validate Dependencies According to Clean Architecture</h3><h4>You can use dependency-cruiser to keep the clean architecture through the evolution of your code</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GZBELapJcC6Ya0Mv" /><figcaption>Photo by <a href="https://unsplash.com/@marcojodoin?utm_source=medium&amp;utm_medium=referral">Marc-Olivier Jodoin</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In my <a href="https://betterprogramming.pub/clean-architecture-with-react-cc097a08b105">previous article</a>, I explained how to convert (transform) your React-based code into clean architecture.</p><p>Your next challenge is to keep the clean architecture through the evolution of your code. This tends to be difficult when multiple members work as a team (especially when the team includes newbies). But here is some good news. Just like using lint to maintain the source code format, we can introduce a tool to keep the most important rule of clean architecture: the dependency rule, which says that source code dependencies can only point upwards (one-way).</p><p>For example, my previous article showed the following dependency graph for a TicTacToe program. Here is <a href="https://gitlab.com/kmiyashita/clean-tic-tac-toe">the entire source code of this example.</a> Let’s see how the tool can protect the clean architecture through code evolution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/380/1*5rPfDik_uk4lZIncPNxvYQ.png" /><figcaption>Dependency graph of TicTacToe</figcaption></figure><h3>Getting Started With Dependency-Cruiser</h3><p><em>dependency-cruiser</em> is a tool that analyzes all your source files and validates dependencies among files.</p><p><a href="https://github.com/sverweij/dependency-cruiser">GitHub - sverweij/dependency-cruiser: Validate and visualize dependencies. Your rules. JavaScript, TypeScript, CoffeeScript. ES6, CommonJS, AMD.</a></p><p>You can easily install the tool and initialize its configuration file (dependency-cruiser.js) for your repo as follows:</p><pre>$ yarn add dependency-cruiser --dev<br>$ npx depcruise --init</pre><p>Now it’s time to validate our source codes. Phew… I’m relieved to see there are no violations.</p><pre>$ npx depcruise src --include-only &#39;^src&#39; --config --output-type err-long<br><br>✔ no dependency violations found (25 modules, 38 dependencies cruised)</pre><p>But there is more. Combined with <em>Graphviz</em>, <em>dependency-cruiser</em> generates a cool dependency graph.</p><p><a href="https://www.graphviz.org/">Graphviz</a></p><pre>$ npx depcruise src --include-only &#39;^src&#39; --config --output-type dot | dot -T svg &gt; dependency-graph.svg &amp;&amp; open dependency-graph.svg</pre><p>Cool! You can see all dependencies are aligned with your expectations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ff2TcNhKhO_SP3Vnb8MpFQ.png" /></figure><p>Since we would use those two commands frequently, it’s a good idea to make scripts for them in your package.json.</p><pre>&quot;scripts&quot;: {<br>    &quot;depcruise:validate&quot;: &quot;depcruise src --include-only &#39;^src&#39; --config --output-type err-long&quot;,<br>    &quot;depcruise:tree&quot;: &quot;depcruise src --include-only &#39;^src&#39; --config --output-type dot | dot -T svg &gt; dependency-graph.svg &amp;&amp; open dependency-graph.svg&quot;<br>}</pre><p>Then let’s see how <em>dependency-cruiser</em> detects invalid dependencies. We add the following invalid line in src/Domain/UseCase/ClickOnBoardUseCase.ts.</p><pre>// src/Domain/UseCase/ClickOnBoardUseCase.ts<br>import { TicTacToeView } from &quot;../../Presentation&quot;;</pre><p>Since the Presentation layer is lower than the Domain layer, this import statement should be detected as an error. Voilà! <em>Dependency-cruiser</em> gives us a detailed analysis in text and a crystal clear graph.</p><pre>$ yarn depcruise:validate<br>yarn run v1.22.17<br>$ depcruise src --include-only &#39;^src&#39; --config --output-type err-long<br><br>  warn no-circular: src/Presentation/hook/useTicTacToeModelController.ts → <br>      src/Domain/UseCase/index.ts →<br>      src/Domain/UseCase/ClickOnBoardUseCase.ts →<br>      src/Presentation/index.ts →<br>      src/Presentation/TicTacToeView.tsx →<br>      src/Presentation/hook/useTicTacToeModelController.ts<br>    This dependency is part of a circular relationship. You might want to<br>    revise your solution (i.e. use dependency inversion, make sure the modules<br>    have a single responsibility)<br><br>  warn no-circular: src/Domain/UseCase/ClickOnBoardUseCase.ts → <br>      src/Presentation/index.ts →<br>      src/Presentation/TicTacToeView.tsx →<br>      src/Domain/UseCase/index.ts →<br>      src/Domain/UseCase/ClickOnBoardUseCase.ts<br>    This dependency is part of a circular relationship. You might want to<br>    revise your solution (i.e. use dependency inversion, make sure the modules<br>    have a single responsibility)<br><br><br>✖ 2 dependency violations (0 errors, 2 warnings). 25 modules, 39 dependencies cruised.<br><br>✨  Done in 0.81s.<br><br>$ yarn depcruise:tree    <br>yarn run v1.22.17<br>$ depcruise src --include-only &#39;^src&#39; --config --output-type dot | dot -T svg &gt; dependency-graph.svg &amp;&amp; open dependency-graph.svg<br>✨  Done in 1.08s.</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*65otJosfziEgwesOvM3ioA.png" /></figure><p><em>Dependency-cruiser</em> detects this line as a violation against the “no-circular” rule predefined in the configuration file (<em>dependency-cruiser.js</em>) as follows:</p><pre>  forbidden: [<br>    {<br>      name: &quot;no-circular&quot;,<br>      severity: &quot;warn&quot;,<br>      comment:<br>        &quot;This dependency is part of a circular relationship. You might want to revise &quot; +<br>        &quot;your solution (i.e. use dependency inversion, make sure the modules have a single responsibility) &quot;,<br>      from: {},<br>      to: {<br>        circular: true,<br>      },<br>    },<br>    ...<br>  ]</pre><p>In this way, the default configuration file already has generic rules, and you can detect violations such as no-circular.</p><h3>Customize Rules for Clean Architecture</h3><p>The default “no-circular” rule is a good start, but we need more strict dependency checking than generic rules. For example, can we detect the following invalid case?</p><pre>// src/Presentation/TicTacToeView.tsx<br>import { RepositoryImpl } from &quot;../Data&quot;;</pre><p>According to our design policy, we don’t want any direct dependency between Presentation and Data, but the default configuration cannot detect this invalid dependency since it does not cause any circular. See the dependency link with purple marking below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s3pk1Fv20dTFbWwZKL5g9w.png" /></figure><p>We need to declare that Presentation can only depend on Domain as follows:</p><pre>  allowedSeverity: &quot;error&quot;,<br>  allowed: [<br>    {<br>      from: { path: &quot;(^src/Presentation)&quot; },<br>      to: { path: [&quot;^src/Domain&quot;] },<br>    },<br>  ]</pre><p>With this new configuration, you observe the dependency link from Presentation/TicTacToeView.tsx to Data/index.ts is labeled as “not-in-allowed.” Great! Now <em>dependency-cruiser</em> detects this dependency as a violation of our new rule.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AvZSJjXGBH3N7ZChqjae2Q.png" /></figure><p>But you may notice that other valid dependencies are also labeled as “not-in-allowed.” If you use “allowed” rules, dependency-cruiser will emit a “not-in-allowed” message for each dependency that does not satisfy at least one of them. This means you need to specify all valid dependencies explicitly now. Although it seems cumbersome at first, it is a good habit to design dependencies and add new rules whenever you introduce new folders in your repo.</p><p>Here is the final configuration file:</p><pre>  allowedSeverity: &quot;error&quot;,<br>  allowed: [<br>    {<br>      from: { path: &quot;(^src/Main)&quot; },<br>      to: {<br>        // “$1” is introduced from regular expression’s “group matching”. <br>        // You can reference the part matched between brackets in “from” <br>        // string by using “$1” in “to”.<br>        path: [&quot;^$1&quot;, &quot;^src/Presentation&quot;, &quot;^src/Data&quot;, &quot;^src/Domain&quot;],<br>      },<br>    },<br>    {<br>      // Presentation other than Presentation/hook<br>      from: { path: &quot;(^src/Presentation)&quot;, pathNot: &quot;^src/Presentation/hook&quot; },<br>      to: { path: [&quot;^$1&quot;, &quot;^src/Domain&quot;] },<br>    },<br>    {<br>      // We want no hooks to depend on Presentation to make hooks independent<br>      // from any graphical presentation<br>      from: { path: &quot;(^src/Presentation/hook)&quot; },<br>      to: { path: [&quot;^$1&quot;, &quot;^src/Domain&quot;] },<br>    },<br>    {<br>      from: { path: &quot;(^src/Data)&quot; },<br>      to: { path: [&quot;^$1&quot;, &quot;^src/Domain&quot;] },<br>    },<br>    {<br>      from: { path: &quot;(^src/Domain/UseCase)&quot; },<br>      to: { path: [&quot;^$1&quot;, &quot;^src/Domain/Repository&quot;, &quot;^src/Domain/Model&quot;] },<br>    },<br>    {<br>      from: { path: &quot;(^src/Domain/Repository)&quot; },<br>      to: { path: [&quot;^$1&quot;, &quot;^src/Domain/Model&quot;] },<br>    },<br>    {<br>      from: { path: &quot;(^src/Domain/Model)&quot; },<br>      to: { path: [&quot;^$1&quot;] },<br>    },<br>    {<br>      // Files outside of established folders (e.g. src/index.tsx) can reference<br>      // any files.<br>      from: {<br>        pathNot: [&quot;^src/Main&quot;, &quot;^src/Presentation&quot;, &quot;^src/Data&quot;, &quot;^src/Domain&quot;],<br>      },<br>      to: {},<br>    },<br>  ],</pre><p>This comprehensive definition of valid dependencies gives you the following error and graph:</p><pre>$ yarn depcruise:validate<br>yarn run v1.22.17<br>$ depcruise src --include-only &#39;^src&#39; --config --output-type err-long<br><br>  error not-in-allowed: src/Presentation/TicTacToeView.tsx → src/Data/index.ts<br><br>✖ 1 dependency violations (1 errors, 0 warnings). 25 modules, 39 dependencies cruised.<br><br>error Command failed with exit code 1.</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6GMW6bUSN2e_SeNV9D49Sw.png" /></figure><h3>Visualize Dependencies in Big Repo</h3><p>We have visualized a dependency graph showing all files. This is good when your repo is small. But soon, your repo will include dozens and hundreds of files once your team members start working on the same repo. And you would want to visualize the whole repo on a higher level to check the dependency links.</p><p><em>Dependency-cruiser</em> provides a variant of graph (”ddot”) that summarizes modules on the folder level, and you can customize it with <a href="https://github.com/sverweij/dependency-cruiser/blob/1d01ca9405606c2fbe6edf0d94923c2dd1b9b8ff/doc/options-reference.md#theme-dot-ddot-and-archi-reporters">themes</a> and <a href="https://github.com/sverweij/dependency-cruiser/blob/1d01ca9405606c2fbe6edf0d94923c2dd1b9b8ff/doc/options-reference.md#filtering-dot-ddot-and-archi-reporters">filters</a>. See the following high-level graph for the same repo.</p><pre>$ npx depcruise src --include-only &#39;^src&#39; --config --output-type ddot | dot -T svg &gt; dependency-graph.svg &amp;&amp; open dependency-graph.svg</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/863/1*HkFqQKk11L_zgylJnmrZag.png" /></figure><h3>Integrate Dependency Validation in Git</h3><p>When multiple members work on your repo, keeping the dependencies designed by clean architecture is hard. It is a good idea to run dependency-cruiser whenever any member tries to commit changes.</p><p>Let’s use <em>husky</em> to automate dependency checking before any commit and prohibit the commit if a dependency violation is found.</p><p><a href="https://typicode.github.io/husky/#/">Husky - Git hooks</a></p><pre>$ npx husky-init &amp;&amp; yarn<br>$ npx husky add .husky/pre-commit &#39;yarn depcruise:validate&#39;</pre><p>Once this precommit hook is configured, nobody can make commits that violate dependencies. For example, the following shows how you are notified of a violation when you try to make an invalid commit.</p><pre>$ git commit -m &#39;chore: intentinal violation of dependencies&#39;<br>yarn run v1.22.17<br>$ depcruise src --include-only &#39;^src&#39; --config --output-type err-long<br><br>  error not-in-allowed: src/Presentation/TicTacToeView.tsx → src/Data/index.ts<br><br>✖ 1 dependency violations (1 errors, 0 warnings). 25 modules, 39 dependencies cruised.<br><br>error Command failed with exit code 1.<br>info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.<br>husky - pre-commit hook exited with code 1 (error)</pre><p>You can see the final repo <a href="https://gitlab.com/kmiyashita/clean-tic-tac-toe">here</a>.</p><h3>Conclusion</h3><p>I showed how to validate your repo from a clean architecture viewpoint. <em>Dependency-cruiser</em> is a powerful tool that can be integrated into your git repo’s precommit hook. That way, you can keep your repo aligned with clean architecture’s dependency rules. I hope this tool will help you to maintain your projects.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=743077ea084c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/validate-dependencies-according-to-clean-architecture-743077ea084c">Validate Dependencies According To Clean Architecture</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Four Strategies to Achieve Clean Code]]></title>
            <link>https://medium.com/@ken.miyasita/four-strategies-to-achieve-clean-code-9a7951abfa58?source=rss-bad27daeb320------2</link>
            <guid isPermaLink="false">https://medium.com/p/9a7951abfa58</guid>
            <category><![CDATA[refactoring]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Ken Miyashita]]></dc:creator>
            <pubDate>Sat, 31 Dec 2022 06:31:28 GMT</pubDate>
            <atom:updated>2024-01-02T04:23:43.150Z</atom:updated>
            <content:encoded><![CDATA[<h4>Guidance for refactoring code</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*yybuZpKKrxEfXiyZ" /><figcaption>Photo by <a href="https://unsplash.com/es/@freegraphictoday?utm_source=medium&amp;utm_medium=referral">AbsolutVision</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Uncle Bob’s book <a href="https://www.amazon.com/Clean-Code-Handbook-Software-Craftsmanship-ebook/dp/B001GSTOAM/ref=tmm_kin_swatch_0?_encoding=UTF8&amp;qid=1670567037&amp;sr=1-1-9e67e56a-6f64-441f-a281-df67fc737124">“Clean Code”</a> gives you the best agile practice of cleaning code. But as he says in the book, we cannot write clean code from the very beginning. Practically we refactor/transform our code every day to achieve more readable clean code. In this article, I show the essence of his book in a way that you can apply it to your refactoring process.</p><h3>Criteria: What is clean code?</h3><p>In the book, the author first says: “Writing clean code is a lot like painting a picture. Most of us know when a picture is painted well or badly. But being able to recognize good art from bad does not mean that we know how to paint.”</p><p>Then he cites the definition of “clean code” by several well-known programmers. e.g. “elegant and efficient”, “simple and direct”. Yes, I totally agree. But we need more tangible criteria with which we can determine if our code is clean enough.</p><p>I adopt the following two criteria.</p><h4>Criterion 1: A source file should be like a newspaper article which you can read from top to bottom.</h4><blockquote><em>The topmost parts of the source file should provide the high-level concepts and algorithms. Detail should increase as we move downward, until at the end we find the lowest level functions and details in the source file.</em></blockquote><p>This metaphor gave me a quite vivid idea about “what is the good source code”. Source code should be a material to be read by other engineers to understand what you design. If you don’t want to move your eyes back and forth when you read a newspaper article, why do you force your readers to take the burden? Of course, you shouldn’t.</p><p>If you are experienced engineers who are too familiar with Pascal, C, and C++ that enforce functions to be defined before they are used, you may feel uneasy with this simple criterion since it is totally opposite to your manner. But I strongly recommend you to try this new manner and let your colleagues to read your codes. Most of them would say this order makes it easier to read your source code as an “article”.</p><p>This newspaper metaphor gives you another sub criterion about your source files. Each source file should be short enough to let you read it as an article which conveys just one topic. You should easily remember what is the main topic of this source file (article). If you cannot express the main topic with one sentence, that implies the source file is too big. You should decompose the file into multiple smaller files according to abstraction levels and topics of functions included in the file.</p><h4>Criterion 2: A function should be small and focused just like a paragraph in an article.</h4><blockquote><em>Functions should do one thing. The should do it well. The should do it only.</em></blockquote><p>This “small function” rule has been said for decades. But honestly I had no clear strategy about how to decompose larger functions into smaller readable ones. But Uncle Bob gives us very concrete strategies to achieve those two criteria.</p><h3>Strategies with examples: How to write clean code?</h3><p>Now you understand what source code is “readable” in the context of “Clean Code”. But you may wonder how to write readable code. Or more practically you would wonder how to refactor / improve your code to make it readable. Don’t worry. The book provides several concrete strategies for that. In this section, I will select some of those strategies and show them with actual code refactoring.</p><p>As an example, I would refactor the code for TicTacToe which I wrote in the previous article.</p><p><a href="https://medium.com/@ken.miyasita/clean-architecture-with-react-cc097a08b105">Clean Architecture with React</a></p><p>The following function is a function which handles the use case where the user presses a square on the TicTacToe board.</p><pre>import type { Board, Square } from &quot;../Model&quot;;<br>import type { Repository } from &quot;../Repository&quot;;<br>import { isNextTurnX, calculateWinnerOnBoard } from &quot;./Util&quot;;<br><br>export async function clickOnBoard(<br>  indexOnBoard: number,<br>  repository: Repository<br>) {<br>  const { board, stepNumber } = await repository.getCurrentStep();<br>  if (!calculateWinnerOnBoard(board) &amp;&amp; !board[indexOnBoard]) {<br>    const newBoard = board.slice();<br>    newBoard[indexOnBoard] = isNextTurnX(stepNumber) ? &quot;X&quot; : &quot;O&quot;;<br>    await repository.deleteStepsAfterCurrentStepNumber();<br>    await repository.addStep(newBoard);<br>    await repository.setCurrentStepNumber(stepNumber + 1);<br>  }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/319/1*T8xb1IJNxGwihBNFQbJPjA.png" /><figcaption>Screenshot of Tic Tac Toe</figcaption></figure><p>First let me show two basic strategies for refactoring.</p><h4>Strategy 1: Describe a function as a brief TO paragraph: “To do X, we do A and then B.”</h4><p>“To do X” part corresponds to the function name. “we do A and then B” part corresponds to the function body. Note the abstraction level of A and B should be the same, and that level is one level below that of “To do X”. In this way, describing TO paragraph will force you to describe a function at one level of abstraction.</p><h4>Strategy 2: Extract blocks and make them functions.</h4><p>The blocks within if statements, else statements, while statements, and so on should be one line long. Probably that line should be a function call.</p><p>Now combining Strategy 1 and Strategy 2, let’s see how the function <em>clickOnBoard()</em> can be refactored.</p><p>We would say “To click a square on the board, we check if we can mark the square on the board and mark the square if you can.” Does it look too obvious? Yes, it is. But looking obvious is a great thing since you totally understand what this function does.</p><pre>export async function clickOnBoard(<br>  indexOnBoard: number,<br>  repository: Repository<br>) {<br>  const { board, stepNumber } = await repository.getCurrentStep();<br>  if (canMarkOnBoard(indexOnBoard, board)) {<br>    await markOnBoard(indexOnBoard, repository, board, stepNumber);<br>  }<br>}<br><br>function canMarkOnBoard(indexOnBoard: number, board: Board): boolean {<br>  return (<br>    !calculateWinnerOnBoard(board) &amp;&amp;<br>    board[indexOnBoard] === null<br>  );<br>}<br><br>async function markOnBoard(<br>  indexOnBoard: number,<br>  repository: Repository,<br>  board: Board,<br>  stepNumber: number<br>) {<br>  const newBoard = board.slice();<br>  newBoard[indexOnBoard] = isNextTurnX(stepNumber) ? &quot;X&quot; : &quot;O&quot;;<br>  await repository.deleteStepsAfterCurrentStepNumber();<br>  await repository.addStep(newBoard);<br>  await repository.setCurrentStepNumber(stepNumber + 1);<br>}</pre><p>Now <em>clickOnBoard()</em> becomes quite easy to understand. But newly introduced two functions <em>canMarkOnBoard()</em> and <em>markOnBoard()</em> do not look ideal. Then let’s refactor those functions.</p><p>Why doesn’t <em>canMarkOnBoard()</em> look ideal? Imagine how you would explain this function to your colleagues. You may want to add comments as follows. And here comes Strategy 3.</p><pre>function canMarkOnBoard(indexOnBoard: number, board: Board): boolean {<br>  return (<br>    !calculateWinnerOnBoard(board) &amp;&amp; // Nobody has won on the board<br>    board[indexOnBoard] === null.     // The square on the board is free<br>  );<br>}</pre><h4>Strategy 3: Make function name itself descriptive enough and eliminate comments as much as possible.</h4><p>You may have added descriptive comment to each function definition. But convert that comment into function name itself, and make the function name descriptive enough.</p><p>When I read this strategy, I was shocked since I believed that descriptive comments were the key for readable code. But I am now convinced with this strategy. There are two main reasons to deprioritize comments.</p><ul><li>Comments are destined to become stale in the long run through refactoring. You often forget to update comments when you modify codes. Once the comment and code become inconsistent, you cannot decide which of comment or code to believe. And the comment becomes stale. On the other hand, function names are maintained by nature with rich support by modern IDEs. You can rename a function with one click and all codes referring that function are updated correspondingly.</li><li>Function names are visible in two places: (1) the code to define the function (2) the codes which use the function. If you use descriptive function names, your codes become readable in those two aspects.</li></ul><p>Let’s see how it looks like after refactoring the code with Strategy 3.</p><pre>function canMarkOnBoard(indexOnBoard: number, board: Board): boolean {<br>  return hasNobodyWonOnBoard(board) &amp;&amp;<br>         isSquareOnBoardFree(indexOnBoard, board);<br>}<br><br>function hasNobodyWonOnBoard(board: Board): boolean {<br>  const winner = calculateWinnerOnBoard(board);<br>  return !winner;<br>}<br><br>function isSquareOnBoardFree(indexOnBoard: number, board: Board): boolean {<br>  return board[indexOnBoard] === null;<br>}</pre><p>We eliminate comments in <em>canMarkOnBoard()</em>, but the code is enough descriptive in more elegant manner. Doesn’t it look like pseudo code? If so, that is a huge success.</p><p>Then let’s tackle <em>markOnBoard()</em>. What makes this function less readable? The biggest pain point is the number of arguments, and we have Strategy 4.</p><h4>Strategy 4: Eliminate function arguments as much as possible.</h4><p>Uncle Bob says “Arguments are hard. They take a lot of conceptual power. ~ The argument is at a different level of abstraction than the function name and forces you to know a detail that isn’t particularly important at that point.” He strongly recommends to use as few arguments as possible.</p><p>But how? The technique could be different according to programming language you use. Here I will show how to use lexical scope (closure) in JavaScript / TypeScript. Originally <em>markOnBoard()</em> has four arguments as follows.</p><pre>async function markOnBoard(<br>  indexOnBoard: number,<br>  repository: Repository,<br>  board: Board,<br>  stepNumber: number<br>) {<br>  const newBoard = board.slice();<br>  newBoard[indexOnBoard] = isNextTurnX(stepNumber) ? &quot;X&quot; : &quot;O&quot;;<br>  await repository.deleteStepsAfterCurrentStepNumber();<br>  await repository.addStep(newBoard);<br>  await repository.setCurrentStepNumber(stepNumber + 1);<br>}</pre><p>Now you can eliminate all those arguments by defining <em>markOnBoard()</em> inside <em>clickOnBoard()</em> as follows.</p><pre>export async function clickOnBoard(<br>  indexOnBoard: number,<br>  repository: Repository<br>) {<br>  const { board, stepNumber } = await repository.getCurrentStep();<br><br>  if (canMarkOnBoard()) {<br>    await markOnBoard();<br>  }<br>  return;<br><br>  async function markOnBoard(): Promise&lt;void&gt; {<br>   const newBoard = board.slice();<br>   newBoard[indexOnBoard] = isNextTurnX(stepNumber) ? &quot;X&quot; : &quot;O&quot;;<br>   await repository.deleteStepsAfterCurrentStepNumber();<br>   await repository.addStep(newBoard);<br>   await repository.setCurrentStepNumber(stepNumber + 1);<br>  }<br>}</pre><p>The body of <em>markOnBoard()</em> can refer to all variables defined in the outer scope: <em>indexOnBoard</em> and <em>repository</em> are the arguments of <em>clickOnBoard()</em> while <em>board</em> and <em>stepNumber</em> are local variables defined in <em>clickOnBoard()</em>. You can read this “article” from top to bottom without any perceptual stress since all four variables are defined (introduced) first, then used (referred) later.</p><p>If you have learnt the cost of closure before, you may hesitate to use closure in this way since closure is expensive in its execution. But I believe you can use closure to achieve readability unless the function with closure is called hundreds of times in a second. In this example, <em>clickOnBoard()</em> is called whenever users click a square on the board, and the frequency of invoking this function would be less than a few times in a second. You should not be a fundamentalist who always avoids using closure, but be a pragmatist.</p><p>Finally let me show how the code is refactored with Strategy 1 ~ 4. You can see the final whole source code here: <a href="https://gitlab.com/kmiyashita/clean-tic-tac-toe/-/blob/main/src/Domain/UseCase/ClickOnBoardUseCase.ts">Final Result</a></p><pre>import type { Board, Square } from &quot;../Model&quot;;<br>import type { Repository } from &quot;../Repository&quot;;<br>import { isNextTurnX, calculateWinnerOnBoard } from &quot;./Util&quot;;<br><br>export async function clickOnBoard(<br>  indexOnBoard: number,<br>  repository: Repository<br>) {<br>  const { board, stepNumber } = await repository.getCurrentStep();<br>  if (canMarkOnBoard()) {<br>    await markOnBoard();<br>  }<br>  return;<br><br>  function canMarkOnBoard(): boolean {<br>    return hasNobodyWonOnBoard() &amp;&amp; isSquareOnBoardFree();<br>  }<br><br>  function hasNobodyWonOnBoard(): boolean {<br>    const winner = calculateWinnerOnBoard(board);<br>    return !winner;<br>  }<br><br>  function isSquareOnBoardFree(): boolean {<br>    return board[indexOnBoard] === null;<br>  }<br><br>  async function markOnBoard() {<br>    const newBoard = copyBoard();<br>    newBoard[indexOnBoard] = isNextTurnX(stepNumber) ? &quot;X&quot; : &quot;O&quot;;<br>    await deleteInvalidFutureSteps();<br>    await repository.addStep(newBoard);<br>    await repository.setCurrentStepNumber(stepNumber + 1);<br>  }<br><br>  function copyBoard(): Board {<br>    return [...board];<br>  }<br><br>  function deleteInvalidFutureSteps(): Promise&lt;void&gt; {<br>    return repository.deleteStepsAfterCurrentStepNumber();<br>  }<br>}</pre><h3>Conclusion</h3><p>I showed how to transform your codes into clean readable code.</p><p>We have two criterias:</p><ol><li>A source file should be like a newspaper article.</li><li>A function should be small like a paragraph in an article.</li></ol><p>And I showed four strategies to achieve those criteria. Each strategy is quite simple, but the combination of those strategies would transform your code totally. I hope the process described in this article would give you good guidance for your refactoring.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9a7951abfa58" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Clean Architecture With React]]></title>
            <link>https://medium.com/better-programming/clean-architecture-with-react-cc097a08b105?source=rss-bad27daeb320------2</link>
            <guid isPermaLink="false">https://medium.com/p/cc097a08b105</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[clean-architecture]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Ken Miyashita]]></dc:creator>
            <pubDate>Wed, 07 Dec 2022 06:13:49 GMT</pubDate>
            <atom:updated>2023-01-02T07:10:35.757Z</atom:updated>
            <content:encoded><![CDATA[<h4>Clean architecture makes your applications easy to maintain and extendable. But our codes tend to be biased by various framework-driven coding styles. In this article, I want to show how to convert (transform) your react-based code into clean architecture.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*idcPkWsv0q6kBvQi" /><figcaption>Photo by <a href="https://unsplash.com/@therealslimshadyiltun?utm_source=medium&amp;utm_medium=referral">İltun Huseynli</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><a href="https://blog.cleancoder.com/uncle-bob/2012/08/13/the-clean-architecture.html">Clean architecture</a> defines several layers stacked vertically, each of which represents different areas of software. The upper layers represent the application’s basic policies while the lower layers represent mechanisms.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/251/1*6d2zszJFKp47WlZUF95yPQ.png" /></figure><p>The overriding rule that makes this architecture work is <em>the dependency rule</em>. This rule says that <em>source code dependencies</em> can only point upwards. With layers and the dependency rule, you can design applications with very low coupling and independent of technical implementation details, such as databases and frameworks.</p><p>I employ layers defined in <a href="https://paulallies.medium.com/clean-architecture-typescript-and-react-8e509098abfe">this article</a> with the following definitions:</p><p>The <strong>Domain</strong> layer describes what your project or application does. Codes in Domain layer should be independent of platforms and frameworks.</p><ul><li><strong>Models</strong> represent real-world objects related to the problem.</li><li><strong>Repository</strong> provides interface to access models.</li><li><strong>Use cases</strong> include all business logic of your application.</li></ul><p>The<strong> Presentation</strong> layer describes HOW your application interacts with the outside world.</p><p><strong>Data</strong> layer describes how your application manages data.</p><p><strong>Main</strong> layer (the bottom-most layer) provides the bootstrap code which is in charge of weaving all software components in other layers into one application.</p><p>But in real applications, the control flow is not always upwards. For example, business logic in the UseCase layer uses an interface in the Repository layer, and Repository (upper layer) needs to access data managed in the Data layer (lower layer). See the figure below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/411/1*9ks3aD8UfwmXKaUQNhy_0A.png" /></figure><p>To resolve this violation of the dependency rule, we usually use <a href="https://en.wikipedia.org/wiki/Dependency_inversion_principle">the dependency inversion principle.</a> We arrange the relationship between the interface (e.g. RepositoryX) and its implementation (e.g. RepositoryImpl) so that the source code dependency directs upwards. With this technique, upper layers can call implementations defined in lower layers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/481/1*tqQ8wq4XvtAbsJ_KK5_0Bw.png" /></figure><h3>Transform React Application Into Clean Architecture</h3><p>When you start your application code from the react application’s template (e.g. skeleton created by <a href="https://create-react-app.dev/">create-react-app</a>), all codes are included in Presentation layer at first. This is because react (and all UI frameworks) focuses on how to present data to users. In this section, we will transform react-based application code and make it conformant to clean architecture.</p><p>Here is the original code of TicTacToe used in <a href="https://reactjs.org/tutorial/tutorial.html">the official react tutorial</a>.</p><pre>function Square(props) {<br>  return (<br>    &lt;button className=&quot;square&quot; onClick={props.onClick}&gt;<br>      {props.value}<br>    &lt;/button&gt;<br>  );<br>}<br><br>class Board extends React.Component {<br>  renderSquare(i) {<br>    return (<br>      &lt;Square<br>        value={this.props.squares[i]}<br>        onClick={() =&gt; this.props.onClick(i)}<br>      /&gt;<br>    );<br>  }<br><br>  render() {<br>    return (<br>      &lt;div&gt;<br>        &lt;div className=&quot;board-row&quot;&gt;<br>          {this.renderSquare(0)}<br>          {this.renderSquare(1)}<br>          {this.renderSquare(2)}<br>        &lt;/div&gt;<br>        &lt;div className=&quot;board-row&quot;&gt;<br>          {this.renderSquare(3)}<br>          {this.renderSquare(4)}<br>          {this.renderSquare(5)}<br>        &lt;/div&gt;<br>        &lt;div className=&quot;board-row&quot;&gt;<br>          {this.renderSquare(6)}<br>          {this.renderSquare(7)}<br>          {this.renderSquare(8)}<br>        &lt;/div&gt;<br>      &lt;/div&gt;<br>    );<br>  }<br>}<br><br>class Game extends React.Component {<br>  constructor(props) {<br>    super(props);<br>    this.state = {<br>      history: [<br>        {<br>          squares: Array(9).fill(null)<br>        }<br>      ],<br>      stepNumber: 0,<br>      xIsNext: true<br>    };<br>  }<br><br>  handleClick(i) {<br>    const history = this.state.history.slice(0, this.state.stepNumber + 1);<br>    const current = history[history.length - 1];<br>    const squares = current.squares.slice();<br>    if (calculateWinner(squares) || squares[i]) {<br>      return;<br>    }<br>    squares[i] = this.state.xIsNext ? &quot;X&quot; : &quot;O&quot;;<br>    this.setState({<br>      history: history.concat([<br>        {<br>          squares: squares<br>        }<br>      ]),<br>      stepNumber: history.length,<br>      xIsNext: !this.state.xIsNext<br>    });<br>  }<br><br>  jumpTo(step) {<br>    this.setState({<br>      stepNumber: step,<br>      xIsNext: (step % 2) === 0<br>    });<br>  }<br><br>  render() {<br>    const history = this.state.history;<br>    const current = history[this.state.stepNumber];<br>    const winner = calculateWinner(current.squares);<br><br>    const moves = history.map((step, move) =&gt; {<br>      const desc = move ?<br>        &#39;Go to move #&#39; + move :<br>        &#39;Go to game start&#39;;<br>      return (<br>        &lt;li key={move}&gt;<br>          &lt;button onClick={() =&gt; this.jumpTo(move)}&gt;{desc}&lt;/button&gt;<br>        &lt;/li&gt;<br>      );<br>    });<br><br>    let status;<br>    if (winner) {<br>      status = &quot;Winner: &quot; + winner;<br>    } else {<br>      status = &quot;Next player: &quot; + (this.state.xIsNext ? &quot;X&quot; : &quot;O&quot;);<br>    }<br><br>    return (<br>      &lt;div className=&quot;game&quot;&gt;<br>        &lt;div className=&quot;game-board&quot;&gt;<br>          &lt;Board<br>            squares={current.squares}<br>            onClick={i =&gt; this.handleClick(i)}<br>          /&gt;<br>        &lt;/div&gt;<br>        &lt;div className=&quot;game-info&quot;&gt;<br>          &lt;div&gt;{status}&lt;/div&gt;<br>          &lt;ol&gt;{moves}&lt;/ol&gt;<br>        &lt;/div&gt;<br>      &lt;/div&gt;<br>    );<br>  }<br>}<br><br>// ========================================<br><br>const root = ReactDOM.createRoot(document.getElementById(&quot;root&quot;));<br>root.render(&lt;Game /&gt;);<br><br>function calculateWinner(squares) {<br>  const lines = [<br>    [0, 1, 2],<br>    [3, 4, 5],<br>    [6, 7, 8],<br>    [0, 3, 6],<br>    [1, 4, 7],<br>    [2, 5, 8],<br>    [0, 4, 8],<br>    [2, 4, 6]<br>  ];<br>  for (let i = 0; i &lt; lines.length; i++) {<br>    const [a, b, c] = lines[i];<br>    if (squares[a] &amp;&amp; squares[a] === squares[b] &amp;&amp; squares[a] === squares[c]) {<br>      return squares[a];<br>    }<br>  }<br>  return null;<br>}</pre><p>And here is the screenshot of TicTacToe.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/461/1*2PApRqXAtLdZ8wbhkqTg5Q.png" /></figure><h3>Design Model layer</h3><p>First, let’s extract data models in the Model layer. By definition, the models defined here should be platform-agnostic and framework-agnostic, and they should purely focus on business rules.</p><p>Even if the original code does not have clear type definitions, you should definitely define those types to utilize TypeScript’s type inference mechanism and let it support you while developing.</p><pre>export type Square = null | &quot;X&quot; | &quot;O&quot;;<br><br>export type Board = Square[];<br><br>type HistoryStep = {<br>  board: Board;<br>};<br><br>export type History = HistoryStep[];</pre><h3>Design UseCase and Repository layers</h3><p>The next step is to extract use cases. A use case can be formalized as “when X happens, do Y”.</p><p>In React applications, use cases are typically implemented as (1) rendering function which is called by React framework, (2) event handlers for user input, or (3) autonomous effects. In the TicTacToe example, we have three use cases.</p><ul><li>render(): When any data is updated, this function is called.</li><li>handleClick(i): When you press a square on the board, this function is called.</li><li>jumpTo(step): When you press a “Go to move #x” button, this function is called.</li></ul><p>But you notice the original use case functions (render(), handleClick(), jumpTo()) include codes from multiple layers (UseCase, Repository, Data, Presentation (react)). We somehow need to untangle this spaghetti and distribute codes into appropriate layers.</p><p>I usually start this untangling by analyzing dependencies among variables. Then I find the primary data sources which cannot be deduced from any other variables. In the TicTacToe example, you can easily detect two data sources history and stepNumber as the figure below depicts. Those primary data need to be stored in persistent data storage, and we put them in the Data layer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/872/1*cAR1a7rxpsFPit628qwQIQ.png" /></figure><p>Designing the boundary between the UseCase layer and Repository layer is subjective, and partially up to you. The Repository layer is defined as the central place to keep all model-specific operations. On top of that I have my policy to define operations in theRepository layer as follows:</p><ul><li>Repository operations should be minimal. Exposing all raw setter/getter functions for primary data sources is not a good idea since it could lead to invalid / inconsistent data easily.</li><li>Repository operations should be neutral and independent from the business logic defined in UseCase layer.</li><li>Each repository operation should access multiple data sources only when the operation needs to change them at once (as an atomic operation) to keep consistency among data sources.</li></ul><p>Based on this policy, I decouple UseCase layer and Repository layer as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dedDxV5GCC4j0xCLD0Y0xg.png" /></figure><p>Let’s define the Repository interface. The implementation comes later.</p><pre>export type Step = {<br>  board: Board;<br>  stepNumber: number;<br>  numOfAllSteps: number;<br>};<br><br>/**<br> * Repository managing the history of TicTacToe steps.<br> * Each step consists of a board.<br> */<br>export interface Repository {<br>  getCurrentStep(): Promise&lt;Step&gt;;<br>  setCurrentStepNumber(stepNumber: number): Promise&lt;void&gt;;<br>  deleteStepsAfterCurrentStepNumber(): Promise&lt;void&gt;;<br>  addStep(board: Board): Promise&lt;void&gt;;<br>}</pre><p>You can define UseCase functions then. Now you can understand the business logic more clearly.</p><pre>export async function clickOnBoard(<br>  indexOnBoard: number,<br>  repository: Repository<br>) {<br>  const { board, stepNumber } = await repository.getCurrentStep();<br>  const newBoard = board.slice();<br>  if (calculateWinnerOnBoard(newBoard) || newBoard[indexOnBoard]) {<br>    return;<br>  }<br>  newBoard[indexOnBoard] = isNextTurnX(stepNumber) ? &quot;X&quot; : &quot;O&quot;;<br>  await repository.deleteStepsAfterCurrentStepNumber();<br>  await repository.addStep(newBoard);<br>  await repository.setCurrentStepNumber(stepNumber + 1);<br>}<br><br>export async function jumpToStep(<br>  stepNumber: number,<br>  repository: Repository<br>): Promise&lt;void&gt; {<br>  return repository.setCurrentStepNumber(stepNumber);<br>}</pre><h3>Design Presentation layer</h3><p>In Presentation layer, the most important tip is to form <a href="https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller">MVC (Model-View-Controller)</a>. In react applications, we usually amalgamate “model” and “controller” in one object which acts as a bridge between the Presentation layer and the UseCase layer.</p><p>See TicTacToeModelController in the figure below. React components work as “view” in MVC, and refer to “model-controller” with custom hooks. In this way, we can decouple pure rendering codes (”view”) from any data handling codes (”model” and “controller”).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/401/1*KZVpP9avcOFi66OBFK9Hdw.png" /></figure><p>Here is the code for TicTacToeModelController.</p><pre>export function useTicTacToeModelController(repository: Repository) {<br>  const [currentStep, setCurrentStep] = useState&lt;Step | null&gt;(null);<br><br>  useEffect(() =&gt; {<br>    async function init() {<br>      const initialStep = await repository.getCurrentStep();<br>      setCurrentStep(initialStep);<br>    }<br>    init();<br>  }, []);<br><br>  const handleClickOnBoard = async (indexOnBoard: number) =&gt; {<br>    await clickOnBoard(indexOnBoard, repository);<br>    const newStep = await repository.getCurrentStep();<br>    setCurrentStep(newStep);<br>  };<br><br>  const handleJumpToStep = async (stepNumber: number) =&gt; {<br>    await jumpToStep(stepNumber, repository);<br>    const newStep = await repository.getCurrentStep();<br>    setCurrentStep(newStep);<br>  };<br><br>  return {<br>    currentStep,<br>    handleClickOnBoard,<br>    handleJumpToStep,<br>  };<br>}</pre><p>And here is TicTacToeView.</p><pre>type TicTacToeViewProps = {<br>  repository: Repository;<br>};<br><br>export function TicTacToeView({ repository }: TicTacToeViewProps) {<br>  const { currentStep, handleClickOnBoard, handleJumpToStep } =<br>    useTicTacToeModelController(repository);<br><br>  if (!currentStep) {<br>    return null;<br>  }<br><br>  const winner = calculateWinnerOnBoard(currentStep.board);<br>  const xIsNext = isNextTurnX(currentStep.stepNumber);<br>  return (<br>    &lt;div className=&quot;game&quot;&gt;<br>      &lt;div className=&quot;game-board&quot;&gt;<br>        &lt;BoardView board={currentStep.board} onClick={handleClickOnBoard} /&gt;<br>      &lt;/div&gt;<br>      &lt;div className=&quot;game-info&quot;&gt;<br>        &lt;StatusView winner={winner} xIsNext={xIsNext} /&gt;<br>        &lt;JumpToStepButtons<br>          numOfAllSteps={currentStep.numOfAllSteps}<br>          onClick={handleJumpToStep}<br>        /&gt;<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><h3>Design Data layer</h3><p>Data layer has two sub-layers. Data:Repository layer is the layer where you implement the behavior defined in Domain:Repository layer. Data:DataSource layer implements actual data storage such as on-memory storage or network storage.</p><p>As you can see in the figure below, we apply the dependency inversion principle between Domain:Repository layer (upper layer) and Data:Repository layer (lower layer). While the control flow is downwards (e.g. Domain uses Data), the source code dependency is upwards.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/661/1*fnCIn2naW-RJM1BSmwonew.png" /></figure><p>Here is RepositoryImpl:</p><pre>export class RepositoryImpl implements Repository {<br>  dataSource: DataSource;<br><br>  constructor(dataSource: DataSource) {<br>    this.dataSource = dataSource;<br>  }<br><br>  async getCurrentStep(): Promise&lt;Step&gt; {<br>    const [history, stepNumber] = await Promise.all([<br>      this.dataSource.getHistory(),<br>      this.dataSource.getStepNumber(),<br>    ]);<br>    const board = history[stepNumber].board;<br>    const numOfAllSteps = history.length;<br><br>    return { board, stepNumber, numOfAllSteps };<br>  }<br><br>  async setCurrentStepNumber(stepNumber: number): Promise&lt;void&gt; {<br>    const history = await this.dataSource.getHistory();<br>    if (stepNumber &lt; history.length) {<br>      await this.dataSource.setStepNumber(stepNumber);<br>    } else {<br>      throw Error(<br>        `Step number ${stepNumber} should be smaller than the history size (${history.length})`<br>      );<br>    }<br>  }<br><br>  async deleteStepsAfterCurrentStepNumber(): Promise&lt;void&gt; {<br>    const [history, stepNumber] = await Promise.all([<br>      this.dataSource.getHistory(),<br>      this.dataSource.getStepNumber(),<br>    ]);<br>    const trimmedHistory = history.slice(0, stepNumber + 1);<br>    await this.dataSource.setHistory(trimmedHistory);<br>  }<br><br>  async addStep(board: Board): Promise&lt;void&gt; {<br>    const history = await this.dataSource.getHistory();<br>    history.push({ board });<br>    await this.dataSource.setHistory(history);<br>  }<br>}</pre><h3>Design Main layer</h3><p>Finally, we weave all components in several layers into one application in the bootstrap code in the Main layer.</p><p>In this bootstrap code, we create a repository implementation and pass it to TicTacToeView. Then the repository is passed to UseCase layer through TicTacToeModelController.</p><pre>// Dependency injection<br>const dataSource = new OnMemoryDataSourceImpl();<br>const repository = new RepositoryImpl(dataSource);<br><br>export function App() {<br>  return &lt;TicTacToeView repository={repository} /&gt;;<br>}</pre><p>This is a technique called <a href="https://en.wikipedia.org/wiki/Dependency_injection">Dependency Injection (DI)</a>. As you can see in the diagram below, UseCase layer uses (depends on) Repository layer, but the codes in UseCase layer should not create actual objects in Repository layer which depend on lower layer (Data layer).</p><p>By decoupling the object creation (in Main layer) and object usage (in UseCase layer), we can avoid violating the Dependency Rule (all reference arrows should be upwards: lower layer to upper layer).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/742/1*Qf63RbptpS45ji0yedUS9A.png" /></figure><p>That’s it! You can see the final source code <a href="https://gitlab.com/kmiyashita/clean-tic-tac-toe/-/tree/clean-architecture/src">here</a>.</p><h3>Conclusion</h3><p>I showed how to transform your react application codes into clean architecture. Once you become familiar with clean architecture, you may be able to design your code conformant to clean architecture from the very beginning. But even in that case, I hope the design process described in this article would give you good guidance for your refactoring.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cc097a08b105" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/clean-architecture-with-react-cc097a08b105">Clean Architecture With React</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Developing Chrome Extensions With AWS Amplify Authentication]]></title>
            <link>https://medium.com/better-programming/developing-chrome-extensions-with-amplify-authentication-be9b9e496a06?source=rss-bad27daeb320------2</link>
            <guid isPermaLink="false">https://medium.com/p/be9b9e496a06</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Ken Miyashita]]></dc:creator>
            <pubDate>Mon, 10 Jan 2022 02:11:01 GMT</pubDate>
            <atom:updated>2022-01-30T10:59:02.465Z</atom:updated>
            <content:encoded><![CDATA[<h4>Build amazing Chrome extensions</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pm8qMPPrpy4Jetk2W6LOnQ.png" /></figure><p>Chrome extensions are small programs that allow users to customize their browsing experience. Users can customize Chrome functionality and behavior in many ways with them. An extension might overlay information related to the currently displayed web page, for instance.</p><p>Personalized behaviors may be desired when you create Chrome extensions. Displaying information according to the user’s preferences, for example. In this case, your Chrome extension must manage user-specific data on your server. Now it’s time to introduce AWS Amplify. AWS Amplify provides a set of tools and features that lets frontend web and mobile developers quickly and easily build full-stack apps on AWS, with the flexibility to leverage the full breadth of AWS services as your use cases change.</p><p>This article explains how you can create Chrome extensions combining the following technologies.</p><ul><li>React</li><li>TypeScript</li><li>AWS Amplify</li><li>AWS Cognito (Authentication)</li><li>AWS AppSync (GraphQL)</li></ul><p>I have created a boilerplate git repository here, showing a working example.</p><p><a href="https://gitlab.com/kmiyashita/chrome-extension-amplify-auth">Ken Miyashita / chrome-extension-amplify-auth</a></p><h3>Prerequisites</h3><p>The following basics are not covered in this article, and you are expected to be familiar with them. Since those technologies provide comprehensive tutorials, I recommend you go through them first.</p><h4><a href="https://developer.chrome.com/docs/extensions/mv3/getstarted/">Chrome extension</a></h4><ul><li>What are (1) background scripts (2) popup scripts, and (3) content scripts.</li><li>How those scripts are segmented, and how they communicate with each other.</li></ul><h4><a href="https://webpack.js.org/guides/getting-started/">Webpack</a></h4><ul><li>Why bundling is necessary.</li><li>What are (1) entry points, (2) bundles, and (3) loaders.</li></ul><h4><a href="https://docs.amplify.aws/start/q/integration/react/">AWS Amplify (with react)</a></h4><ul><li>How to develop React applications with Amplify.</li><li>How to integrate Amazon Cognito as the main authentication provider.</li><li>How to connect API and database to your applications.</li></ul><h3>What Are the Challenges?</h3><p>You can find many tutorials and working examples online if you want to create simple Chrome extensions or standalone web applications with Amplify.</p><p>However, if you want to combine the above technologies, you would encounter the following challenges. The solution may seem obvious after reading this article.</p><p>But I spent a few weeks trying to achieve a stable codebase just combining them, and I believe my boilerplate would be helpful as a starter.</p><h4>Folder structure</h4><p>Multiple small scripts (applications) are working together, sharing code auto-generated by Amplify. What is the most appropriate folder structure for them?</p><h4>Webpack configuration for Chrome extensions with react</h4><p>Typically, <a href="https://create-react-app.dev/"><em>create-react-app</em></a> is used when creating react applications. It is a great tool and gives you a solid starting point to develop full-fledged react applications.</p><p>But you cannot use the outcome of create-react-app as is for your Chrome extensions.</p><p>Although we need to create multiple bundles (background script, popup script, content script), create-react-app does not support that use case.</p><h4>Managing security tokens for AWS authentication</h4><p>By default, AWS Amplify stores security tokens in localStorage for the browser. But if you want to sign in on your Chrome extension’s popup window and let the content script access personalized data, this default behavior is inconvenient. You need to establish the way to manage security tokens shared among popup scripts and content scripts.</p><h3>Chrome Extension Example (Boilerplate)</h3><h4>Overview</h4><p>The boilerplate is a fully functional (but minimal) application with the following features.</p><ul><li><strong>Portal site: </strong>It is a simple react application accessing personalized data (ToDo items) on AWS.</li><li><strong>Popup script:</strong> It allows users to sign in to AWS. Security tokens are stored in Chrome storage.</li><li><strong>Content Scripts:</strong> With security tokens in Chrome storage, content scripts access personalized data on AWS.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6wNbAV5UCg8832ZtWk_bBQ.png" /></figure><h4>Setup</h4><p>Clone <a href="https://gitlab.com/kmiyashita/chrome-extension-amplify-auth.git">the boilerplate repo</a>, and install dependencies.</p><pre>$ git clone <a href="https://gitlab.com/kmiyashita/chrome-extension-amplify-auth.git">https://gitlab.com/kmiyashita/chrome-extension-amplify-auth.git</a><br>$ cd chrome-extension-amplify-auth<br>$ yarn</pre><p>Move to the subfolder for Amplify project and initialize the project.</p><pre>$ cd packages/amplify-shared<br>$ amplify init<br>? Choose your default editor: Visual Studio Code<br>? Select the authentication method you want to use: AWS profile<br>? Please choose the profile you want to use:  default</pre><p>Lastly, provision the backend resources using the config files in the amplify directory.</p><pre>$ amplify push</pre><h4>Run Chrome Extension</h4><p>Build Chrome Extension:</p><pre>$ yarn build</pre><p>Open the Extension Management of Chrome browser, and load the extension built in chrome-extension-amplify-auth/packages/chrome-ext/dist</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/578/1*FCBqFpsXG-jjGa25kDzz7A.png" /></figure><p>When you open any web page, you’ll notice that your content script shows a small overlay at the lower right corner.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/646/1*H55IMzDNgpRK4qyXg1hXCA.png" /></figure><p>By clicking on the Chrome extension icon, you can open a pop-up window. Create a new user account, and sign in.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/429/1*XJYgq44rAVzFfIoL44PiHA.png" /></figure><p>Now, the overlay by the content script automatically updates and shows ToDo items.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/518/1*OeuBiW2OH_R9g8YBWCnjxA.png" /></figure><h4>Run Portal Site</h4><p>Run the webserver for the portal site.</p><pre>$ yarn start-web</pre><p>Open http://localhost:8080 in Chrome browser, and observe ToDo items.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/664/1*opwsXeuUUbcaBjKfC33zMQ.png" /></figure><h3>Folder Structure</h3><p>We have the following two requirements regarding folder structure.</p><ul><li>Amplify code should be shared among multiple bundles in Chrome extension (content script, popup script) and Portal site.</li><li>Multiple bundles (content script, popup script, background script) need to be created for the Chrome extension.</li></ul><p>In order to meet those requirements, we take the following approach.</p><ul><li>Monorepo structure.</li><li>Amplify project forms an independent package (amplify-shared) in monorepo structure. This package is shared among two packages: chrome-ext and web-ui.</li><li>The package“chrome-ext has three subfolders for background script, content script, and popup script. Webpack creates bundles from those subfolders.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E31WYh6bxyv5SWz5thrh2A.png" /></figure><h3>Webpack Configuration for Chrome Extension</h3><p>Webpack is a static module bundler for modern JavaScript applications. In most cases, webpack does not require a configuration file to bundle your project since version 4.0.0. But we would introduce the minimal configuration file <a href="https://gitlab.com/kmiyashita/chrome-extension-amplify-auth/-/blob/main/packages/chrome-ext/webpack.config.js">webpack.config.js</a> for the following purposes.</p><ul><li>Create multiple bundles (background script, popup script, content script)</li><li>Compile TypeScript codes into JavaScript.</li><li>Suppress using eval for source mapping since Chrome extension’s CSP (Content Security Policy) does not allow it.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dNy5wHAnGLIRh7NUoMwp2Q.png" /></figure><h3>Authentication</h3><p>When you sign in using Authentication with AWS Amplify, security tokens are stored in <a href="https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage"><em>localStorage</em></a> by default. After signing in, Amplify functions to access data use the stored security tokens.</p><p>Unfortunately, in our scenario, this mechanism doesn’t work as intended. Popup script runs in the extension’s context while content scripts run in the context of a web page and not the extension. Since <em>localStorage</em> is segmented per context, security tokens stored by popup script cannot be accessed by content scripts.</p><p>But Amplify is well designed, and <a href="https://docs.amplify.aws/lib/auth/manageusers/q/platform/js/#managing-security-tokens">it allows us to customize where security tokens are stored.</a> In order to solve this problem, we use <a href="https://developer.chrome.com/docs/extensions/reference/storage/"><em>chrome.storage.local</em></a>. It provides the same storage capabilities as the localStorage API with the following key differences:</p><ul><li>Your extension’s content scripts can access user data in common shared with the popup script.</li><li>It’s asynchronous with bulk read and write operations, and therefore faster than the blocking and serial localStorage API.</li></ul><p>Here is the <a href="https://gitlab.com/kmiyashita/chrome-extension-amplify-auth/-/blob/main/packages/chrome-ext/src/common/SharedAuthStorage.ts">SharedAuthStorage.ts</a> implementing our custom storage for security tokens.</p><p><strong>In the popup script</strong></p><ul><li>setItem()<em> </em>is called and security tokens are stored in <em>chrome.storage.local</em>.</li></ul><p><strong>In the content script</strong></p><ul><li>sync()<em> </em>is called in Amplify.configure(). It populates on-memory cache, scanning chrome.storage.local.</li><li>Once on-memory cache is populated,<em> </em>getItem() can return values (security tokens) synchronously.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/637101f592c4ef4750eaa2703886b70f/href">https://medium.com/media/637101f592c4ef4750eaa2703886b70f/href</a></iframe><p>You can configure Amplify to use this custom storage <a href="https://gitlab.com/kmiyashita/chrome-extension-amplify-auth/-/blob/main/packages/chrome-ext/src/content/Overlay.tsx#L8">as follows.</a> In this way, you combine your customization and various AWS configuration parameters (awsExports) managed by Amplify CLI.</p><pre>Amplify.configure({<br>    ...awsExports,<br>    Auth: {storage: SharedAuthStorage}<br>});</pre><p>This article explains how to use Amplify with authentication in your Chrome extensions. Hope the boilerplate will help your development.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=be9b9e496a06" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/developing-chrome-extensions-with-amplify-authentication-be9b9e496a06">Developing Chrome Extensions With AWS Amplify Authentication</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>