<?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 Tomáš Gold on Medium]]></title>
        <description><![CDATA[Stories by Tomáš Gold on Medium]]></description>
        <link>https://medium.com/@tomgold_48918?source=rss-a5e68992a20b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*aXK6UzsRvB5ruYWCC__JWA.jpeg</url>
            <title>Stories by Tomáš Gold on Medium</title>
            <link>https://medium.com/@tomgold_48918?source=rss-a5e68992a20b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 02:45:43 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@tomgold_48918/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[Let’s Make Jest Run Much Faster]]></title>
            <link>https://medium.com/@tomgold_48918/lets-make-jest-run-much-faster-ddeefa754969?source=rss-a5e68992a20b------2</link>
            <guid isPermaLink="false">https://medium.com/p/ddeefa754969</guid>
            <dc:creator><![CDATA[Tomáš Gold]]></dc:creator>
            <pubDate>Mon, 28 Oct 2024 11:21:06 GMT</pubDate>
            <atom:updated>2024-10-28T16:09:47.863Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/779/1*ERwObHrniGN2whANjFOEJg.png" /></figure><p>But first, we need to understand why it is so slow.</p><h3>Practical Example</h3><p>Consider a simple React component.</p><pre>import React from &quot;react&quot;;<br>import { deepClone } from &quot;./utils&quot;;<br><br>export function App() {<br>  const obj = { foo: &#39;bar&#39; };<br><br>  return (<br>    &lt;div&gt;<br>      &lt;p&gt;Object looks like this: {JSON.stringify(deepClone(obj))}&lt;/p&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p><em>App </em>component depends only on one utility function — <em>deepClone</em>. The <em>utils </em>file looks like this.</p><pre>import _ from &#39;lodash&#39;;<br>import moment from &#39;moment&#39;;<br>import * as mui from &#39;@mui/material&#39;;<br><br>export const deepClone = (obj) =&gt; _.cloneDeep(obj);<br>export const getFormattedDate = (date) =&gt; moment(date).format(&#39;YYYY-MM-DD&#39;);<br>export const isButton = (instance) =&gt; instance === mui.Button;</pre><p>It exports three one-line helper functions. That’s it.</p><p>Now, here’s a big question: How long do you think it will take to execute this test?</p><pre>import React from &quot;react&quot;;<br>import { render, screen } from &quot;@testing-library/react&quot;;<br>import { App } from &quot;./app&quot;;<br>import &quot;@testing-library/jest-dom&quot;;<br><br>test(&quot;renders the app&quot;, () =&gt; {<br>  render(&lt;App /&gt;);<br>});</pre><p>The answer? <strong>An eternity!</strong></p><pre> PASS  src/tests/react-app/react-app.test.js<br>  √ renders the date and sum correctly (25 ms)<br><br>Test Suites: 1 passed, 1 total<br>Tests:       1 passed, 1 total<br>Snapshots:   0 total<br>Time:        5.045 s</pre><p>It took 5 seconds on my machine, to execute a one-liner test case for a one-liner React component.</p><h3>Analyzing Performance</h3><p>To analyze what is happening behind the scenes, we can use either Chrome’s profiler — I recommend watching <a href="https://www.youtube.com/watch?v=RB2g-o39upo&amp;t=153s&amp;pp=ygUPamVzdCBwcm9maWxsaW5n">this insightful video by Kent C. Dodds</a>.</p><p>Alternatively, you can use a <a href="https://www.npmjs.com/package/jest-neat-runner"><strong>jest-neat-runner</strong></a><strong> </strong>library, which simplifies the profiling process. Set the NEAT_REPORT_MODULE_LOAD_ABOVE_MS option to 150 and enable NEAT_REPORT_TRANSFORM. This configuration will print out the modules that take more than 150ms to load and provide information on how long it took to process (open and transpile) the files.</p><p>Let’s use the latter. This is the output.</p><pre>&gt; jest src/tests/react-app/<br><br>From src\tests\react-app\utils.js -&gt; @mui/material in 1759ms<br>From node_modules\@mui\material\node\styles\adaptV4Theme.js -&gt; @mui/system in 509ms<br>From src\tests\react-app\react-app.test.js -&gt; @testing-library/react in 317ms<br>From node_modules\@testing-library\react\dist\pure.js -&gt; @testing-library/dom in 266ms<br>From node_modules\@mui\system\ThemeProvider\ThemeProvider.js -&gt; @mui/private-theming in 166ms<br>From node_modules\@testing-library\dom\dist\role-helpers.js -&gt; aria-query in 161ms</pre><p>We’re loading “<em>@mui/material</em>” library for almost 2 seconds without even using it!</p><h3>Root Cause In Many Projects?</h3><h4>Messy Dependencies</h4><p>In my experience, performance problems with jest mainly stem from the large number of transitive dependencies that aren’t even used at runtime. As showcased in our example above, if you don’t pay enough attention to what files you import into your application, you might end up in the same situation as me.</p><p>In my case, the <em>App </em>component only depends on the <em>deepClone </em>utility function. However, since <em>deepClone </em>is exported from the <em>utils </em>file, all the dependencies within the <em>utils </em>file were also loaded along with it.</p><p>Files that contain a lot of loosely related functions and heavy dependencies might significantly slow down your application and tests.</p><h4>Barrel Files</h4><p>Jest is not a friend with ESM modules, which leads it to fallback to CommonJS. Consequently, tree-shaking doesn’t function correctly. This is particularly problematic when relying on modules imported from barrel files (index files).</p><p>For instance, when you import a small component or function from a barrel file, Jest will load everything else as well — which obviously causes an unnecessary overhead.</p><h3>What Now?</h3><h4>Adjusting the Import Strategy Manually</h4><p>Aside from removing the barrel files and refactoring the entire codebase by breaking up files with numerous dependencies into smaller, more focused modules. We can identify modules that take a long time to load and look for smaller alternative modules or check if the imported module exports individual parts separately (i.e., named imports) instead of using the barrel file.</p><p>Meaning, instead of</p><pre>import { cloneDeep } from &#39;lodash&#39;;</pre><p>do</p><pre>import cloneDeep from &#39;lodash/cloneDeep&#39;;</pre><p>If we’re not using the module at all, we can mock it via jest.mock to avoid loading it completely.</p><p>However, these adjustments can be quite time-consuming.</p><h4>Runtime Cache Approach</h4><p>A more effective method involves using the <a href="https://www.npmjs.com/package/jest-neat-runner"><strong>jest-neat-runner</strong></a> library with the NEAT_RUNTIME_CACHE option. When this option is on, the library tracks the real runtime usage of all modules (per test file) and stores dependencies that we do not need for subsequent test runs into a cache. Let me show what it does on the example above</p><pre>&gt; jest src/tests/react-app/<br><br>From src\tests\react-app\react-app.test.js -&gt; @testing-library/react in 292ms<br>From node_modules\@testing-library\react\dist\pure.js -&gt; @testing-library/dom in 241ms<br>From node_modules\@testing-library\dom\dist\queries\role.js -&gt; aria-query in 176ms<br><br> PASS  src/tests/react-app/react-app.test.js<br>  √ renders the date and sum correctly (33 ms)<br><br>Test Suites: 1 passed, 1 total<br>Tests:       1 passed, 1 total<br>Snapshots:   0 total<br>Time:        2.29 s<br>Ran all test suites matching /src\\tests\\react-app\\/i.<br> 📢 Jest run done: 1/1 suites passed on the first run. <br>    Used neat cache for 1 file(s).<br>    Node modules skipped: 26.<br>    Source modules skipped: 0.<br><br></pre><p>We reduced the execution time from five seconds to two by skipping the loading of 26 unnecessary libraries, including the MUI library.</p><p>Be cautious — there are several caveats when using NEAT_RUNTIME_CACHE, so make sure to read the README before using it.</p><h3>Other Optimization Techniques</h3><ol><li><strong>Transpilation optimisations</strong>: Examine how many files need to be transpiled and use the most effective transpiler (like SWC or esbuild). If you want to save time, the NEAT_REPORT_TRANSFORM option in <strong>jest-neat-runner</strong> will provide detailed information on how much time and how many modules it takes to transpile.</li><li><strong>Caching Modules in Memory</strong>: By default, Jest does not cache modules in memory, meaning every test run must open, parse, and load the module into memory. If you have a vast suite of tests and enough memory, consider using the NEAT_TRANSFORM_CACHE option to speed things up.</li></ol><h3>What About the CI Pipeline?</h3><ol><li><strong>Parallel Runs</strong>: CircleCI and GitHub Actions support parallel runs. This means you can spin up more machines and divide the load using the <a href="https://jestjs.io/docs/next/cli#--shard">shard </a>parameter in Jest.</li><li><strong>Storing the Jest and Neat Cache</strong>: This is crucial for taking advantage of Jest and <strong>jest-neat-runner</strong> in the CI. Be sure to set the cacheDirectory option in Jest. Then, store the directory after the test run, and restore the cache before running the tests. <strong>Caveat</strong>: If you’re using parallelism, ensure you store unique caches for each node. For instance, CircleCI exposes the CIRCLE_NODE_INDEX environment variable, which you can leverage when storing the cache. This is how it looks in the CircleCI.</li></ol><pre>  - restore_cache:<br>      name: Restore Jest Cache<br>      keys:<br>        - jest-cache-{{ .Branch }}-{{ checksum &quot;package-lock.json&quot; }}-{{ .Environment.CIRCLE_NODE_INDEX }}<br>  - run:<br>      name: Run Tests with Jest<br>      command: |<br>        mkdir -p ~/repo/cache/jest<br>        npm test -- --cacheDirectory=~/repo/cache/jest<br>  - save_cache:<br>      name: Save Jest Cache<br>      key: jest-cache-{{ .Branch }}-{{ checksum &quot;package-lock.json&quot; }}-{{ .Environment.CIRCLE_NODE_INDEX }}<br>      paths:<br>        - ~/repo/cache/jest</pre><p>By following these guidelines, you can significantly enhance Jest’s performance in your projects.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ddeefa754969" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to scan barcodes from your phone into a database]]></title>
            <link>https://medium.com/@tomgold_48918/how-to-scan-barcodes-from-your-phone-into-a-database-7b747cda1df7?source=rss-a5e68992a20b------2</link>
            <guid isPermaLink="false">https://medium.com/p/7b747cda1df7</guid>
            <category><![CDATA[database]]></category>
            <category><![CDATA[barcode]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[low-code]]></category>
            <dc:creator><![CDATA[Tomáš Gold]]></dc:creator>
            <pubDate>Sun, 11 Oct 2020 19:50:58 GMT</pubDate>
            <atom:updated>2020-10-11T19:50:58.498Z</atom:updated>
            <content:encoded><![CDATA[<p>MySQL, PostgreSQL, and many more (even HTTP API)!</p><p>Whether you need to send data from your database to mobile or insert data from your mobile to the database, today I will show you how you can do that in<strong> 5 minutes</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*1dv6FhhcEcHinYLPpEl-jw.gif" /><figcaption>The final result of the application</figcaption></figure><p>Our MySQL database looks like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/1*6FucTLZV0MbD1Z4GfQVc4A.png" /><figcaption>Stock database with a stock table and its content</figcaption></figure><p>We have a database named <strong>stock </strong>with table<strong> stock </strong>which contains columns id, name, and amount. I want to scan a barcode (which contains the id of the item) and show the details of the scanned item in my mobile app.</p><p>In order to do that without much effort, we will download <a href="https://www.auri.auriosoftware.com/download.html">Auri</a>, extract its content, and run auri-server.</p><p>This platform allows us to create mobile/web applications and connect them with various API/databases very fast without even touching a single backend or frontend code at all.</p><p>After running auri-server, it should automatically open the IDE in the browser with the default application. It should look like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qhMkjTOI44FFjuuAjP5nnQ.png" /><figcaption>The first run of the Auri application</figcaption></figure><p>The left side panel contains the configuration of the application (backends, components, …). On the right side, we can see the final application in a real-time. The bottom bar contains some debug information like databases call, available variables, and other helpful things.</p><p>We will create a simple app with an autocomplete component that will contain all the data from the <strong>stock </strong>table and then we can search for a specific stock item in the table either by scanning a barcode or by typing its name.</p><p>The whole configuration file looks as follows. You can easily copy-paste this configuration and only modify the SQL statements and that is it!</p><pre>name: Stock<br>backends: <strong><br>  - MySQL: <br>      database: stock<br>      host: localhost<br>      user: root<br>      password: root<br>      port: 3306</strong><br>start: Main<br>screens: <br>  Main:<br>    title: Stock<br>    components: <br>      - autocomplete: <br>          placeholder: Search item...<br>          name: stockId<br>          <strong>query: SELECT * FROM stock</strong><br>          withScanner: true<br>          itemId: $id<br>          itemTitle: $name<br>          onSelect: <br>            <strong>- query: SELECT * FROM stock WHERE id = $stockId</strong><br>            - goToScreen: StockDetail<br>  StockDetail:<br>    onGoBack: <br>      - resetVariables<br>      - goToScreen: Main<br>    title: Detail<br>    components: <br>      - item:<br>          title: $name<br>          details:<br>            - amount: $amount<br>            - id: $id</pre><p>The configuration is simple.</p><p>The application name is Stock. We want to connect to the MySQLdatabase named stock. The start screen is Main. The Main screen contains the component autocomplete which contains data from thequery SELECT * FROM stock . Each item in autocomplete has to have a title which is displayed to the user and idfor the unique identification of the item.</p><p>When selecting an item by scanning or manual typing it will trigger the onSelect operation which will call thequery SELECT * FROM stock WHERE id = $stockId . The selected item id is stored in the variable stockId which corresponds to the name of the component. After that, we will go to screen StockDetail which renders the item component with the information from the previous SQL query “SELECT * FROM stock WHERE id = $stockId”.</p><p>Used variables in the item component <strong><em>$name</em>, <em>$amount</em> </strong>and <strong><em>$id</em></strong> correspond to the columns from the previous query.</p><p>The final result looks like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aTGnpx1isdkPY-_CEdVrig.png" /></figure><h4>And that is all!</h4><p>Now you can grab a mobile phone, click the preview icon on the top right section and go test your application!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*lDaZsLbnpIzPd-vXjNygaA.gif" /></figure><p>The production deployment is very easy, just follow <a href="https://www.auri.auriosoftware.com/docs/#production-section">these steps.</a> You can turn on device authentication, alerting, and even monitor the traffic in the <a href="https://www.auri.auriosoftware.com/docs/#prod-admin-ui">admin section</a>.</p><p>Are you missing some database connector or some other feature? Do you have some issues or questions? Join <a href="https://discord.com/invite/Svc7rTw">this discord</a> and the developers of the platform will definitely help you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7b747cda1df7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[This is why coupling is your worst enemy]]></title>
            <link>https://itnext.io/this-is-why-coupling-is-your-worst-enemy-d4678d0cab49?source=rss-a5e68992a20b------2</link>
            <guid isPermaLink="false">https://medium.com/p/d4678d0cab49</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[http-request]]></category>
            <dc:creator><![CDATA[Tomáš Gold]]></dc:creator>
            <pubDate>Mon, 19 Nov 2018 15:52:55 GMT</pubDate>
            <atom:updated>2019-07-07T14:58:07.189Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SFELgpAxx_k8W7BRFF8hOg.png" /></figure><p>Let me show you its negative impact on poorly written HTTP Server (<a href="https://expressjs.com/">Express Framework</a>) in <strong>Node.Js.</strong></p><p><strong><em>We build spectacular apps, check </em></strong><a href="https://auriosoftware.com/"><strong><em>auriosoftware.com</em></strong></a></p><p>It always starts with an interesting prediction that our new server will be “small and simple”.</p><p>And yet, as most of the predictions, even this one will soon be doomed.</p><h4>It all starts with this boilerplate code</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/24e1282759c9921445b49e2ef335da39/href">https://medium.com/media/24e1282759c9921445b49e2ef335da39/href</a></iframe><p>The first use case is quite simple. When our server receives a login request from a client it will call the <strong>external HTTP API</strong> and when everything goes well it will send the 200 status code response to the end user.</p><p>We are building <strong>middleware</strong>. This server stands between UI and the <strong>external HTTP</strong> endpoint which should not be known to the end user.</p><p>Small and simple, as it should be.</p><p>This is a test snippet for this use case.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f4deeb7a241292d77dbe1dc0d342055a/href">https://medium.com/media/f4deeb7a241292d77dbe1dc0d342055a/href</a></iframe><p>When our external endpoint returns OK status code we are expecting that proper response is sent to the end user.</p><h4>Couple months later</h4><p>After some time our middleware has many more use cases to handle. Therefore a lot of new functions like this came up and a lot of these test cases came up as well.</p><p>We find out that we have to change our HTTP server (express) because it is too slow and some new fancy HTTP server has just come up.</p><p>So we go into the code and realize…. that… well… <strong>we are pretty much doomed.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/374/1*tOIjeDcbge_UJChJs1dqbQ.gif" /></figure><p>WHY??</p><p>Because we have to change <strong>EVERYTHING</strong>.</p><p>Yes, I mean everything. Just look at our code, we have express everywhere. In our tests and in our production code.</p><p><strong>We tightly coupled our high-level policy with low-level details like express response and request object.</strong></p><p>Just look at the code. If we want to change our HTTP server we have to go through the whole code base and change the API of the express request and response object to the API of the new server.</p><p>Our old test snippet.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2ef23a4012b04d53a97eacfb83279fbd/href">https://medium.com/media/2ef23a4012b04d53a97eacfb83279fbd/href</a></iframe><p>New snippet with changed API.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cf69092b876021f66c383a20b33ca0d2/href">https://medium.com/media/cf69092b876021f66c383a20b33ca0d2/href</a></iframe><p>Old production code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ef66197236abbf473f6f2169b166ebd6/href">https://medium.com/media/ef66197236abbf473f6f2169b166ebd6/href</a></iframe><p>New one.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c488441630216424ee9f008ffa81b31d/href">https://medium.com/media/c488441630216424ee9f008ffa81b31d/href</a></iframe><h4>Couple months later #2</h4><p>We somehow managed to change our HTTP server to the new one (after a lot of time spent).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/288/1*ff4Bt3cpqenRyiNmNlrl7w.gif" /></figure><h4>Couple months later #3</h4><p>Our product owner came to us that we have to change our external HTTP endpoint to another one which has completely different API.</p><p>So we run our IDE and realized…</p><p>well…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/240/1*zkhojjWIsW2WkNT2PPsaKg.gif" /></figure><p>We are pretty much fuc***, doomed. That we are pretty much doomed again.</p><p><strong>And WHY??</strong></p><p>because again, we coupled our <strong>low-level detail (the external API) with our high-level policy everywhere</strong>.</p><p>Just look at the code, we have to go through our code base again and change the API of our external HTTP endpoint.</p><p>This is how the old external endpoint looks.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/95394df5170ef41c4109a222f61e0f97/href">https://medium.com/media/95394df5170ef41c4109a222f61e0f97/href</a></iframe><p>The new API.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6734bbdfe361ad4da0212fdff348c9fb/href">https://medium.com/media/6734bbdfe361ad4da0212fdff348c9fb/href</a></iframe><p>The class diagram of whole Login use case looks like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*0EuDppVrMCMXfu8DmW226A.png" /></figure><p>So… how do we fix that?</p><h3>What about this solution?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/817/1*G4RuybDWvX4JdGjzKIQiRw.png" /></figure><p>Login has no knowledge of its surroundings! (<a href="https://en.wikipedia.org/wiki/Law_of_Demeter">Law of Demeter</a>) .</p><p>It has knowledge of stable interfaces like <strong>Response</strong>, <strong>Request</strong>, and <strong>Action</strong>. It does not know whether Response is the express object, node object or whatever object. It does not care.</p><p>We obey <a href="https://en.wikipedia.org/wiki/Dependency_inversion_principle"><strong>Dependency Inversion Principle</strong></a> because high-level module (Login) depends on abstractions (Response, Request, and Action) and low level-details (Express Response, Request, and Specific External HTTP Endpoint) depends on these abstractions as well.</p><p>We inverted the dependencies. Now we can change the Express HTTP server in one place, without breaking anything else. And that is exactly what we wanted. We don’t care about changing the specific external HTTP endpoint either. We depend on the abstraction called <strong>Action</strong>. It could be anything.</p><p>Just look at the new code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0ce68e0c25c944cdd40037ccbbd0473c/href">https://medium.com/media/0ce68e0c25c944cdd40037ccbbd0473c/href</a></iframe><p>Request and Response Adapters looks as follows.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/232e5cd84377bee591838fd45f5bb219/href">https://medium.com/media/232e5cd84377bee591838fd45f5bb219/href</a></iframe><p>And Specific External Login Action.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4848f50789410050ecd5c97fea05d1f9/href">https://medium.com/media/4848f50789410050ecd5c97fea05d1f9/href</a></iframe><p>If we need to change the external HTTP action we would only create a new file. If we need to change the HTTP server we would only create new files with new server and adapters for his request and response object.</p><p><strong>We would not change the Login file (use case) at all!</strong></p><h3>Applied Patterns and Principles</h3><h4>Law of Demeter</h4><blockquote>“a given object should assume as little as possible about the structure or properties of anything else (including its subcomponents)”</blockquote><h4>Dependency inversion principle</h4><blockquote>“High-level modules should not depend on low-level modules. Both should depend on <a href="https://en.wikipedia.org/wiki/Abstraction_(computer_science)">abstraction</a>”</blockquote><h4>Adapter Pattern</h4><blockquote>“allows otherwise incompatible classes to work together by converting the interface of one class into an interface expected by the clients.”</blockquote><h3>Oh boy… that JavaScript thingy</h3><blockquote>“But…JavaScript doesn’t have interfaces so there are no dependencies towards classes and interfaces from your diagram”</blockquote><p>Don’t be fooled!</p><p>There are no <strong>explicit</strong> dependencies, but there are definitely <strong>implicit</strong> ones!</p><p>If Login action would not use the same API provided from the interfaces Request, Response, and Action it would throw a runtime error during the action somewhere in the code.</p><p>I strongly suggest using TypeScript instead because a lot of people fall into this trap. With TypeScript, you can define explicit dependencies of your module and it helps you to keep your design clean.</p><h3>It’s not all sunshine and rainbows</h3><p>There is still at least one problem. Our business logic (Login use case) is still coupled with the HTTP protocol. If you look at the diagram you could see that coupling. But imagine how much abstraction would be necessary to decouple that (look at the login example).</p><p>Adding more and more abstractions could potentially harm us. Just imagine how much code would you have to write in order to decouple that. And even adding a new use case would be really hard and time-consuming.</p><p>It is wise to think about your project and consider such a change to your design because the price for this flexibility is really expensive.</p><p><a href="http://foobazbar.club/">More articles in my blog <strong>foobazbar.club</strong></a><strong>.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d4678d0cab49" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/this-is-why-coupling-is-your-worst-enemy-d4678d0cab49">This is why coupling is your worst enemy</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why I stopped using snapshot testing with Jest]]></title>
            <link>https://medium.com/@tomgold_48918/why-i-stopped-using-snapshot-testing-with-jest-3279fe41ffb2?source=rss-a5e68992a20b------2</link>
            <guid isPermaLink="false">https://medium.com/p/3279fe41ffb2</guid>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[jest]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[snapshot]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Tomáš Gold]]></dc:creator>
            <pubDate>Thu, 01 Nov 2018 09:49:27 GMT</pubDate>
            <atom:updated>2019-07-07T15:10:12.698Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*RQwRLQ0yyCvYmRn_Nst5yg.png" /></figure><p>These days a lot of people is using <a href="https://jestjs.io/docs/en/snapshot-testing">Jest’s snapshot testing </a>on a daily basis. I will show you reasons why I stopped.</p><blockquote><em>We build spectacular apps, check</em><strong><em> </em></strong><a href="https://auriosoftware.com/"><strong><em>auriosoftware.com</em></strong></a></blockquote><h4>Fragility</h4><p>We changed a little bit of code and it blew off half of our tests. The problem is that these snapshots are highly coupled with our implementation and as we all know, coupling is one of the biggest pain in software development.</p><p>How coupled you asked?</p><p>Imagine we have a component and we created a new <strong><em>div</em></strong> container because of a new design requirement. We run the tests and here it is, our friendly output from our failing snapshot test.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CIoGNmc8-GDU17orr5cL5Q.png" /></figure><p>We voluntary highly coupled the component’s DOM with our tests. Every time we do even a little change to our code, <strong>our tests will fail!</strong></p><p>That new div container is there only because of some minor cosmetic change. It did not even slightly touch component’s functionality and it definitely did not change the component’s contract, but still, our test failed.</p><p>Some of you might say…</p><blockquote>“But this test helps you because you can notice that something is wrong”</blockquote><p>Let me introduce you to my working process.</p><ol><li>I create a new feature</li><li>I will check “manually” that the UI is properly rendered and all functionality is really working.</li><li>I will check whether my tests are passing</li><li>Before every commit I create, I will run git diff and look whether a code is clean and properly tested.</li></ol><p>And look at my console’s output, does not it look familiar to you?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/638/1*X0O7Sw8oM9v3VWLojc92RA.png" /></figure><p>This output has the same value as the snapshot test, and yet, it is not that annoying.</p><p>I can see that I added only one <em>div</em> element. I will create a commit and push it to the source code repository. Then, I am creating a pull request and guess what.</p><p><strong>My colleague will go through the same working process as I did.</strong></p><p>Our bugs in the system do not exist because of our luck of snapshot tests, but most likely because of our lack of discipline and professionalism.</p><h4>Irrelevance (after time)</h4><p>Let&#39;s say you have quite a big project with a lot of these snapshot tests. You created a new feature, you are great, you are happy… until you run the tests.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*1hlPjyTVoTzGDQMcENVQjA.gif" /></figure><p>Well, most of them failed.</p><p>It is frustrating, but you check all of these failed tests whether something is wrong and update them. This becomes part of your working process.</p><p><strong>A couple of weeks later.</strong></p><p>You have become professional snapshot updater, congratulations. You have gained so much experience because you have been doing this whole eternity. Your brain knows every shortcut for updating a snapshot.</p><p>Actually, you are so experienced that you most probably don’t even look at these failed snapshots. You will update them automatically because your brain is convinced that nothing is wrong.</p><p>These tests became <strong>irrelevant</strong> because you are completely ignoring them.</p><h4>No TDD!</h4><p>This is the biggest obstacle for me because I can’t imagine to code without writing a test first. If you are thinking about creating a snapshot first, well, good luck with that.</p><h4>Descriptiveness</h4><p>Seriously, who would not love this syntax?</p><pre>test(&#39;render Markdown in preview mode&#39;, () =&gt; {<br>    const wrapper = shallow(<br>        &lt;MarkdownEditor value=&quot;*Hello* Jest!&quot; /&gt;<br>    );</pre><pre>    <strong>expect(wrapper).toMatchSnapshot();</strong></pre><pre>    wrapper.find(&#39;[name=&quot;toggle-preview&quot;]&#39;).simulate(&#39;click&#39;);</pre><pre>    <strong>expect(wrapper).toMatchSnapshot();</strong><br>});</pre><p>Good tests are supposed to be good documentation. If you don’t know how the component works, you should just look at your tests.</p><p>But…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/195/1*eKABkUzJKEc9oWoFf9qrpQ.gif" /></figure><p>What is the mysterious snapshot? Where it comes from? What actually happens when i click on the toggle preview?</p><p>Tests should have 3 parts: Arrange, Act and Assert.</p><ol><li><strong>Arrange</strong> — instantiate the component</li><li><strong>Act</strong> — click on the toggle preview</li><li><strong>Assert</strong> — match snapshot (?)</li></ol><p>Do you really know what should happen after we clicked on that?</p><p>I am missing something in the Assert part. It is not explicit enough. It reminds me of this scene from South Park.</p><p><a href="https://www.youtube.com/watch?v=tO5sxLapAts">https://www.youtube.com/watch?v=tO5sxLapAts</a></p><p>Needless to say, there is quite a big chance that you would create an invalid snapshot because you are depending on the correctness of your implementation.</p><h4>False safety</h4><p>When I joined a team which has been working on a project for a while, my first question was</p><blockquote>“Do you have a tests?”</blockquote><p>And they replied (with the proud look in their eyes)</p><blockquote>“Hell Yeah”</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*o3WLd0EYbSQjLnEIiAoBag.gif" /></figure><p>I was really glad because I had worked with people who did not even try to write tests. So I jumped to the code and saw something…interesting.</p><pre>describe(&#39;&lt;UserForm /&gt;&#39;, () =&gt; {<br>    it(&#39;should render&#39;, () =&gt; {<br>        <strong>const </strong>renderer = <strong>new </strong>ShallowRenderer();<br>        renderer.render(&lt;UserForm /&gt;);<br>        <strong>const </strong>result = renderer.getRenderOutput();<br>        expect(result).toMatchSnapshot();<br>    });<br>});</pre><p>I call it <strong><em>‘it should render </em></strong>’ disease. I saw it everywhere, and why? Because it was so easy to write these tests and let me tell you, managers were pumped how fast the implementation went (yes, it was a greenfield project only a couple of months old).</p><p>Why is this a problem?</p><p><strong>Because the tests were green!</strong></p><p>They were confident enough to deploy all new features with these “tests” because at the end of the day, tests were passing and after all, tests were part of the acceptance criteria of a complete ticket (story), therefore mandatory.</p><p>It was fun, it was fast, but it was missing test cases which would test the component’s functionality (contract), therefore it was useless.</p><p>I could not imagine changing the existing code because I would not know whether my change broke some functionality, but I definitely knew that I am going to break some snapshot tests.</p><h4>Summary</h4><p>I am not saying that snapshot testing is a bad thing…</p><p>Just kidding, I think it is pretty bad.</p><p>It is not a great idea to couple your implementation details with these tests. At least in my world. I can not imagine a world where all members of a team are being professional enough and being careful and brave to pain attention to these failed snapshot tests.</p><p>I would look around for a different solution, maybe something like <a href="https://www.chromaticqa.com/">Chromatic</a>, because it is not coupled with DOM.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3279fe41ffb2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to properly test React Components]]></title>
            <link>https://itnext.io/how-to-properly-test-react-components-9f090969cb6f?source=rss-a5e68992a20b------2</link>
            <guid isPermaLink="false">https://medium.com/p/9f090969cb6f</guid>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[enzyme]]></category>
            <category><![CDATA[jest]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Tomáš Gold]]></dc:creator>
            <pubDate>Thu, 25 Oct 2018 13:29:38 GMT</pubDate>
            <atom:updated>2019-07-07T15:11:37.602Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AesMA3F0ivTq0trIXCSU5Q.jpeg" /></figure><p>Do your tests fail even with a little change of code? Do you mock heavily? Are you testing function calls and component state all the time? Well, you probably doing it wrong.</p><blockquote><em>We build spectacular apps, check</em><strong><em> </em></strong><a href="https://auriosoftware.com/"><strong><em>auriosoftware.com</em></strong></a></blockquote><p>I have read a lot of articles about how to test React components and most of the time I felt like there should be a better way. In this article, I would like to address some common issues with help of <a href="https://jestjs.io/">Jest</a> and <a href="https://github.com/airbnb/enzyme">Enzyme</a>.</p><p>So let&#39;s begin with the most important advice.</p><h3><strong>Test behavior, not implementation details!</strong></h3><p>Look at the example below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5ad1de20b8b258d16d70f8192e95ab7e/href">https://medium.com/media/5ad1de20b8b258d16d70f8192e95ab7e/href</a></iframe><p>At first, it seems ok. I have an email input and I want to test <em>“When I change the email input the new value will appear in my state”</em>.</p><p>The problem is that you are testing implementation details, specifically the internal component state. And when you couple your tests with implementation details, your tests become fragile.</p><p>Look at the property “<strong><em>email</em></strong>” in the state. Whenever you rename that property or refactor your component, <strong>your test will fail!</strong></p><p>If you are asking “But how the hell do I know whether this input works if I don&#39;t test that” let me show you that you actually don&#39;t need this test.</p><h4>Creating a feature</h4><p>Let&#39;s imagine we need a shiny new feature which is a simple subscription form where a user can write his email and subscribe to the news from our product.</p><p>Because I pretend to be a professional I am doing TDD so let me write our first failing test.</p><p>“<strong>When a valid email was filled and form was submitted, it should subscribe to the news with correct email</strong>”</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8107f5c2516161547911e1636072d0ea/href">https://medium.com/media/8107f5c2516161547911e1636072d0ea/href</a></iframe><p>If we fill the email input and click on the submit button, we expect that the <em>subscribe</em> function is called with the email from the input.</p><p><strong>We are testing behavior! Not the implementation.</strong></p><p>We run the test and it failed because we don&#39;t have any implementation yet. So, let&#39;s write enough production code to pass the test.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/756d9d0b84b7db6e922c27c2229621df/href">https://medium.com/media/756d9d0b84b7db6e922c27c2229621df/href</a></iframe><p>In order to make it pass we created the state object with “<strong><em>email</em></strong>” property and implemented the <strong><em>onChange</em></strong> handler on the email input. After that, we created the <strong><em>onSubmit</em></strong> handler on the submit button and called the subscribe function with the <strong><em>email</em></strong> from the state.</p><p>Let&#39;s run the test again. It passed.</p><p><strong>Our high-level use case forced us to write that code! </strong>These use cases are the component’s contract which you should test. We would not test the implementation details like the internal state of the component and how it changes because it is volatile.</p><p><strong>Conclusion. </strong>Avoid testing component state and don&#39;t dive to DOM in order to find some element you need to test (<em>ex: div &gt; foo &gt; input</em>) because whenever you change your DOM, your tests will fail. We want to depend on stable things, as in life so in software development.</p><h3>What is a UNIT TEST?</h3><p>This is another important topic because a lot of people are a little bit confused about what unit really is and this misunderstanding has a huge impact on your tests.</p><p>Let&#39;s try to figure it out by extending our previous example.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/14199f254b4d64db080b2cdedfd97449/href">https://medium.com/media/14199f254b4d64db080b2cdedfd97449/href</a></iframe><p>After some time our component got bigger and we encapsulated some logic into different components. We created a component for email input, submit button and for marketing content which contains some text and logo.</p><p>My question is<strong> how should we change the tests of Subscription component?</strong></p><p>The answer is simple, <strong>we will not change</strong> <strong>anything!</strong></p><p>In fact, our tests are still passing. We were moving, creating and changing things and our tests are still working properly because we did not couple our tests with implementation details!</p><p>You might be asking yourself.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/556/1*NaGJ_IL0wwMI0kvZE_I_Qw.jpeg" /></figure><p>Is this an integration test? The answer is no! Let&#39;s bring some definitions from Robert C. Martin.</p><blockquote><strong>Unit test. </strong>A test written by a programmer for the purpose of ensuring that the production code does what the programmer expects it to do.</blockquote><blockquote><strong>Integration Test.</strong> A test written by architects and/or technical leads for the purpose of ensuring that a sub-assembly of system components operates correctly. These are <em>plumbing</em> tests. <strong>They are <em>not</em> business rule tests</strong>. Their purpose is to confirm that the sub-assembly has been integrated and configured correctly.</blockquote><blockquote><strong>Micro-test.</strong> A unit test written at a very small scope. The purpose is to test a single function, or small grouping of functions.</blockquote><blockquote><strong>Functional Test</strong>: A unit test written at a larger scope, with appropriate mocks for slow components.</blockquote><p>Do you see a word <strong><em>class</em></strong> in the definition of a unit test?</p><p><strong>We could imagine a unit as a module</strong>.<strong> </strong>We want to test if we give the module input <em>a,</em> it should return output <em>b</em>. The module is a black box and we are testing only his public API.</p><p>A lot of people gets the concept of unit testing as a testing a class (component) in isolation. In order to test this class in isolation, you have to set strict boundaries around that class and mock all of its collaborators. But when you mock all of the collaborators, every time they change your tests have to change as well.</p><p>Look again on our previous test.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8107f5c2516161547911e1636072d0ea/href">https://medium.com/media/8107f5c2516161547911e1636072d0ea/href</a></iframe><p>We can consider our test as a<strong> functional test. </strong>This is not an integration test because:</p><ol><li>we are testing business rules,</li><li>we mocked our slow components, more specifically the <em>subscribe</em> call because the production implementation of this function would call probably some HTTP endpoint,</li><li>the test is at a larger scope because we are testing whole Subscription component including children presentational components in the hierarchy.</li></ol><p>This gave us power because we can even change libraries such as material design, bootstrap or whatever and our <strong>tests will be still passing</strong>, because they do not depend on their specific API.</p><h4>Bad example of Subscription component’s tests</h4><p>This is how the <em>Subscription</em> example would look like if you over specified your tests.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9a2938455856f84df82e452340edb46d/href">https://medium.com/media/9a2938455856f84df82e452340edb46d/href</a></iframe><p>We coupled implementation details like <em>MarketingContent</em>, <em>EmailInput</em>, and <em>SubmitForm </em>component. What if we change prop “onChange” to “handleChange”? What if we change the names of these components? What if we remove <em>MarketingContent</em> and move that logic to parent component?</p><p><strong>Our tests will fail!</strong></p><p>But that is not the only problem. Now we have to test all these components as well! And I ensure you that one day we will forget some test and all of these tests become useless because, at the end of the day, our code does not work because we forget to call some method in some child component in the hierarchy.</p><h4><strong>Summary</strong></h4><p>Testing is hard, don’t make it harder. Try to not over specify your tests and try to depend on stable things.<strong> </strong>Yeah, and it is much more fun when you are doing TDD.</p><h4>Some useful links.</h4><p>Test definitions from Robert C. Martin — <a href="https://blog.cleancoder.com/uncle-bob/2017/05/05/TestDefinitions.html">https://blog.cleancoder.com/uncle-bob/2017/05/05/TestDefinitions.html</a></p><p>TDD: Where Did It All Go Wrong — <a href="https://www.youtube.com/watch?v=EZ05e7EMOLM&amp;t=1574s">https://www.youtube.com/watch?v=EZ05e7EMOLM</a></p><p><a href="http://foobarbaz.club/">More articles on my blog <strong>foobarbaz.club</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9f090969cb6f" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/how-to-properly-test-react-components-9f090969cb6f">How to properly test React Components</a> was originally published in <a href="https://itnext.io/">ITNEXT</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 apply SOLID principles in React applications]]></title>
            <link>https://medium.com/@tomgold_48918/how-to-apply-solid-principles-in-react-applications-6c964091a982?source=rss-a5e68992a20b------2</link>
            <guid isPermaLink="false">https://medium.com/p/6c964091a982</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[solid]]></category>
            <dc:creator><![CDATA[Tomáš Gold]]></dc:creator>
            <pubDate>Tue, 16 Oct 2018 09:43:34 GMT</pubDate>
            <atom:updated>2019-07-07T15:12:39.599Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6b-fHNLJoBcSdMrPnAUvkw.png" /></figure><p>In this article, we are going to look at the SOLID principles and how to apply them in the React.</p><p>For the sake of simplicity, I will not provide the full implementation of some components. So let&#39;s begin.</p><h3><strong>Single Responsibility Principle</strong></h3><p>First is the Single responsibility principle. This principle tells us that <strong>module should have one and only one reason to change.</strong></p><p>Let’s imagine we are trying to build an application which displays users in a table.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/550ff2969d117242964bd88452987f34/href">https://medium.com/media/550ff2969d117242964bd88452987f34/href</a></iframe><p>We have a component which has a user list in the state. We are fetching users from some HTTP endpoint and each user is editable. This component violates the Single Responsibility Principle because <strong>it has more than 1 reason to change.</strong></p><p>I can see these reasons.</p><ol><li>Every time I want to change the header of application.</li><li>Every time I want to add a new component to the application (e.g. footer).</li><li>Every time I want to change the user fetching mechanism, for example, the address of endpoint or protocol.</li><li>Every time I want to change the user list table (e.g. column styling, etc…)</li></ol><p><strong>Solution. </strong>After you identify your reasons to change try to eliminate them by creating a suitable abstraction (component, function, …) for each reason.</p><p>Let&#39;s try to fix that problem. Lets go refactor the <strong>App</strong> component.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5c3fbbfb63636e21899f726e43596892/href">https://medium.com/media/5c3fbbfb63636e21899f726e43596892/href</a></iframe><p>Now, when we want to change the header we change the <strong>Header</strong> component and when we want to add a new component we change the <strong>App</strong> component. We solved problem 1 <em>(change the header of application</em>) and 2 <em>(add a new component to the application) </em>by moving that logic from the App component to the new components. Let&#39;s solve the problem 3 and 4.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/960e8c144ec22480b938b6d61d1237c5/href">https://medium.com/media/960e8c144ec22480b938b6d61d1237c5/href</a></iframe><p>This is our new container component <strong>UserList. </strong>We solved problem 3 <strong><em>(</em></strong><em>change the user fetching mechanism) </em>by creating props functions <strong><em>fetchUser</em></strong> and <strong><em>saveUser. </em></strong>So when we want to change the HTTP endpoint we go to the function <em>(save/fetch)User </em>and change that there.</p><p>The last problem 4 <em>(change the user list table)</em> was resolved by creating a simple presentation component <strong>UserTable</strong> which encapsulated the HTML and styling of the user table.</p><figure><a href="https://blog.usejournal.com/meet-journal-d222fce8db1d"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PMBwoU5bWkso8M2A1ocS9Q.png" /></a></figure><h3>Open Closed Principle</h3><p>This principle states “<em>software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification</em>”.</p><p>If you look at the <strong>UserList</strong> component above you can notice that if we want to display users in a different format, we have to modify the UserList’s <strong><em>render</em></strong> method. This is a violation of this principle.</p><p>We can obey this principle by using <a href="https://reactjs.org/docs/composition-vs-inheritance.html">Component Composition</a>.</p><p>Look at the refactored UserList component below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/26c470e3aef360c1aa12913715ad751d/href">https://medium.com/media/26c470e3aef360c1aa12913715ad751d/href</a></iframe><p>We modified the <strong>UserList</strong> component in a way that it is open for extension, because it renders its children and therefore it is easy to extend its behavior. It is closed for modification because all necessary changes will be done in different components. We can even deploy this component independently.</p><p>Lets look how would we display users in a list by using our new component.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7cf9a3127539f82590766e212094d509/href">https://medium.com/media/7cf9a3127539f82590766e212094d509/href</a></iframe><p>We extended the <strong>UserList</strong> behavior by creating a new component which knows how to display users. We can even fetch new detailed information about each user in this new component without even touching <strong>UserList</strong> component and that was the goal.</p><h3>Liskov Substitution Principle</h3><blockquote>“objects in a program should be replaceable with instances of their subtypes without altering the correctness of that program.”</blockquote><p>Or if you don’t mind more accurate description.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*ToXLL1aet69THe2qxuwCmQ.jpeg" /></figure><p>Look at the example below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d4e26fbee927151caecf89b98a6e9439/href">https://medium.com/media/d4e26fbee927151caecf89b98a6e9439/href</a></iframe><p>We have a class <strong><em>User</em></strong> which accept roles in the constructor. Then, we created an <strong><em>AdminUser</em></strong> class which is the <strong><em>User</em></strong> derivative.</p><p>After that, we have created a simple function <strong><em>showUserRoles </em></strong>which accept <strong><em>user</em></strong> as a parameter and prints all of the user’s roles to the console.</p><p>But after we called the <strong><em>showUserRoles</em></strong> function with ordinaryUser and adminUser instances, it crashed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/392/1*eZw2mM1ltNdxDOnbaBEHCg.png" /></figure><p>And why? The <strong><em>AdminUser </em></strong>looks like the <strong><em>User.</em> </strong>It definitely “quacks” like the User because it has the same methods. The problem was with the “batteries”. Because, when creating the admin user, we created an object of roles instead of an array.</p><p>We violated the Liskov Substitution Principle because the <strong><em>showUserRoles</em></strong> <strong>function should work correctly with the User and its derivatives!</strong></p><p>Fix is simple, we will just create an array of roles instead of an object.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6069e129c42498fe439e230f89087e6c/href">https://medium.com/media/6069e129c42498fe439e230f89087e6c/href</a></iframe><h3>Interface Segregation Principle</h3><p>This principle tells us that<strong> we should not depend on things we don&#39;t need.</strong></p><p>This principle applies especially on static types languages because your dependencies are explicitly defined by interfaces.</p><p>Let&#39;s bring an example.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0e4115e79452dd44571937f31b245677/href">https://medium.com/media/0e4115e79452dd44571937f31b245677/href</a></iframe><p><strong>UserTable</strong> component renders <strong>UserRow</strong> component while passing whole user object to its props. When you look at the <strong>UserRow</strong> component, it depends on the whole user but only cares about user’s <strong><em>id</em></strong> and <strong><em>name</em></strong>.</p><p>When you would write a test for this component in Typescript or Flow, you have to mock the whole user because otherwise, your compiler will fail.</p><p>At first, it does not seem a problem if you are using vanilla Javascript, but someday, you will add Typescript to your code base and suddenly it will break all your tests because you would have to assign all properties from interfaces even if you are using only half of them.</p><p>But still, it is more descriptive this way.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c0faccbcbd681de33b35a9864bde1d82/href">https://medium.com/media/c0faccbcbd681de33b35a9864bde1d82/href</a></iframe><p>Keep in mind that this principle does not apply only on prop-types.</p><h3>Dependency Inversion Principle</h3><p>This principle tells us that <strong>we should depend upon abstractions, not concretions.</strong></p><p>Let&#39;s look at the example.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c3ed6be80fc9a882c6e1fcccf5ab60f3/href">https://medium.com/media/c3ed6be80fc9a882c6e1fcccf5ab60f3/href</a></iframe><p>If you look at this code you will see that component <strong>App</strong> depends on the concretion, more specifically global <strong><em>fetch</em></strong>. In UML world this relation would look like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/131/1*6frfqdVPBkMklxpQgJvYhg.png" /></figure><p>A high-level module should not depend on low-level details, both should depend on abstraction.</p><p>The App should not know how to fetch users. In order to fix that problem, we have to inverse the dependencies between <strong>App</strong> component and <strong>fetch</strong> so the UML diagram will look like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/131/1*lFb-wk_nA8_bEYrJ2lDCSA.png" /></figure><p>And the implementation.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/410f7ad18aa68282453b57621f2ff4e4/href">https://medium.com/media/410f7ad18aa68282453b57621f2ff4e4/href</a></iframe><p>We can say that App is loosely coupled, because it has no knowledge whether we are using HTTP, SOAP or even powerpoint protocol. It does not care.</p><p>It gives us power because we can easily change the fetching method and the <strong>App component will not change a bit!</strong></p><p>And testing is really simple, we can easily mock these fetching functions.</p><h3>Summary</h3><p>Invest your time to create a better code, your colleagues and your future self will thank you for that.</p><blockquote><em>We build spectacular apps, check</em><strong><em> </em></strong><a href="https://auriosoftware.com/"><strong><em>auriosoftware.com</em></strong></a></blockquote><p><a href="https://twitter.com/foobarbazgold">Stay in touch with me on Twitter</a>.</p><figure><a href="https://usejournal.com/?utm_source=medium.com&amp;utm_medium=noteworthy_blog&amp;utm_campaign=guest_post_image"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f2IVAl0TbsfES9cFGYr40g.png" /></a></figure><p>📝 Read this story later in <a href="https://usejournal.com/?utm_source=medium.com&amp;utm_medium=noteworthy_blog&amp;utm_campaign=guest_post_read_later_text">Journal</a>.</p><p>🗞 Wake up every Sunday morning to the week’s most noteworthy Tech stories, opinions, and news waiting in your inbox: <a href="https://usejournal.com/newsletter/?utm_source=medium.com&amp;utm_medium=noteworthy_blog&amp;utm_campaign=guest_post_text">Get the noteworthy newsletter &gt;</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6c964091a982" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>