<?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 Giovanni Pinto on Medium]]></title>
        <description><![CDATA[Stories by Giovanni Pinto on Medium]]></description>
        <link>https://medium.com/@giovannipinto?source=rss-b174b1fa8424------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*UONpdN9UvDOObx0K.</url>
            <title>Stories by Giovanni Pinto on Medium</title>
            <link>https://medium.com/@giovannipinto?source=rss-b174b1fa8424------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 21:45:22 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@giovannipinto/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[Don’t mock what you don’t own: a real world scenario]]></title>
            <link>https://medium.com/@giovannipinto/dont-mock-what-you-don-t-own-a-real-world-scenario-267b06d219ca?source=rss-b174b1fa8424------2</link>
            <guid isPermaLink="false">https://medium.com/p/267b06d219ca</guid>
            <category><![CDATA[xunit]]></category>
            <category><![CDATA[mock]]></category>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[tdd]]></category>
            <dc:creator><![CDATA[Giovanni Pinto]]></dc:creator>
            <pubDate>Wed, 21 Feb 2018 11:10:36 GMT</pubDate>
            <atom:updated>2018-02-21T11:10:36.274Z</atom:updated>
            <cc:license>http://creativecommons.org/licenses/by/4.0/</cc:license>
            <content:encoded><![CDATA[<p>If you practice TDD you are surely familiar with mocks and stubs and you may have stumbled upon the need to fake an external dependency, most commonly a third party library. I am not here to explain why <a href="https://davesquared.net/2011/04/dont-mock-types-you-dont-own.html">you</a> <a href="https://github.com/testdouble/contributing-tests/wiki/Don&#39;t-mock-what-you-don&#39;t-own">shouldn’t</a> <a href="https://8thlight.com/blog/eric-smith/2011/10/27/thats-not-yours.html">mock </a>types you don’t own but rather to provide an example of how to apply the most common solutions.</p><p>In this scenario I need to implement a controller (BotActionController) that takes as input a text message written in natural language and uses a <strong>third party library</strong> made by Dialogflow, <strong>ApiAi</strong>, to process that message. After the message is recognized the controller needs to call an IActionService.Handlemethod to act on it. Let’s see how it should work:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/995473da3c3f948cfc75096ccf276052/href">https://medium.com/media/995473da3c3f948cfc75096ccf276052/href</a></iframe><p>Reading the tests makes straightforward to understand what the BotActionController class implementation looks like and what should it do:</p><ul><li>it has an ApiAi and an IActionService dependencies;</li><li>it has an OnMessage method that calls the ApiAi.TextRequest method to process the user input written in natural language;</li><li>given a message, if it’s not recognizable, throw an UnrecognizableIntentException ;</li><li>given a message, if it’s recognizable, call the IActionService.Handle method with the AiResponse returned by ApiAi.TextRequest .</li></ul><p>As you can see, the BotActionController class has a direct dependency on <strong>ApiAi </strong>, a <strong>third party library</strong>. That require to stub the library itself and pass it to the controller constructor to be able to fake the ApiAi.TextRequest call. What if we cannot just instantiate an ApiAi object? In fact, we can’t:</p><pre>Castle.DynamicProxy.InvalidProxyConstructorArgumentsException : Can not instantiate proxy of class: ApiAiSDK.ApiAi.Could not find a parameterless constructor.</pre><p>The ApiAI class requires a configuration object for the constructor. We can, of course, make one up but that will not solve anything and we’ll probably consequently need a waterfall of stubs. <strong>We are trying to force a fake behavior to code we have zero control over. </strong>Sometimes you get lucky and go on without even noticing the huge mistake you’re making. Sometimes your third party library needs a valid api key and has a limited paid daily quota that you can exceed just by continuously and automatically running tests.</p><p>When you absolutely have to stub an external library to test your unit of work you probably have some <strong>bad code design</strong> somewhere. In this case that design flaw was really easy to spot. The controller violates the <a href="https://en.wikipedia.org/wiki/Open/closed_principle">Open-Closed principle</a> since it directly depends on ApiAi . Imagine that someday you want to use a newer version of the library, or an entirely different one: you’ll need to rewrite the controller to remove the old dependency, add the new one and implement the different provided APIs, breaking all the tests (and requiring new ones). That doesn’t even make sense in a TDD environment. The controller must instead be open to extension, but close to modification. The direct dependency from a third party library should be wrapped inside a local service. Let’s do this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e9c5aa9cc7a042fdf609c4268377aea5/href">https://medium.com/media/e9c5aa9cc7a042fdf609c4268377aea5/href</a></iframe><p>Et voilà. You <em>may</em> have noticed that I didn’t include the controller code itself. That’s because it’s not really required and, if tests are good enough, they should be sufficient to understand what the system under test really does. After all that’s also what good TDD is about, right?</p><h4>You just moved the problem to the IAiService implementation</h4><p>Let’s see what the ApiAiService looks like. As usual, we start with the first tests:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7a16e890729a6afe3547a87b85cfaa25/href">https://medium.com/media/7a16e890729a6afe3547a87b85cfaa25/href</a></iframe><p>The ApiAiService implements IAiService but also expose an addition method: DoLanguageProcessing This method is not required by the interface but it’s useful because it abstract the third party API call and allows for testing the implementation. Sometimes it’s useful, if not necessary, to provide overridable methods only for the sake of be able to mock them. Quoting Roy Osherove:</p><blockquote>Some people feel that opening up the design to make it more testable is a bad thing because it hurts the object-oriented principles the design is based on. I can wholeheartedly say to those people, “Don’t be silly.” Object-oriented techniques are there to enforce constraints on the end user of the API (the end user being the programmer who will use your object model) so that the object model is used properly and is protected from unintended usage. […] When you write unit tests for your code, you’re adding another end user (the test) to the object model. That end user is just as important as the original one, but it has different goals when using the model. The test has specific requirements from the object model that seem to defy the basic logic behind a couple of object oriented principles, mainly encapsulation. […] The problem is that the second end user of the API, the test, needs these external dependencies as a feature in the code.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=267b06d219ca" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ES7 async error handling: do it right or die]]></title>
            <link>https://medium.com/@giovannipinto/async-error-handling-forced-to-do-it-right-2817cf9e8b43?source=rss-b174b1fa8424------2</link>
            <guid isPermaLink="false">https://medium.com/p/2817cf9e8b43</guid>
            <category><![CDATA[async-functions]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[error-handling]]></category>
            <dc:creator><![CDATA[Giovanni Pinto]]></dc:creator>
            <pubDate>Tue, 27 Jun 2017 08:55:19 GMT</pubDate>
            <atom:updated>2017-06-27T08:55:59.224Z</atom:updated>
            <cc:license>https://creativecommons.org/licenses/by-nc-nd/4.0/</cc:license>
            <content:encoded><![CDATA[<p>Javascript asynchronous execution is one of Node.js (and the browser) strongest feature but can also be annoying and error prone. Promises are not the most elegant solution and often add lots of ceremony to the party. I personally hate promise chaining since it produce unreadable code and every callback must be tightly coupled with the previous one.</p><p>Fortunately ES7 came to the rescue and introduced a well know feature to C# developers: async functions. How does they work? Well, in ES7, they’re basically syntactic sugar on top of ES2015 Promise. An async function always returns a Promise and it automatically cast a value to a Promise if needed. For example, writing</p><pre>function returnPromise() {<br>  return Promise.resolve(true)<br>}<br>returnPromise().then((v) =&gt; console.log(v))</pre><p>is the same as writing</p><pre>async function returnAsync() {<br>  return true<br>}<br>const v = await returnAsync()<br>console.log(v)</pre><p>In fact, you could do returnAsync().then((v) =&gt; console.log(v))The two functions have the same behaviour.</p><p>That’s really straightforward. What if we throw some errors? Let’s try with the following setup:</p><pre>async function Main() {<br>  async function asyncThrows(id) {<br>    return new Promise((res, rej) =&gt; {<br>      console.log(`ASYNC ERROR ${id}`)<br>      throw `ASYNC ERROR ${id}`<br>    })<br>  }<br>  try {<br>    // ASYNC ERROR 1<br>    // ASYNC ERROR 1 CAUGHT<br>    // OK<br>    await asyncThrows(1)<br>  }<br>  catch(e) {<br>    console.log(e, &#39;CAUGHT&#39;)<br>    return &#39;OK&#39;<br>  }<br>  return &#39;OK&#39;<br>}</pre><pre>Main()<br>  .then((r) =&gt; console.log(r))<br>  .catch((e) =&gt; console.error(e))</pre><p>Running the code gives the following output:</p><pre>ASYNC ERROR 1<br>ASYNC ERROR 1 CAUGHT<br>OK</pre><p>The asyncThrowsfunction is awaited and the thrown exception is correctly caught. The code basically behave like synchronous code, pretty nice right?</p><p>Let’s remove the awaitkeyword and see what happen:</p><pre>ASYNC ERROR 1<br>OK<br>(node:4804) UnhandledPromiseRejectionWarning: [..]</pre><p>The exception is thrown but is never caught. Node informs us that</p><blockquote>Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.</blockquote><p>Sounds really bad. In the future that code will just crash the software. What’s happening? The asyncfunction call doesn’t block code execution, so the next instruction after the asyncThrowscall will be the return &#39;OK&#39;statement. The exception is thrown only after, when there’s no one to catch it.</p><p>But wait, there’s more.</p><p>Let’s try with 2 awaited async calls</p><pre>// ASYNC ERROR 1<br>// ASYNC ERROR 1 CAUGHT<br>// OK<br>let a = await asyncThrows(1)<br>let b = await asyncThrows(2)</pre><p>Everything’s looking good, and the code behave exactly like expected. That’s basically a synchronous program, since the second async call must await the first one to be executed. The error is thrown and the control flow jumps to the catchblock.</p><p>You should be aware that the above code doesn’t take fully advantage of asynchronous programming: you will probably want to execute the two functions parallelly and not sequentially. Let’s do it!</p><p>Now the two asyncfunctions are parallelly executed:</p><pre>// ASYNC ERROR 1<br>// ASYNC ERROR 2<br>// ASYNC ERROR 1 CAUGHT<br>// OK<br>// (node:12988) UnhandledPromiseRejectionWarning: [...]<br>let a = asyncThrows(1)<br>let b = asyncThrows(2)<br>await a + await b</pre><p>There is a caught error and a unhandled one. The 2 asynchronous calls are parallelly executed so, when the first is caught, the flow breaks and the catch block is executed. The second asynchronous call is still running and throwing an exception that cannot be caught anymore. That mistake will crash your Node program and probably gives you a really bad headache during debugging.</p><p>So, what’s the right way to do it? The answer is simple. Every awaited function should have his own catchblock.</p><pre>// OK<br>let a = asyncThrows()<br>let b = asyncThrows()<br>try { await a } catch(e) {}<br>try { await b } catch(e) {}</pre><p>Async functions are an awesome addition to ES7. You can write synchronous code that runs asynchronously. They make our code more readable, elegant and easier to debug but they also introduce some subtle way of destroying your software, so they must be handled extra carefully.</p><p>When they will be implemented? Well, they’re <a href="http://kangax.github.io/compat-table/es2016plus/#test-async_functions">basically already there</a> and Node ≥7.10.0 <a href="http://node.green/#ES2017-features-async-functions">fully supports them</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2817cf9e8b43" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>