<?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 Gilad Hoshmand on Medium]]></title>
        <description><![CDATA[Stories by Gilad Hoshmand on Medium]]></description>
        <link>https://medium.com/@giladhoshmand?source=rss-e9a99afa1999------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*x9oJLaXkbdRmo12CWdrQnA.jpeg</url>
            <title>Stories by Gilad Hoshmand on Medium</title>
            <link>https://medium.com/@giladhoshmand?source=rss-e9a99afa1999------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 17:23:48 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@giladhoshmand/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[The curios case of the always catching coder]]></title>
            <link>https://medium.com/@giladhoshmand/the-curios-case-of-the-always-catching-coder-760090c45442?source=rss-e9a99afa1999------2</link>
            <guid isPermaLink="false">https://medium.com/p/760090c45442</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[application-lifecycle]]></category>
            <category><![CDATA[error-handling]]></category>
            <dc:creator><![CDATA[Gilad Hoshmand]]></dc:creator>
            <pubDate>Fri, 05 Jan 2024 13:30:38 GMT</pubDate>
            <atom:updated>2025-04-21T14:37:23.748Z</atom:updated>
            <content:encoded><![CDATA[<h3>Error handling: The curios case of the ever catching coder</h3><p>I recently opened an old project and got nostalgic about some code I wrote. I started to look around and noticed it had a terrible ratio between business logic code and all other code, especially error handling code. <br>I started poking around and..</p><blockquote>..as I followed the code into each rabbit hole I started to get that itch — I couldn’t resist but refactor and clean up.</blockquote><blockquote>As I got deeper and deeper in I started to feel uncomfortable — like I could never find my way out of this adventure — a thought crept in — if I don’t discard my changes this code could explode in my face and I’ll never be able to make it work again.</blockquote><figure><img alt="A coding rabbit hole" src="https://cdn-images-1.medium.com/max/1024/1*34aKjD2K2K-rVD2Vr47TVw.jpeg" /><figcaption>Join me on this journey</figcaption></figure><h3>The oh-no-do-not-explode sentiment</h3><p>It lead me to ask myself — <strong>Why are we as developers so afraid of an error? </strong>Should we really defend against all issues at any cost?<br>What actually happens when an error is thrown?</p><p>If you’ve ever encountered “bullet proof”, “defensive”, “never-fail” code you could not miss it — it’s full of just-in-case redundant checks, validations, ifs and try-catch syntax. <br>It’s usually bloated, unreadable and repetitive. Code smells all over.</p><p>Let’s get to some examples, imagine we have the following modules:</p><pre>// module that exposes a method that does something<br>import { task } from &#39;./some-module.js&#39;;<br><br>export const doSomething = (arg1, log) =&gt; {<br> try{<br>   // Possibly do some logic, processing and logging<br>   return task(arg1)<br> } catch (e) {<br>   log({e}, &#39;some message with useful info about the error&#39;)<br>   return { error: &#39;some error message&#39; }<br> }<br>}<br><br>// Another different module<br>export const task = (arg1) =&gt; {<br> try{<br>   return doSomeTaskWithArg(agr1); // this does some logic<br> } catch (e) {<br>   return { err: e }<br> }<br>}</pre><p>Code is ugly but fine I guess.. I mean 10- lines of code for what should be 2 lines.. anyway some problems can be seen right away:</p><ul><li>task method <strong>never</strong> throws — so why and what is doSomething catching?</li><li>Each method returns the caught error “gracefully” but in a custom and unexpected format</li></ul><p>I call this <strong>over-catching</strong> and it’s where programmers are so reluctant to not let anything “bad” happen they just wrap any code they write thinking — “my code does x and if x fails I will gracefully return y”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/1*M1iqkEYQ_4WfL0T9MgkamQ.jpeg" /><figcaption>The over catch is real</figcaption></figure><h3>Module consumer</h3><p>Scenario: You’ve been asked to use this module for a task and decided to join in on the defensive coding style thinking:</p><blockquote>Well if everybody before me wrote super defensive code I won’t be the one to break this app in production!</blockquote><pre>const unexpectedResult = doSomething(someArg);<br>if(unexpectedResult.error){ // cover this just in case right?<br> // do the resulting logic<br>}<br>if(unexpectedResult.err){<br> // so dome other logic that handles the other throw catch implications<br>}<br>// now do what I really wanted to do with <br>// unexpectedresult.doSomethingReturnValue</pre><p>Your code works, you’re content with the cover-all-cases-never-fail approach and you’re filled with confidence nothing can explode. Great.</p><p>The problem is the <strong>code looks disgusting</strong>, it’s super bloated, problems just keep building up and in practice only 3–5 lines are the actual application logic needed. <br>Also — <strong>tests now require branching</strong> to cover different scenarios.</p><h4>Think about the poor consumer</h4><p>What if the consumer wants to write it’s own error handling logic? <br>You have now made that so much more complex as they must follow your custom error output (that will possibly change or be extended overtime?).<br>Also — most importantly — you obscured any information on what the hell happened.</p><p>And what is the deal with custom errors and return values??? <br>All I have to say is:</p><blockquote>Congratulations!</blockquote><blockquote>You have now forced the module consumer to go read all the code it is consuming</blockquote><p>So.. should they re-implement/fork your method to a non-catching one? <br>Then also copy the tests and change to fit the throwing nature of the copied code?<br>I’m just getting started and this is already terrible.</p><h3>TL;DR rules of thumb</h3><p>First things first the penny must drop:</p><blockquote>try-catch is not a safety mechanism — it is a part of your business logic!!!</blockquote><p>Everyone OK?</p><h4>Rule of thumb is:</h4><p>If you know what to do with the error — handle it<br>If you are at the top most level — handle it<br>If you really (but I mean really) know what you’re doing — handle it<br>Else — throw!</p><p>All together now:</p><pre>// module that exposes a method that does something<br>import { task } from &#39;./some-module.js&#39;;<br>export const doSomething = (arg1, log) =&gt; {<br> // Possibly do some logic, processing, logging etc.<br> return task(arg1)<br>}<br>// some-module <br>export const task = (arg1) =&gt; {<br> // Possibly do some logic, processing, logging etc.<br> return doSomeTaskWithArg(agr1); <br>}<br><br>// some code in another module that knows what it wants to do in case of error<br>try{<br> const result = doSomething(someArg);<br>} catch (e) {<br> // HERE: handle the thrown error because <br> // you know what you want to happen in case of failure<br>}<br><br>// some code in some other module that does NOT know what to do with an error<br>const result = doSomething(someArg);<br>// don&#39;t catch</pre><h3>Stop being graceful — Seriously, stop it.</h3><p>Is there some book I didn’t read that says you should catch errors in order to write good code?<br>Is there some mannerism that I’m not aware of that frowns upon not handling a thrown error?</p><h4>STOP:</h4><ul><li>Nobody needs to read method code in order to understand what you’re returning on error</li><li>Obscuring what had happened</li><li>Catching because you‘re afraid</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=760090c45442" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How GPT-4 refactors deprecated code for me]]></title>
            <link>https://medium.com/@giladhoshmand/refactoring-deprecated-code-using-gpt-4-99c0c4f2b9d1?source=rss-e9a99afa1999------2</link>
            <guid isPermaLink="false">https://medium.com/p/99c0c4f2b9d1</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[gpt-4]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Gilad Hoshmand]]></dc:creator>
            <pubDate>Wed, 02 Aug 2023 15:05:50 GMT</pubDate>
            <atom:updated>2023-08-15T14:06:09.060Z</atom:updated>
            <content:encoded><![CDATA[<p>Following my attempts to <a href="https://medium.com/@giladhoshmand/how-gpt-4-helps-me-refactor-code-12a728266c03">refactor old code</a>. I went further into the rabbit hole to see if I can use GPT-4 to specifically refactor deprecated code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/0*ZaLp9l-DQieH_ybp.jpg" /><figcaption>I wander what that feels like.. stay tuned</figcaption></figure><h3>Refactoring deprecated code</h3><p>I quickly searched the code base for some known deprecated methods usage and asked GPT-4 for help:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/758/1*UDjAPILlElwdY3DGvhqhSw.png" /><figcaption>“Can you have update deprecated code” don’t know wtf happened here..</figcaption></figure><p>This is a really good use case — small amount of scoped code that does 1 specific thing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/677/0*63YidhD9cWAHNN58.jpg" /><figcaption>That’s all I have to say</figcaption></figure><p>Onto bigger fish — I remembered an old project that always throws deprecation warnings. The following file is a great example; I simplified it and added some comments for readability.</p><pre>from pymongo import MongoClient, ASCENDING<br>class MongoDBHandler:<br>    def __init__(self, host=&quot;localhost&quot;, port=27017, db_name=&quot;test_db&quot;):<br>        # MongoClient is not deprecated, <br>        # but passing host and port as separate arguments is.<br>        self.client = MongoClient(host, port)<br>        self.db = self.client[db_name]<br>    def insert_document(self, collection_name, document):<br>        # insert is deprecated in favor of insert_one or insert_many.<br>        return self.db[collection_name].insert(document)<br>    def find_document(self, collection_name, query={}):<br>        # find_one is not deprecated<br>        # but passing an empty dict as a query is not recommended.<br>        return self.db[collection_name].find_one(query)<br>    def create_index(self, collection_name, fields):<br>        # ensure_index is deprecated in favor of create_index.<br>        return self.db[collection_name].ensure_index(fields, ASCENDING)</pre><p>GPT to the rescue (again)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/752/1*hLgkUpE3D22wpAVOr1WzrQ.png" /></figure><p>I questioned the implementation of find_document and got a lesson:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/746/1*t1kI8fJHtVAtIVDP0Ns7pw.png" /></figure><p>So it turns out not only deprecated methods were updated but also a known bad practice was taken care of — but did I want that?</p><p>This is exactly the place to stop and say — whether some AI or LLM produced 99% of the code or whether you just asked for some pointer —</p><h4>Own the final code, own the implications of any change to the code base, you are responsible for it and no one else. Code that was refactored or produced is to be used as assistance but the code committed is signed by you and you alone. There is no blaming a machine after production exploded because of generated code you did not understand or test well enough.</h4><h4>Limitations</h4><p>All was going smoothly so I thought we’ll go ahead and upgrade the pymongo package:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/582/1*VMqYMCjRGIUrOK1hLoaLeA.png" /><figcaption>ah-oh</figcaption></figure><p>This is a limitation you should be aware of — if you are wanting or required to use the latest &amp; greatest in your code — bad news. The training data stops at a certain point in time and you should always remember that when using these tools.</p><h4>Tips &amp; Takeaways</h4><ul><li>You can use AI aid for different scenarios to your liking and as you see fit — it’s not a “one size fits all” situation.</li><li>Own the end result</li><li>Tests are your best friend when refactoring — check out <a href="https://medium.com/@giladhoshmand/how-gpt-4-writes-tests-for-me-775194008ec5">How GPT-4 writes tests for me</a></li><li>Don’t put any confidential/IP code into a black box on the web</li><li>Remember this — messy input = messy output.<br>The input you supply should have all the information needed for refactoring — nothing less, nothing more.</li><li>Large Language Models (LLM) are trained on a set of data which is naturally finite and up to a certain point in time.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=99c0c4f2b9d1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How GPT-4 helps me refactor new code]]></title>
            <link>https://medium.com/@giladhoshmand/how-gpt-4-helps-me-refactor-new-code-e0b58dd559f0?source=rss-e9a99afa1999------2</link>
            <guid isPermaLink="false">https://medium.com/p/e0b58dd559f0</guid>
            <category><![CDATA[gpt-4]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Gilad Hoshmand]]></dc:creator>
            <pubDate>Mon, 31 Jul 2023 17:25:29 GMT</pubDate>
            <atom:updated>2023-07-31T17:25:29.085Z</atom:updated>
            <content:encoded><![CDATA[<p>Following my last story <a href="https://medium.com/@giladhoshmand/how-gpt-4-helps-me-refactor-code-12a728266c03">How GPT-4 helps me refactor code</a> — this time <strong>refactoring new code</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/696/0*abGUWQ41jvx1GE6h" /><figcaption>Use GPT-4 to write new code</figcaption></figure><h3>Writing New Code</h3><p>This is our use case — you write new code, you’re in the zone, you know what’s going on, you tested, you wrote tests — it’s working and you’re about to commit but wait!</p><p>Wouldn’t it be great if you could just get a second set of eyes to look at your code? <br>Maybe you’re fatigued or focused on the big picture — it would be nice to have someone/thing go over it for you — just use GPT to check it with a simple prompt.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/660/0*SP8eO8gf4wueoRdg" /><figcaption>Code together with GPT-4</figcaption></figure><p>First example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/964/1*vuDjUBBbPZj5v9smQGHwlw.png" /><figcaption>Top answer from the top rated JavaScript question in SO</figcaption></figure><p>Now, in this case, the code is shorter, cleaner, much less prone to annoying issues if someone tries to modify it for some reason. It’s an easy call — I’ll use it.</p><p>Next up something a little more complex — is a linked list a palindrome?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/871/1*gTHGRKlGxofN5lHFV8pZIw.png" /><figcaption>Starting off with stroking the developer ego — big gg by ChatGPT</figcaption></figure><p>Solution itself has some nice pros — cleaner, shorter and more readable!<br>Minor detail: notice how var was not changed to const as some linters would suggest. GPT doesn’t know what you intend to do with this variable — it extracts what it can from your input — in this case — it’s a <strong>fact</strong> that isPalindrome is a var.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*P1FmPNUJzUJM5fErpjRocA.png" /><figcaption>GPT-4 added explanation</figcaption></figure><p>It’s worth mentioning the explanation produced at the end and noting: the efficiency tip in the second sentence could be crucial — <strong>own your solution, know wtf you’re doing</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/0*iDJIWwXc23tEx-J2.gif" /><figcaption>Easy win</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e0b58dd559f0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to refactor code with Truth Tables]]></title>
            <link>https://medium.com/@giladhoshmand/how-to-refactor-code-with-truth-tables-91d45f4927de?source=rss-e9a99afa1999------2</link>
            <guid isPermaLink="false">https://medium.com/p/91d45f4927de</guid>
            <category><![CDATA[refactoring]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Gilad Hoshmand]]></dc:creator>
            <pubDate>Mon, 10 Jul 2023 18:54:53 GMT</pubDate>
            <atom:updated>2026-03-05T11:35:34.158Z</atom:updated>
            <content:encoded><![CDATA[<p>As usual — this not an intro article. <br>You should know:</p><ul><li>What are truth tables</li><li>Logical expressions</li><li>Basic unit testing ideas</li><li>Why refactoring is painful</li><li>What you’re doing with your life (I said “should know”…)</li></ul><h3>Option 1:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*lYz7uJ0Eepm1jUi0.jpg" /><figcaption>TFW</figcaption></figure><h3>Option 2</h3><p>Accept the TRUTH</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*eFzFP6_RcSA8Jyw4.jpg" /><figcaption>Don’t be these people</figcaption></figure><h3>Follow step by step guide:</h3><ol><li>We map all the business logic into a logical expressions.</li><li>Make a truth table covering all scenarios.</li><li>For each row of values — substitute values and add in the result. <br><strong>Follow the code blindly -</strong> no opinions, judgements or “I know what happens here” — switch values and debug like a robot please.</li><li>The full table is your truth — when you refactor — you must keep it logically equal to what you started with.<br>Extract minimal logical expression from Truth Table.</li><li>Make sure all these cases are covered by tests.<br>(Optional) Add ending logical expression to docs/comment so that no one has to do this again.</li><li>Refactor to match the resulting logical expression from our Truth Table</li><li>Run tests</li><li>Be happy</li></ol><p>This is our example:</p><pre>function isSomething(a, b){<br>  if(a)<br>    if(b)<br>      return a !== b;<br>  else{<br>    if(!b)<br>      return true;<br>  }<br>  return true;<br>}</pre><p><strong>Step 1:</strong> going over the code we can see 3 expressions that effect the business logic:</p><ul><li>a (exists)</li><li>b (exists)</li><li>a !== b</li></ul><p><strong>Step 2:</strong> Making the truth table to cover all cases</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/243/1*M1nf163rjwOqLhgfClXn7Q.png" /></figure><p>0 represents false and 1 represents true.</p><p>Step 3: For each row of values — substitute values and add in the result.</p><p>Let’s do the first one: if(a) === false , if(b) === false , a !== b is false. <br>First if is false so we jump to the else clause, !b is true so we return true.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/243/1*ov0wf_DDIEGsFNUDQtgy1Q.png" /><figcaption>This is our updated table</figcaption></figure><p>Another run to get the hang of it we will run with values — 1 1 0 — meaning: if(a) === true , if(b) === true , a !== b is false.</p><p>The first 2 if statements are true and a !== b is false so the return value is false.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/241/1*wxAmMA-Uq_exnpRlUT6RBw.png" /><figcaption>Updated truth table</figcaption></figure><p>I did the rest of them, the end result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/125/1*fUYNKLnE5C2fllns7-sSUA.png" /><figcaption>Simplified &amp; full</figcaption></figure><p>We’ll try to make a simple-as-possible equation that reflects the table:</p><p>!(a exists &amp;&amp; b exists &amp;&amp; a === b)</p><p>Which is equivalent to: !(a exists) || !(b exists) || a !== b</p><p>Explanation: <br>The first expression is the only one that results in false and I added a NOT operator to it.<br>Equivalence explanation: it’s just a simple logical expression rules when opening the brackets with the NOT operator before them.</p><p>Now we can refactor to:</p><pre>function isSomething(a, b){<br>  return !a || !b || a !== b;<br>}<br><br>// OR equivalent expression (with different coding style)<br>const isSomething = (a, b) =&gt; !(a &amp;&amp; b &amp;&amp; a === b);</pre><p>Beautiful right?</p><h3>Tests — READ THIS</h3><p>At this stage you run your tests again to make sure you didn’t break anything. This gives so much confidence in the refactor since you’ve logically mapped all cases, covered them with tests (that should pass of course) and you can confidently know that you didn’t break anything.</p><h3>Next up</h3><p>Next example is from Stack Overflow, all of it including comments are originals:</p><pre>function validatePassword(errorMessage)<br>{<br>   const password = document.getElementById(&quot;password&quot;);<br>   const confirm_password = document.getElementById(&quot;password_confirm&quot;);<br><br>   if(password.value)<br>   {<br>      // Check if confirm_password matches<br>      if(password.value != confirm_password.value)<br>      {<br>         return false;<br>      }<br>   }<br>   else<br>   {<br>      // If password is empty but confirm password is not<br>      if(confirm_password.value)<br>      {<br>         return false;<br>      }<br>   }<br>   return true;<br>}</pre><p>We’re not going into best practices and we’ll never know what happened here but we can try to dissect the code a little. Right from the start we can notice (maybe with the aid of our IDE):</p><ol><li>errorMessage is not even used</li><li>true is returned as default.</li><li>Technique is questionable</li></ol><p>After steps 1–4 we get:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*Ff-8HTf1sKPFnXhuuKdtrg.png" /><figcaption>Same technique as before</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/577/0*iRdta8bl6FSsQK2-.jpg" /><figcaption>Not sure…</figcaption></figure><p>We found a bug! That’s great! Or.. if both empty password values then return value should be true? <br>This is where tests will save the day!<br>If they are written look to them for the intended logic, if not — well.. someone kind of screwed up and you’ll need to make a decision.. you either “fix” this or write tests to cement it as intended behavior.</p><p>For example sake — we’ll treat it as a bug.</p><p>Finish up <em>Step 4: Extract minimal logical expression from Truth Table<br></em>password.value &amp;&amp; confirm_password.value &amp;&amp; passwords match</p><p>We are now at <em>Step 5: Make sure all these cases are covered by tests </em>so we have a chance to add tests to cover these bad cases. Do this right away.</p><p>Step 6— expression from Step 4 easily translates into:</p><pre>function validatePassword(_errorMessage) {<br>   const password = document.getElementById(&quot;password&quot;);<br>   const confirm_password = document.getElementById(&quot;password_confirm&quot;);<br>   return password.value &amp;&amp; confirm_password.value &amp;&amp; password.value == confirm_password.value;<br>}</pre><p>Run tests to make sure nothing broke.</p><p>We’re not here for a coding lesson but while you’re empowered with confidence by the truth table and the tests coverage — you can cleanup and update technique to more modern style and practice. <br>Things like:</p><ul><li>== equality may be a mistake here</li><li>errorMessage still not used (I changed the name to reflect that)</li><li>Use const instead of var and other things</li></ul><h3>Input validation</h3><p>There are different contexts for using truth tables — let’s talk about validation and (non app logic) bugs.</p><p>We map method input expressions(nothing too interesting in this case) and any other value that we rely on. In the last example these are 2 HTML elements:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/709/1*XCpBhyNt8U-9183fP0Yzog.png" /><figcaption>Steps 1–4</figcaption></figure><p>In the example above some document.getElementById calls may result in null being returned. This is not handled by the code. Again — we look to our tests to find out if this is intended behavior. If one of the HTML elements doesn’t exist — the method will throw — is this desirable? Is this expected?</p><blockquote>I can’t make these decisions for you, it depends on the code but after creating this truth table and realizing these possible bugs you must add tests that cement this decision/logic so that it’s not coincidental.</blockquote><h3>To sum up the article — some of the things truth tables can help you with:</h3><ul><li>Refactor old code</li><li>Map all test cases</li><li>Find bugs</li><li><strong>ACCEPT THE TRUTH</strong></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=91d45f4927de" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How GPT-4 helps me refactor code]]></title>
            <link>https://medium.com/@giladhoshmand/how-gpt-4-helps-me-refactor-code-12a728266c03?source=rss-e9a99afa1999------2</link>
            <guid isPermaLink="false">https://medium.com/p/12a728266c03</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[chatgpt]]></category>
            <category><![CDATA[gpt-4]]></category>
            <category><![CDATA[refactoring]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Gilad Hoshmand]]></dc:creator>
            <pubDate>Thu, 08 Jun 2023 09:32:24 GMT</pubDate>
            <atom:updated>2023-07-30T17:38:13.654Z</atom:updated>
            <content:encoded><![CDATA[<h3>How GPT-4 helps me refactor old code</h3><p>Following my last story <a href="https://medium.com/@giladhoshmand/how-gpt-4-writes-tests-for-me-775194008ec5">How ChatGPT writes tests for me</a> — let’s see some more practical use<strong> </strong>for GPT-4, this time —<strong> refactoring old code</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/0*PdfUqVhHliWNqWDR.jpg" /><figcaption>Let’s dive deeper into GPT-4 capabilities</figcaption></figure><h3>Refactoring</h3><p>Refactoring techniques, tools &amp; methodologies are a whole domain — I’m not going to attempt to explain or describe this world. If you are needing an intro I do recommend finding solid, thorough reads about it.<br>I once took a very interesting course in university about “Proving Code Correctness” which in part elaborated excellently on different refactoring practices.</p><p>Today I show how GPT-4 can be a great assistance in different refactoring scenarios.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/503/0*Y86cFJoCa9eqhaAJ.jpg" /></figure><h3>Refactoring existing code</h3><p>Scenario: you need to refactor/modify some code that was written years ago by someone who’s not around anymore, things start off nicely, you reduce number of lines, cleanup, you’re happy. <br>Then as you gain some confidence — things start to break, tests appear flaky, you start to lose your mind. Next you devise a plan on how to sell the <em>Let’s throw this code in the garbage</em> option.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1015/0*GDcVcbHXmWXpsjTv.png" /><figcaption>It’s definitely one of these</figcaption></figure><p>Secret option #3: Refactor with AI at your side — how would I have loved to have this tool in previous projects I worked on!</p><p>Note: Tests are a must for this scenario — make sure they exist and are up to date covering all code branches.</p><p>Check out the example:</p><blockquote>ME: simplify and add j-doc to the following code</blockquote><pre>checkPermission: function (check, item, user) {<br>    var ans;<br>    var access = check.permissions.filter(function (permission) {<br>      return compareShareUser(permission.user, user.id);<br>    });<br>    if (access &amp;&amp; access.length &gt; 0) {<br>      if (!(access[0].exclude &amp;&amp; access[0].exclude.indexOf(item._id.toString()) &gt;= 0)) {<br>        ans = check;<br>      }<br>    }<br>    return ans;<br>  }</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/822/1*K-HbVG8UUVuJIpyblXKz2g.png" /></figure><p>Again — the subtleties (ie. let vs. const) &amp; style are up to you but this is much much better. The J Docs are so clear! It interpreted the terrible names and explained what actually are in simple words.</p><p>At this point you don’t even have to commit the code but you can easily understand it without hours spent reading &amp; debugging the pile of garbage.</p><p>It’s not even such terrible code; hold your breath for the next example:</p><pre>// don&#39;t even try to read this<br>const checkPermissions =  function (req, item, originalItem, companyId) {<br>    return new RSVP.Promise(async function (resolve, reject) {<br>      let checkIfItemIncluded = () =&gt; {<br>        let tempItem = originalItem || item;<br>        if (tempItem &amp;&amp; tempItem.type &amp;&amp; tempItem.type.startsWith(&quot;typeA&quot;)) {<br>          CollectionA.aggregate()<br>            .match({ _id: originalItem._id })<br>            .graphLookup({<br>              from: &quot;items&quot;,<br>              startWith: &quot;$_id&quot;,<br>              connectFromField: &quot;_id&quot;,<br>              connectToField: &quot;children&quot;,<br>              as: &quot;parents&quot;<br>            })<br>            .then((originalItemWithParents) =&gt; {<br>              let ancestors = originalItemWithParents[0].parents.map((p) =&gt; p._id);<br>              ancestors.push(originalItem._id);<br>              CollectionA.findOne({<br>                permissions: {<br>                  $elemMatch: {<br>                    user: req.auth.data.id,<br>                    isRoot: true,<br>                    &quot;options.includeItems&quot;: { $in: ancestors },<br>                  },<br>                },<br>              })<br>                .select(&quot;_id&quot;)<br>                .then((found) =&gt; {<br>                  if (found) {<br>                    resolve(true);<br>                  } else {<br>                    resolve(false);<br>                  }<br>                }, reject);<br>            }, reject);<br>        } else {<br>          resolve(false);<br>        }<br>      };<br>      let checkSecondary = () =&gt; {<br>        CollectionA.findOne({ children: { $in: [item.id || item._id] } })<br>          .select(&quot;permissions&quot;)<br>          .populate(&quot;permissions&quot;)<br>          .lean()<br>          .exec(function (err, parent) {<br>            if (err) {<br>              reject(err);<br>            } else {<br>              if (parent) {<br>                checkPermissions(req, parent, originalItem || item, companyId).then(resolve, reject);<br>              } else {<br>                checkIfItemIncluded();<br>              }<br>            }<br>          });<br>      };<br>      if (!req.auth || !req.auth.data || !req.auth.data.id || !item || (item &amp;&amp; !item.permissions)) {<br>        return resolve(false);<br>      } else {<br>        if (!companyId) {<br>          ({ companyId } = await findCompany(item));<br>        }<br>        const ans = await isCompany({ userId: req.auth.data.id, companyId });<br>        if (!ans) {<br>          console.log(`Permission DENIED. user dont belong to company ${companyId}`);<br>          return resolve(false);<br>        }<br>        findUser(req.auth.data.id)<br>          .then((user) =&gt; {<br>            var access = item.permissions.filter(function (share) {<br>              return comparePermissions(share.user, req.auth.data.id);<br>            });<br>            if (access &amp;&amp; access.length &gt; 0) {<br>              if (<br>                access[0].exclude &amp;&amp;<br>                access[0].exclude.indexOf((originalItem || item)._id.toString()) &gt;= 0<br>              ) {<br>                return resolve(false);<br>              } else {<br>                return resolve(true);<br>              }<br>            } else {<br>              if (user &amp;&amp; user.roles &amp;&amp; user.roles.indexOf(&quot;all&quot;) &gt;= 0) {<br>                User.findOne({<br>                  _id: { $in: item.permissions.map((s) =&gt; s.user._id) },<br>                  supportAccess: { $gt: new Date().addDays(-1) },<br>                })<br>                  .then((auth) =&gt; {<br>                    if (auth) {<br>                      resolve(true);<br>                    } else {<br>                      checkSecondary();<br>                    }<br>                  })<br>                  .catch(reject);<br>              } else {<br>                checkSecondary();<br>              }<br>            }<br>          })<br>          .catch(reject);<br>      }<br>    });<br>  }</pre><p>This code is unreadable and has everything I despise about old patchy code — callback hell, bad naming, too many lines, too many things done, huge methods within methods, mixed layers — it’s a mess.</p><p>If you write code like this — I’ve no words for you — you’re hopeless.<br>If you’ve been a victim of such code read on for help.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/250/0*D5oGy4tcd1NsKLap.jpg" /><figcaption>Fuck This Guy</figcaption></figure><p>GPT-4 to the rescue!</p><pre>/**<br> * Checks if an item is included in a collection.<br> * @param {object} req - The request object.<br> * @param {object} item - The item to be checked.<br> * @param {object} originalItem - The original item.<br> * @returns {Promise} - Resolves to boolean.<br> */<br>async function checkItemInclusion(tempItem, originalItem) {<br>  if (tempItem?.type?.startsWith(&quot;typeA&quot;)) {<br>      const originalItemWithParents = await CollectionA.aggregate()<br>          .match({ _id: originalItem._id })<br>          .graphLookup({<br>              from: &quot;items&quot;,<br>              startWith: &quot;$_id&quot;,<br>              connectFromField: &quot;_id&quot;,<br>              connectToField: &quot;children&quot;,<br>              as: &quot;parents&quot;,<br>          });<br>          let ancestors = originalItemWithParents[0].parents.map((p) =&gt; p._id);<br>      ancestors.push(originalItem._id);<br>      const found = await CollectionA.findOne({<br>          permissions: {<br>              $elemMatch: {<br>                  user: req.auth.data.id,<br>                  isRoot: true,<br>                  &quot;options.includeItems&quot;: { $in: ancestors },<br>              },<br>          },<br>      }).select(&quot;_id&quot;);<br>      return !!found;<br>  }<br>  return false;<br>}<br>/**<br> * Checks if an item is a child of a collection.<br> * @param {object} req - The request object.<br> * @param {object} item - The item to be checked.<br> * @param {object} originalItem - The original item.<br> * @returns {Promise} - Resolves to boolean.<br> */<br>async function checkSecondaryPermissions(req, item, originalItem, companyId) {<br>  const parent = await CollectionA.findOne({ children: { $in: [item.id || item._id] } })<br>      .select(&quot;permissions&quot;)<br>      .populate(&quot;permissions&quot;)<br>      .lean();<br>  if (parent) {<br>      return await checkPermissions(req, parent, originalItem || item, companyId);<br>  }<br>  return await checkItemInclusion(originalItem || item, originalItem);<br>}<br>/**<br> * Main function that checks if a user has permissions.<br> * @param {object} req - The request object.<br> * @param {object} item - The item to be checked.<br> * @param {object} originalItem - The original item.<br> * @param {string} companyId - The company id.<br> * @returns {Promise} - Resolves to boolean.<br> */<br>async function checkPermissions(req, item, originalItem, companyId) {<br>  try {<br>    // If request, item or user id is missing, resolve to false<br>    if (!req?.auth?.data?.id || !item?.permissions) {<br>      return false;<br>    }<br>    if (!companyId) {<br>      ({ companyId } = await findCompany(item));<br>    }<br>    if (!(await isCompany({ userId: req.auth.data.id, companyId }))) {<br>      console.log(`Permission DENIED. user don&#39;t belong to company ${companyId}`);<br>      return false;<br>    }<br>    const user = await findUser(req.auth.data.id);<br>    var access = item.permissions.filter((share) =&gt; comparePermissions(share.user, req.auth.data.id));<br>    if (access &amp;&amp; access.length &gt; 0) {<br>      return !(access[0].exclude?.indexOf((originalItem || item)._id.toString()) &gt;= 0);<br>    }<br>    if (user?.roles?.indexOf(&quot;all&quot;) &gt;= 0) {<br>      const auth = await User.findOne({<br>        _id: { $in: item.permissions.map((s) =&gt; s.user._id) },<br>        supportAccess: { $gt: new Date().addDays(-7) },<br>      });<br>      if (auth) {<br>        return true;<br>      }<br>    }<br>    return await checkSecondary();<br>  } catch (error) {<br>    throw error;<br>  }<br>}</pre><p>Wow!</p><ul><li>Separate methods</li><li><strong>30% less lines of code</strong></li><li><strong>No callback hell</strong></li><li>Documentation for each</li></ul><p>I couldn’t ask for more.. so I asked for some pointers:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/758/1*7ezpA0JqzevdOhcc7hR86w.png" /></figure><p>While chatting a little more we ran into some interesting ideas</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/706/1*VNzY_8ht5P-leKA3_3UJjQ.png" /><figcaption>Suspicious</figcaption></figure><p>I didn’t notice this addDays method but turns out it’s actually a custom method so I asked if we can improve that..</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/821/1*4SCvwjR7VwvKWzxE0pM7_Q.png" /></figure><p>This leads us on our next mission…</p><h4>Tips &amp; Takeaways</h4><ul><li>You can use AI aid for different scenarios to your liking and as you see fit — it’s not a “one size fits all” situation.</li><li>Own the end result</li><li>Tests are your best friend when refactoring — check out <a href="https://medium.com/@giladhoshmand/how-gpt-4-writes-tests-for-me-775194008ec5">How GPT-4 writes tests for me</a></li><li>Don’t put any confidential/IP code into a black box on the web</li><li>The input you supply should have all the information needed for refactoring — nothing less, nothing more — messy input = messy output.</li><li>Large Language Models (LLM) are trained on a set of data which is naturally finite and up to a certain point in time.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*TVzqYdV9ljK9h6hp.jpg" /><figcaption>If you’ve made it this far — you know what to do</figcaption></figure><h4>Remember: Own the final code, own the implications of any change to the code base, you are responsible for it and no one else. Code that was refactored or produced is to be used as assistance but the code committed is signed by you and you alone. There is no blaming a machine after production exploded because of generated code you did not understand or test well enough.</h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=12a728266c03" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How GPT-4 writes tests for me]]></title>
            <link>https://medium.com/@giladhoshmand/how-gpt-4-writes-tests-for-me-775194008ec5?source=rss-e9a99afa1999------2</link>
            <guid isPermaLink="false">https://medium.com/p/775194008ec5</guid>
            <category><![CDATA[software-testing]]></category>
            <category><![CDATA[chatgpt]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[gpt-4]]></category>
            <category><![CDATA[testing]]></category>
            <dc:creator><![CDATA[Gilad Hoshmand]]></dc:creator>
            <pubDate>Wed, 22 Mar 2023 20:17:26 GMT</pubDate>
            <atom:updated>2023-06-08T08:15:01.149Z</atom:updated>
            <content:encoded><![CDATA[<h4>Trying out GPT-4</h4><p>ChatGPT — everybody is talking about it, everyone has an opinion, it’s a lot of fun to play around with but we are <strong>not playing</strong> here — I want to show some <strong>practical use</strong> which can help you save time and be more efficient.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qWPcEzLcxEuGFxy3" /><figcaption>I’m using <strong>GPT-4 </strong>for this article</figcaption></figure><h4>Motivation</h4><p>We’ve all seen it before — that project with a ever falling code coverage percentage — increasingly scary to deploy and as predictable as North Korea.</p><figure><img alt="Meme-”My boss congratulating me on the latest deployment”-”Me who has no idea what the code i changed was for”" src="https://cdn-images-1.medium.com/max/528/1*B-8wxCNl_E9MrjPy4ejj6w.jpeg" /><figcaption>TFW</figcaption></figure><p>This often happens because of <strong>lack of procedure</strong> and <strong>bad time allocation</strong> — aka — not allocation time to write tests. <br>What if I told you writing unit tests is now a matter of seconds?</p><h4>Steps:</h4><ol><li>Put the code you want tests for in ChatGPT</li><li>Copy-paste the answer — It’s not compiling</li><li>Remember the C++ vet from work that said ChatGPT is a millennial pile of garbage that will never replace him</li><li>Come back to this blog post — Easy right?</li></ol><h4>Best practices</h4><p>Generally speaking - any time you give the Large Language Model (LLM) some code with no specifics, context, requirements etc. — anything can happen, I mean anything..</p><p>Me: <em>Write tests for this code</em> : &lt;code&gt; <br>Chat: &lt;code output&gt;<br>Me: <em>This code does not compile</em><br>Chat: <em>You are right, sorry for that, let me fix it for you.. &lt;Produces worst code&gt;<br></em>Me: <em>This code has more issues than before you “fixed” it</em><br>Chat: <em>I’m sorry for that &lt;Produces exact same code&gt;</em></p><h4><strong>TL;DR — Start here</strong></h4><p>What is ChatGPT really good at:</p><ul><li>Languages &amp; technologies that have been around for a while</li><li>Languages &amp; technologies that are widely used</li><li>Standard code with standard usage</li><li>Utility code that does something specific</li></ul><p>Less efficient with(results vary):</p><ul><li>New technologies &amp; libraries — it is only <strong>trained until a specific point in time </strong>— this is <strong>critical </strong>to know and pay attention to.</li><li>code that was heavily customized or abused for a hard to predict magic reason — things can get messy</li><li>Complex code that has complex dependencies</li></ul><h4>Examples:</h4><p>The easiest time-saver is generating tests for any <strong>utility method</strong> that takes some input and does some processing &amp; output. I’ll take the example of the top rated JavaScript question on StackOverflow:</p><p>My input:<em> Write tests in Typescript &amp; jest for this code:</em></p><pre>export const removeItemOnce = (arr:any[], value:any) =&gt; {<br>  const index = arr.indexOf(value);<br>  if (index &gt; -1) {<br>  arr.splice(index, 1);<br>  }<br>  return arr;<br>}<br>   <br>export const removeItemAll = (arr:any[], value:any) =&gt; {<br>  let i = 0;<br>  while (i &lt; arr.length) {<br>    if (arr[i] === value) {<br>      arr.splice(i, 1);<br>    } else {<br>      ++i;<br>    }<br>  }<br>  return arr;<br>}</pre><p>The answer, in seconds, test all <em>“basic functionality” </em>as ChatGPT calls it.</p><pre>import {removeItemOnce, removeItemAll} from &#39;./util&#39;<br>describe(&#39;removeItemOnce&#39;, () =&gt; {<br>    it(&#39;should remove the first occurrence of the value from the array&#39;, () =&gt; {<br>      const arr = [1, 2, 3, 4];<br>      const value = 3;<br>      const expected = [1, 2, 4];<br>      const result = removeItemOnce(arr, value);<br>      expect(result).toEqual(expected);<br>    });<br>  <br>    it(&#39;should return the original array if the value is not found&#39;, () =&gt; {<br>      const arr = [1, 2, 3, 4];<br>      const value = 5;<br>      const result = removeItemOnce(arr, value);<br>      expect(result).toEqual(arr);<br>    });<br>  });<br>  <br>  describe(&#39;removeItemAll&#39;, () =&gt; {<br>    it(&#39;should remove all occurrences of the value from the array&#39;, () =&gt; {<br>      const arr = [1, 2, 3, 4, 3, 5];<br>      const value = 3;<br>      const expected = [1, 2, 4, 5];<br>      const result = removeItemAll(arr, value);<br>      expect(result).toEqual(expected);<br>    });<br>  <br>    it(&#39;should return the original array if the value is not found&#39;, () =&gt; {<br>      const arr = [1, 2, 3, 4];<br>      const value = 5;<br>      const result = removeItemAll(arr, value);<br>      expect(result).toEqual(arr);<br>    });<br>  });</pre><p>We have 100% line coverage but we want a little more and so I should have been more <strong>descriptive, specific </strong>and generally less lazy — I should specify I want edge cases checked too (yes it’s not obvious for a LLM).</p><p>Me:<em> Add some edge case checks</em></p><pre>  it(&#39;should return an empty array if the input array is empty&#39;, () =&gt; {<br>    const arr: number[] = [];<br>    const value = 5;<br>    const result = removeItemOnce(arr, value);<br>    expect(result).toEqual([]);<br>  });<br><br>  it(&#39;should return an empty array if the input array contains only the value to be removed&#39;, () =&gt; {<br>    const arr = [5];<br>    const value = 5;<br>    const result = removeItemOnce(arr, value);<br>    expect(result).toEqual([]);<br>  });<br><br>// more cases that are not needed to prove the point</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/0*Og460wsQYidBIjMq.gif" /><figcaption>Berry Nice</figcaption></figure><p>OK we’ve proved a point about specifying what you need rather then just throwing code in and hoping what you’re expecting will actually be tested.<br>Moving on to more complex scenarios —how does ChatGPT handle dependencies? Well… it depends.. and this is <strong>really interesting</strong></p><p>This is the sample ES Module code I’m using:</p><pre>import { SendMessageCommand, SQSClient } from &#39;@aws-sdk/client-sqs&#39;;<br><br>const client = new SQSClient({<br>    region: process.env.AWS_REGION,<br>    credentials: {<br>        accessKeyId: process.env.AWS_KEY as string,<br>        secretAccessKey: process.env.AWS_SECRET as string,<br>    }<br>});<br><br>export const sendMessage = (msg:string) =&gt; client.send(new SendMessageCommand({ <br>    MessageBody: msg,<br>    QueueUrl: process.env.AWS_QUEUE<br>}));</pre><p>Trying to get tests for a node.js ES Module can break your brain. <br>ChatGPT will BS it’s way to an answer which 99% of the time — won’t even compile. <br>The reason? The technique and standard is fairly new. At the time of writing official Jest docs state<em> “Jest ships with </em><strong><em>experimental</em></strong><em> support for ECMAScript Modules (ESM)” </em>while OpenAI site states that <em>“ChatGPT’s training data cuts off in 2021” </em>— Viola!</p><p>The<strong> weak spot of any LLM</strong> is that it is trained on a set of data, if this data has some kind of issue (maybe even over time) like — it is no longer up-to-date, it becomes invalid/incorrect etc. — then <strong>it is/becomes unusable for that case </strong>and this is exactly what is happening with node 19, ES Modules and Jest.</p><p>We’ll go with Python then.. <br>Me: <em>Write tests for the following python code</em></p><pre>from external_dependency import some_util<br>from another_external_dependency import method_that_has_a_side_effect<br><br>def do_some_action(obj: object) -&gt; object:<br>    return some_util(obj)<br><br>def do_some_other_action(obj: object):<br>    ans = do_some_action(obj);<br>    result = method_that_has_a_side_effect(ans);<br>    return result;</pre><p>ChatGPT:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/795/1*SUxGHZo4grQJiPyKwbSUXw.png" /></figure><pre>import unittest<br>from unittest.mock import MagicMock, patch<br>from your_module import do_some_action, do_some_other_action<br><br>class TestYourModule(unittest.TestCase):<br><br>    def test_do_some_action(self):<br>        mock_obj = MagicMock()<br>        with patch(&quot;your_module.some_util&quot;) as mock_some_util:<br>            mock_some_util.return_value = &quot;expected_value&quot;<br>            result = do_some_action(mock_obj)<br>            self.assertEqual(result, &quot;expected_value&quot;)<br>            mock_some_util.assert_called_once_with(mock_obj)<br><br>    def test_do_some_other_action(self):<br>        mock_obj = MagicMock()<br>        mock_ans = MagicMock()<br>        mock_result = MagicMock()<br>        <br>        with patch(&quot;your_module.do_some_action&quot;) as mock_do_some_action, \<br>             patch(&quot;your_module.method_that_has_a_side_effect&quot;) as mock_method_that_has_a_side_effect:<br>            <br>            mock_do_some_action.return_value = mock_ans<br>            mock_method_that_has_a_side_effect.return_value = mock_result<br>            <br>            result = do_some_other_action(mock_obj)<br>            <br>            self.assertEqual(result, mock_result)<br>            mock_do_some_action.assert_called_once_with(mock_obj)<br>            mock_method_that_has_a_side_effect.assert_called_once_with(mock_ans)<br><br>if __name__ == &quot;__main__&quot;:<br>    unittest.main()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/684/1*MBUW9IpJWD5rwJ5VebXNiw.png" /></figure><p>Easy right? Mocks and all!! <br>That is mainly because this has been done so many times before — standard test for <strong>standard use-cases</strong> — the data which has been fed to the LLM has many matching results (tokens) to get “confidence” of a correct prediction and it did make the job easy — 10 seconds.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/220/0*QC9P-cEdforUTpFs.gif" /><figcaption>More time to spoil your loved ones</figcaption></figure><h4>Main takeaways</h4><ul><li>Before you start you should ideally have an understanding of what you want to test in order to provide clear instructions and be able to evaluate the response</li><li>Use a <strong>modular approach</strong> — break the code down to modules that can be separately handled by ChatGPT</li><li>The input you supply should have all the information needed for the tests you want the LLM to output — nothing less, nothing more</li><li>Be precise — excess “garbage” input means you are more likely to get a more “noisy” output</li><li>The source of the answer is unknown — <strong>always make sure you understand the code</strong></li></ul><h4>Tips</h4><ul><li>Don’t fight! ChatGPT is just not great at some things</li><li>Data may not be up to date — latest topics will be missing</li><li>Implementation may not be best practice or even the latest recommended practice — quality is up to you</li><li>AI is your aid; not replacing you just yet (:</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=775194008ec5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to TDD with ChatGPT]]></title>
            <link>https://medium.com/@giladhoshmand/tdd-with-chatgpt-c375b3b78d6a?source=rss-e9a99afa1999------2</link>
            <guid isPermaLink="false">https://medium.com/p/c375b3b78d6a</guid>
            <category><![CDATA[chatgpt]]></category>
            <category><![CDATA[software-testing]]></category>
            <category><![CDATA[tdd]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[gpt-4]]></category>
            <dc:creator><![CDATA[Gilad Hoshmand]]></dc:creator>
            <pubDate>Mon, 06 Mar 2023 21:42:39 GMT</pubDate>
            <atom:updated>2023-09-22T12:17:46.196Z</atom:updated>
            <content:encoded><![CDATA[<h3>Test Driven Development with GPT-4</h3><h3>What is TDD?</h3><p>From Guru99 —<em> “</em><strong><em>Test Driven Development (TDD)</em></strong><em> is software development approach in which test cases are developed to specify and validate what the code will do. In simple terms, test cases for each functionality are created and tested first and if the test fails then the new code is written in order to pass the test and making code simple and bug-free.”</em></p><p>I recommend reading the full article which has a very clear explanation along with pros &amp; cons.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/454/0*5OoTMZfQIAywd51b.png" /><figcaption><strong>Test Driven Development (TDD) by Guru99</strong></figcaption></figure><h3>TDD using ChatGPT</h3><p>After <a href="https://medium.com/@giladhoshmand/how-gpt-4-writes-tests-for-me-775194008ec5">hammering ChatGPT with modules so that it writes tests for me</a> I was exhausted — writing the tests myself would have been easier, faster and much more accurate. So I did.</p><p>It got me wandering — could<strong> I supply the tests and have ChatGPT produce the code </strong>for me?</p><h4>Let’s find out while considering the guidelines:</h4><ul><li>The tests need to define the exact behavior we want our code to have</li><li>Tests must cover edge cases so that Chat output will handle them correctly</li><li>Test for correct error handling so that our code will reflect it</li><li>Supply as much info about the file we want ChatGPT to produce</li></ul><p>Generally speaking —<strong> you should be able to read a test file and know exactly what the code does without ever looking at it</strong>.</p><p>Let’s try starting with a simple SQS client test file. We will import the exported client from the module and test that it has been initiated with the expected configuration.</p><pre>import { SQSClient } from &#39;@aws-sdk/client-sqs&#39;;<br><br>process.env.AWS_REGION = &#39;test-region&#39;;<br>process.env.AWS_KEY = &#39;test-key&#39;;<br>process.env.AWS_SECRET = &#39;test-secret&#39;;<br><br>jest.mock(&#39;@aws-sdk/client-sqs&#39;, () =&gt; {<br>  return {<br>    SQSClient: jest.fn(),<br>  };<br>});<br><br>// I should be able to import an exported member named &#39;client&#39;<br>import { client } from &#39;./sqs.client.js&#39;<br><br>describe(&#39;SQSClient module&#39;, () =&gt; {<br>   it(&#39;Should initialize the SQSClient with the expected input&#39;, () =&gt; {<br>     const expectedConfig = {<br>       region: &#39;test-region&#39;,<br>       credentials: {<br>         accessKeyId: &#39;test-key&#39;,<br>         secretAccessKey: &#39;test-secret&#39;<br>       }<br>     };<br>     expect(SQSClient).toHaveBeenCalledWith(expectedConfig);<br>   });<br>});</pre><p>The answer:</p><pre>import { SQSClient } from &#39;@aws-sdk/client-sqs&#39;;<br><br>export const client = new SQSClient({<br>    region: process.env.AWS_REGION,<br>    credentials: {<br>        accessKeyId: process.env.AWS_KEY,<br>        secretAccessKey: process.env.AWS_SECRET,<br>    }<br>});</pre><p>Remarkably — it works — it also gave me simple, clean code!<br>It “knew” which environment variables and library to use because they were defined/mocked in the test file.</p><p>Let’s try another… this time we’ll make it harder. <br>My input:<em> “Attempt to write http.service.ts based on the following test file”</em></p><pre>import fetch from &#39;node-fetch&#39;;<br>import * as service from &#39;./http.service&#39;;<br><br>const TEST_URL = &#39;https://some.fake.url&#39;;<br>const TEST_BODY = { a: 1, b: 2 };<br><br>afterEach(() =&gt; {<br>  jest.clearAllMocks();<br>});<br><br>jest.mock(&#39;node-fetch&#39;, () =&gt; jest.fn());<br>const mockJson = jest.fn() as jest.MockedFunction&lt;any&gt;;<br>const mockFetch = fetch as jest.MockedFunction&lt;typeof fetch&gt;;<br><br>describe(&#39;Test http service&#39;, () =&gt; {<br>  test(&#39;get calls fetch once with supplied url and expected headers&#39;, async () =&gt; {<br>    await service.get(TEST_URL);<br>    expect(mockFetch).toBeCalledTimes(1);<br>    expect(mockFetch).toHaveBeenCalledWith(<br>      expect.stringMatching(TEST_URL),<br>      expect.objectContaining({<br>        headers: expect.objectContaining({<br>          &#39;Content-Type&#39;: &#39;application/json&#39;,<br>        }),<br>      })<br>    );<br>  });<br><br>  test(&#39;post calls fetch once with supplied url and expected headers&#39;, async () =&gt; {<br>    mockFetch.mockResolvedValueOnce({ ok: true, json: mockJson, status:200 } as Response);<br>    await service.post(TEST_URL, TEST_BODY);<br>    const jsonBody = JSON.stringify(TEST_BODY);<br>    expect(mockFetch).toBeCalledTimes(1);<br>    expect(mockFetch).toHaveBeenCalledWith(<br>      expect.stringMatching(TEST_URL),<br>      expect.objectContaining({<br>        method: &#39;POST&#39;,<br>        headers: expect.objectContaining({<br>          &#39;Content-Type&#39;: &#39;application/json&#39;,<br>          &#39;Content-Length&#39;: jsonBody.length.toString(),<br>        }),<br>        body: jsonBody,<br>      })<br>    );<br>  });<br><br>  test(&#39;post should throw exception thrown by underline node-fetch function&#39;, async () =&gt; {<br>      mockFetch.mockRejectedValue(new Error(&#39;fetch error message&#39;));<br>      await service.post(TEST_URL, TEST_BODY);<br>      await expect(mockFetch).rejects.toThrow(Error(&#39;fetch error message&#39;));<br>  });<br>});</pre><p>The answer I received was again pretty clean!</p><pre>import fetch, { Response } from &#39;node-fetch&#39;;<br><br>export interface RequestOptions {<br>  headers?: Record&lt;string, string&gt;;<br>  body?: Record&lt;string, any&gt; | string;<br>  method?: &#39;GET&#39; | &#39;POST&#39; | &#39;PUT&#39; | &#39;DELETE&#39;;<br>}<br><br>export async function get(url: string, options: RequestOptions = {}): Promise&lt;Response&gt; {<br>  const headers = options.headers || { &#39;Content-Type&#39;: &#39;application/json&#39; };<br>  return fetch(url, { method: &#39;GET&#39;, headers });<br>}<br><br>export async function post(url: string, body: Record&lt;string, any&gt;, options: RequestOptions = {}): Promise&lt;Response&gt; {<br>  const headers = options.headers || {<br>    &#39;Content-Type&#39;: &#39;application/json&#39;,<br>    &#39;Content-Length&#39;: JSON.stringify(body).length.toString(),<br>  };<br>  return fetch(url, { method: &#39;POST&#39;, headers, body: JSON.stringify(body) });<br>}</pre><p>It is now becoming very clear to me of the added benefits aside from having code auto generated for me —<strong>my tests are missing details</strong> and ChatGPT is implementing(guessing) as it sees fit. <br>I now notice my tests don’t tell the full tale; one obvious thing to point out is the return type — it’s a good guess by ChatGPT but what if I required something else?</p><p>Other issues include no error thrown check for the get method and no handling of the !response.ok case for both methods — after seeing the code produced it is clear that I have no tests to cover those cases and so <strong>the behavior is not defined</strong>.</p><p>So I tried the following (don’t do this):</p><pre>/**<br> * Example that specifies the return type of called methods<br> **/<br><br>import fetch, { Response } from &#39;node-fetch&#39;;<br>// Same as before<br>describe(&#39;Test http service&#39;, () =&gt; {<br><br>  test(&#39;get calls fetch once with supplied url and expected headers.<br>        It should return the response.json() payload&#39;, async () =&gt; {<br>    // ...Same as before<br>    // Changed the get return type<br>    const jsonResponse: unknown = await service.get(TEST_URL);<br>    // Same as before<br>  });<br><br>  test(&#39;post calls fetch once with supplied url and expected headers <br>        and returns a response with type fetch Response&#39;, async () =&gt; {<br>    // ...Same as before<br>    // Changed the post return type<br>    const response:Response = await service.post(TEST_URL, TEST_BODY);<br>    // Same as before<br>  });<br>  // Same as before<br>});</pre><p>Chat picked up on the change:</p><pre>import fetch, { Response } from &#39;node-fetch&#39;;<br><br>export async function get(url: string): Promise&lt;unknown&gt; {<br>  const response: Response = await fetch(url, {<br>    headers: {<br>      &#39;Content-Type&#39;: &#39;application/json&#39;,<br>    },<br>  });<br>  return response.json(); // It changed the return type!!<br>}<br><br>export async function post(url: string, body: any): Promise&lt;Response&gt; {<br>  const response: Response = await fetch(url, {<br>    method: &#39;POST&#39;,<br>    headers: {<br>      &#39;Content-Type&#39;: &#39;application/json&#39;,<br>      &#39;Content-Length&#39;: JSON.stringify(body).length.toString(),<br>    },<br>    body: JSON.stringify(body),<br>  });<br>  return response; // Correct return type here too<br>}</pre><p>It changed the return types on both methods to reflect the modified test file I supplied it with. I think that is remarkable.</p><p>Just think of the number of times you’ve encountered a bug just to find out error handling was not done correctly; or the times some code was uncovered by tests that did not exist or were not updated when the code was modified.</p><h3>Takeaways</h3><ul><li>ChatGPT can aid you in your TDD process</li><li>You must specify your requirements very precisely otherwise it will make assumptions</li><li>ChatGPT can help you find unspecified parts of your tests that were not specific enough</li><li>Any code that was not covered in testing won’t be reflected in the final output.</li><li>Beware the code it produces, <strong>never use code without fully understanding every bit of it</strong>.</li><li>In the following diagram ChatGPT comes in at “Make changes to the code”</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/407/0*JOGVzJquIUwL3lNW.png" /><figcaption>Five Steps of Test-Driven Development by Guru99</figcaption></figure><h3>Tips:</h3><ul><li>Chatting back and forth could lead to some messy code as ChatGPT could rewrite the whole code at any step along the conversation.</li><li>Write your tests as though they are the real tests you are going to ship. Anything less could lead to bad results — remember — ChatGPT is built on top of a Language Model — the better “hits” your text gets — the better the results — be as specific as possible.</li></ul><p><strong>Disclaimer: </strong>The results were not always consistent. Asking at different days gave different results. Also after chatting ChatGPT would “learn” and give a different result to the same question. <br>I made an effort to keep the info here as close to reality as possible while filtering out the noise.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c375b3b78d6a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to reach 100% unit test coverage with Node.js Express & Jest]]></title>
            <link>https://medium.com/@giladhoshmand/how-to-reach-100-unit-test-coverage-with-node-js-express-jest-d8909080f9dd?source=rss-e9a99afa1999------2</link>
            <guid isPermaLink="false">https://medium.com/p/d8909080f9dd</guid>
            <category><![CDATA[software-testing]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[unit-testing]]></category>
            <dc:creator><![CDATA[Gilad Hoshmand]]></dc:creator>
            <pubDate>Sat, 21 Jan 2023 17:37:19 GMT</pubDate>
            <atom:updated>2023-01-21T17:37:19.216Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>There is not going to be one, let’s go!</p><h3>Assumptions</h3><p>Trigger warning — there are going to be some assumptions.. I’m assuming you know:</p><ul><li>Some JavaScript</li><li>Basic Node.js &amp; Express setup</li><li>Familiar with Unit testing as a concept</li></ul><p>I want to point out we are NOT going to focus on the 80% but rather on the 20% — those <strong>last few lines that are hard to cove</strong>r — keeping in mind The Pareto Principle. <br>The 80% can be easily done by just applying regular unit testing methods,</p><h3>Let’s GSD</h3><p>We’ll have a simple made up Node.js + Express setup. <br>Our project structure is as follows:</p><pre>.<br>└───src          <br>  └───controllers<br>    │   abc.controller.ts<br>    │   def.controller.ts<br>  └───middlewares<br>    │   auth.middleware.ts<br>    │   postprocess.middleware.ts<br>  └───services<br>    │   db.service.ts<br>    │   http.service.ts<br>  │   app.ts<br>│   package.json<br>│   tsconfig.json<br>│   jest.config.ts</pre><p>We’ll use <a href="https://jestjs.io/">jest</a> so our scripts test scripts in package.json will include:</p><pre>&quot;scripts&quot;: {<br>  &quot;build&quot;: &quot;tsc&quot;,<br>  &quot;test&quot;: &quot;jest&quot;,<br>  &quot;coverage&quot;: &quot;jest --coverage&quot;,<br>}</pre><p>Now as-I-said I’m not going to explain unit testing, Node, Jest etc. — just give an example of the 80% part; let’s look at a simple implementation for the file with the terrible terrible name <em>abc.controller.ts:</em></p><pre>//abc.controller.ts<br>import * as service from &#39;../services/db.service.js&#39;;<br>import { RequestHandler } from &#39;express&#39;;<br>const getById: RequestHandler = (req, res) =&gt; service.getById(<br>  req.params.collection,<br>  req.params.id<br>);<br>const getAll: RequestHandler = (req, res, next) =&gt; {<br>  res.locals.result = await service.getAll(req.params.collection);<br>  next();<br>};<br>export { getAll, getById };</pre><p>The unit tests will look something like:</p><pre>import * as controller from &#39;./abc.controller&#39;;<br>import { NextFunction, Request, Response } from &#39;express&#39;;<br>import * as service from &#39;../services/db.service&#39;;<br>const testId = &#39;test-id&#39;;<br>const testCollection = &#39;test-entity-name&#39;;<br>jest.mock(&#39;../services/db.service&#39;, () =&gt; ({<br>  __esModule: true,<br>  getAll: jest.fn(),<br>  getById: jest.fn(),<br>}));<br>afterAll(() =&gt; {<br>  jest.clearAllMocks();<br>});<br>describe(&#39;Test controller&#39;, () =&gt; {<br>  test(&#39;controller.getById calls service once with supplied collection &amp; id&#39;, async () =&gt; {<br>    jest.spyOn(service, &#39;getById&#39;);<br>    await controller.getById(<br>      { params: { id: testId, collection: testCollection } } as unknown as Request,<br>      {} as unknown as Response,<br>      jest.fn() as NextFunction<br>    );<br>    expect(service.getById).toBeCalledTimes(1);<br>    expect(service.getById).toBeCalledWith(testCollection, testId);<br>  });<br>  test(&#39;Test controller.getAll calls service once with supplied collection &amp; calls the next middleware in chain&#39;, async () =&gt; {<br>    jest.spyOn(service, &#39;getAll&#39;).mockImplementation();<br>    const next: NextFunction = jest.fn();<br>    await controller.getAll(<br>      { params: { collection: testCollection } } as unknown as Request,<br>      {} as unknown as Response,<br>      next<br>    );<br>    expect(service.getAll).toBeCalledTimes(1);<br>    expect(service.getAll).toBeCalledWith(testCollection);<br>    expect(next).toBeCalledTimes(1);<br>  });<br>});</pre><p>Now we’ve worked hard and managed to cover the 80% — controllers, services, middle-wares. Let’s see where we are at..</p><pre>jest - coverage</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/722/1*ssdB2ZZ85aI4ZVaeh5Fcvw.png" /><figcaption>Coverage results — looking good so far</figcaption></figure><p>Ahhh a lot of green! But wait! app.ts is <strong>RED!</strong></p><p>The app.ts file is different then the others, it’s harder to test — it has settings, routing, controller &amp; middle-ware flow logic. <br>For our first attempt we’ll simply import it because what is line coverage? It is a measure of lines executed and the app.ts file is mainly statements:</p><pre>//app.ts<br>import express, { Express, Request, Response } from &#39;express&#39;;<br>import * as controller from &#39;./controllers/abc.controller.js&#39;;<br>import { authMiddleware } from &#39;./middlewares/auth.middleware.js&#39;;<br>import { postprocessMiddleware } from &#39;./middlewares/postprocess.middleware.js&#39;;<br>const app: Express = express();<br>const port = process.env.PORT;<br>app.get(&#39;/healthCheck&#39;, (req: Request, res: Response) =&gt; res.sendStatus(200));<br>app.get(&#39;/api/:collection&#39;, authMiddleware, controller.getAll, postMiddleware);<br>app.get(&#39;/api/:collection/:id&#39;, authMiddleware, controller.getById);<br>app.listen(port, () =&gt; console.log(`Node app listening on port ${port}`));</pre><pre>//app.test.ts<br>jest.mock(&#39;./controllers/abc.controller&#39;, () =&gt; ({<br>  __esModule: true,<br>  getAll: jest.fn(),<br>  getById: jest.fn(),<br>}));<br>jest.mock(&#39;./middlewares/auth.middleware&#39;, () =&gt; ({<br>  __esModule: true,<br>  authMiddleware: jest.fn(),<br>}));<br>jest.mock(&#39;./middlewares/postprocess.middleware&#39;, () =&gt; ({<br>  __esModule: true,<br>  postprocessMiddleware: jest.fn(),<br>}));<br>jest.mock(&#39;express&#39;, () =&gt; ({<br>  default: () =&gt; ({ get: jest.fn(), listen: jest.fn() }),<br>}));<br>import &#39;./app&#39;; //importing will execute most of the code!<br>describe(&#39;Test App code coverage by import&#39;, function () {<br>  it(&#39;Should be a truthy test because the test suite cannot be empty&#39;, () =&gt; {<br>    expect(1).toBe(1);<br>  });<br>});</pre><p>Let’s see the results again:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/719/1*jlz_c6U3TKqVh3yABIPMZQ.png" /></figure><p>Now we did get to 100% line coverage but if you’re OCD about gamified stuff like me you <strong>HAVE TO GET TO 100%</strong> no matter what it takes.</p><h3>The Problem</h3><p>This looks like a non-issue, some of you may say <em>it is</em> a non issue but if the app grows this could get painful. Let’s see what we can do..<br>The main problem is that we have some high coupling in this file and we need to make many mocks, some of them even have some logic baked into them. The problem is grown in magnitude as the app requires more configurations maybe with some different settings for dev &amp; prod.<br>This could be very hard to hard to maintain over time.</p><p>Another issue is that some inner (non-exported) functions in the module cannot be imported and tested on their own — which again means we are coupling things together and not getting reliable feedback while also making it harder to introduce isolated changes without breaking tests (that are required to test too many things at once).</p><p>To cover everything we need to execute the code — but we’re just unit testing the app module, what if these executions cause side effects? what if some data is inserted into our production db?</p><p>To demonstrate we will look at the /healthcheck endpoint handler &amp; the callback executed after app.listen is called.</p><h3>The solution — The Good, the Bad, the Ugly &amp; the Quick and Dirty</h3><h4>The Ugly</h4><p>This is really messy and I’m all against writing more code just to make some test work. Just imagine how these magic lines &amp; hacks could grow over time as more functionality is needed in our app.</p><pre>//app.ts<br>const healthCheckHandler: RequestHandler = (req, res) =&gt; res.sendStatus(200); // extracted function that is missing coverage<br>// app configuration...<br>app.get(&#39;/healthCheck&#39;, healthCheckHandler);<br>let exportForTest;<br>if (process.env.NODE_ENV == &#39;test&#39;) {<br>  exportForTest = healthCheckHandler; // set exported function only in test env<br>}<br>export { exportForTest }; // must be at top level ( cannot happen inside the &#39;if&#39; - that is why we need an extra var exportForTest)</pre><p>This is a short term fix; the technique is hacky and the growth will be painful.</p><p>Everyone will hate you.</p><h4>The Bad</h4><p>You can simply decide that the coverage for this file is purely cosmetic and exclude it in the jest.config.ts file:</p><pre>const config: Config.InitialOptions = {<br>  // ...<br>  coveragePathIgnorePatterns: [&#39;./src/app.ts&#39;],<br>};</pre><p>Or exclude the specific lines from coverage using some predetermined comment — <a href="https://jestjs.io/docs/configuration/#collectcoverage-boolean">check out the docs</a>.</p><p>We’re not even going to discuss these I’m disgusted with you for even thinking about it.</p><h4>Quick &amp; (a little) Dirty</h4><p>Changing the mocks to implement some of the logic will get us some coverage (in this case for express.listen line).</p><pre>// app.test.ts<br>jest.mock(&#39;express&#39;, () =&gt; ({<br>  default: () =&gt; ({ get: jest.fn(), listen: (port:number, callback:() =&gt; void ) =&gt; callback() }),<br>}));</pre><p>We still have the cover the /healthcheck endpoint. We can do that with an external package like <a href="https://github.com/ladjs/supertest"><em>supertest</em></a>. This will not be covered here but basically mimics a call to an endpoint.</p><p>This is a short term win — we actually got to 100%.<br>But it’s also now obvious that as the app will grow so will the complexity of test logic and scenarios to cover — ie. what if we have some complex logic for the callback? Will we rewrite that too?</p><h4>The Good</h4><p>Looking closer at app.ts we start to understand that if we had separation between the entry point, app and routing some of the testing will be easy and natural — no hacks no tricks.</p><pre>// modified app.ts<br>import express, { Express } from &#39;express&#39;;<br>import router from &#39;./router.js&#39;;<br>// In the future some other imports for app tools we need, example:<br>// import myFavoriteLogger from &#39;logger-package-name&#39;;<br>// app.use(myFavoriteLogger) &lt;-- after app init<br>const app: Express = express();<br>app.use(&#39;/&#39;, router);<br>export default app;</pre><pre>// new file router.ts - defines the routes and middleware/handler chain<br>import { Request, Response, Router } from &#39;express&#39;;<br>import { authMiddleware } from &#39;./middlewares/auth.middleware.js&#39;;<br>import * as controller from &#39;./controllers/abc.controller.js&#39;;<br>import { postprocessMiddleware } from &#39;./middlewares/postprocess.middleware.js&#39;;<br>const router = Router();<br>router.get(&#39;/healthCheck&#39;, (req: Request, res: Response) =&gt; res.sendStatus(200));<br>router.get(&#39;/api/:collection/:id&#39;, authMiddleware, controller.getById,);<br>router.get(&#39;/api/:collection&#39;, authMiddleware, controller.getAll, postprocessMiddleware);<br>export default router;</pre><pre>// new file index.ts - this will be the entrypoint for the application<br>import * as dotenv from &#39;dotenv&#39;;<br>import app from &#39;./app.js&#39;;<br><br>dotenv.config();<br>const port = process.env.PORT;<br><br>app.listen(port, () =&gt; console.log(`Node app listening on port ${port}`));</pre><p>Look at the result — it’s so easy to understand where you control entry point load orchestration, adding the next endpoint, modifying (Express) app related settings.<br>The aftermath is 3 files instead of 1 and 3 test files instead of 1. <br>Let’s check out one of them:</p><pre>// app.test.ts<br>jest.mock(&#39;express&#39;, () =&gt; ({<br>  default: () =&gt; ({ use: jest.fn(), options: jest.fn() }),<br>}));<br><br>import &#39;./app&#39;;<br>afterAll(() =&gt; {<br>  jest.clearAllMocks();<br>});<br>describe(&#39;Test app.ts code&#39;, function () {<br>  it(&#39;Everything is ran by importing app module, this is here so that the suite is not empty&#39;, () =&gt; {<br>    expect(1).toBe(1);<br>  });<br>});</pre><p>Que clean! Que beautiful! This gives 100% because all lines were executed!</p><p>Refactoring the entry point to index, app &amp; router modules had given us a clearer view of what isn’t covered and removed some mocking issues.<br>We can now combine some (the least possible) mocking with importing to easily gain 100% coverage. Any specific line/function can be handled <strong>in its own module </strong>without importing the whole app (ie. router stuff will be tested alone). So we might still decide to make mocked logic and use some package to mimic calls but our modules are de-coupled making it easier to maintain &amp; much more predictable to test.</p><h3>Explain it like I’m 9</h3><p>Always put toys in different appropriate boxes, it is sometimes annoying but we can find/change/rely on/use them better tomorrow.</p><p>Go clean your room <strong>now</strong>.</p><h3>Note/Disclaimer</h3><p>100% code coverage does not guarantee no bugs or correctness.<br>For more reading on that check out:<br><a href="https://stackoverflow.com/a/195054/5064324">This answer</a> (not by me) on SO.<br><a href="https://www.softwaretestinghelp.com/code-coverage-tutorial">This read</a> has some good coin dropping moments, one of them is very relevant to this disclaimer:<br>Test Coverage = (Executed Test cases/Total Test cases) * 100<br>Code Coverage = (number of lines of code executed/ total number of lines of code)* 100</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d8909080f9dd" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>