<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Meinert Schwartau</title>
    <description>The latest articles on DEV Community by Meinert Schwartau (@mschwartau).</description>
    <link>https://dev.to/mschwartau</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F279704%2F7bc152ab-6e86-45c0-880e-b18e58c62e9f.jpg</url>
      <title>DEV Community: Meinert Schwartau</title>
      <link>https://dev.to/mschwartau</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/mschwartau"/>
    <language>en</language>
    <item>
      <title>Why TypeScripts never type is super useful</title>
      <dc:creator>Meinert Schwartau</dc:creator>
      <pubDate>Sat, 12 Feb 2022 07:29:55 +0000</pubDate>
      <link>https://dev.to/mschwartau/why-typescripts-never-type-is-super-useful-1pa2</link>
      <guid>https://dev.to/mschwartau/why-typescripts-never-type-is-super-useful-1pa2</guid>
      <description>&lt;p&gt;At first glance, the &lt;a href="https://www.typescriptlang.org/docs/handbook/2/narrowing.html#the-never-type"&gt;never&lt;/a&gt; type  does not sound very useful for everyday coding. But actually, the following property of the type comes in very handy:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;[…] The never type is assignable to every type; however, no type is assignable to never (except never itself) […]&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;With a small hack, this can be used to increase the type safety of a code base with no risk of breaking existing code and without any runtime overhead.&lt;/p&gt;

&lt;h2&gt;
  
  
  Problem
&lt;/h2&gt;

&lt;p&gt;Maybe you have lots of places in your code, where you use some data like an userId, an email, a firstname or whatever. You could just use the standard types for that (string and so on):&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight typescript"&gt;&lt;code&gt;&lt;span class="nx"&gt;getUserByUserId&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;userId&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kr"&gt;string&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt; &lt;span class="nx"&gt;Observable&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nx"&gt;User&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;But this approach has some problems:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;You could accidentally call this method with the wrong parameters, e.g. with an email instead of an userId.&lt;/li&gt;
&lt;li&gt;This error would only be found during runtime, not compile time.&lt;/li&gt;
&lt;li&gt;Sometimes during &lt;a href="https://refactoring.com/"&gt;refactoring&lt;/a&gt; your codebase you want to find all places where a field like a userId is used.  This is very hard if it has a simple type, but very easy if it has a custom type.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Solution
&lt;/h2&gt;

&lt;p&gt;The problems described above disappears, if we don’t use the built in string type but create a custom type for the userId:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight typescript"&gt;&lt;code&gt;&lt;span class="nx"&gt;getUserByUserId&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;userId&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nx"&gt;UserId&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt; &lt;span class="nx"&gt;Observable&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nx"&gt;User&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now it’s easy to find all places where this UserId type is used. And is not possible to accidentally call this method with an email because the latter has another type.&lt;/p&gt;

&lt;h2&gt;
  
  
  Where does the never type come into play?
&lt;/h2&gt;

&lt;p&gt;How to implement this new UserId type? The naive solution does not work out:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight typescript"&gt;&lt;code&gt;&lt;span class="k"&gt;export&lt;/span&gt; &lt;span class="kd"&gt;type&lt;/span&gt; &lt;span class="nx"&gt;UserId&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kr"&gt;string&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="nx"&gt;getUserByUserId&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;some string&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt; &lt;span class="c1"&gt;// no compiler errors here :-(&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The problem is that for typescript &lt;code&gt;string&lt;/code&gt; and &lt;code&gt;UserId&lt;/code&gt; are the compatible (because at runtime they are the same). We need to change the &lt;code&gt;UserId&lt;/code&gt; type, so that they are (at least at compile time) not compatible anymore in order to get compiler errors. We could create a new &lt;code&gt;UserId&lt;/code&gt; class to achieve that. But this might break existing code, which you forgot to migrate and which still expects to get a string, at runtime. But with the help of the &lt;a href="https://www.typescriptlang.org/docs/handbook/2/narrowing.html#the-never-type"&gt;never&lt;/a&gt; type you can define this new type like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight typescript"&gt;&lt;code&gt;&lt;span class="k"&gt;export&lt;/span&gt; &lt;span class="kd"&gt;type&lt;/span&gt; &lt;span class="nx"&gt;UserId&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kr"&gt;string&lt;/span&gt; &lt;span class="o"&gt;&amp;amp;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="c1"&gt;// name of the following field needs to be unique. If it &lt;/span&gt;
  &lt;span class="c1"&gt;// were not unique and you would reuse it for another type, &lt;/span&gt;
  &lt;span class="c1"&gt;// both types would be compatible!&lt;/span&gt;
  &lt;span class="na"&gt;____doesNotMatter_UserId&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nx"&gt;never&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;};&lt;/span&gt;

&lt;span class="c1"&gt;// you can't create new values of type UserId by hand, because &lt;/span&gt;
&lt;span class="c1"&gt;// you cannot assign anything to never. so you'll need this&lt;/span&gt;
&lt;span class="c1"&gt;// converter function:&lt;/span&gt;
&lt;span class="k"&gt;export&lt;/span&gt; &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;toUserId&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;userId&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kr"&gt;string&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="nx"&gt;userId&lt;/span&gt; &lt;span class="k"&gt;as&lt;/span&gt; &lt;span class="nx"&gt;UserId&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This solution has some nice characteristics:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;It’s not possible to assign string values to variables of type &lt;code&gt;UserId&lt;/code&gt; anymore, because they are missing the &lt;code&gt;____doesNotMatter_UserId&lt;/code&gt; attribute. The compiler will complain about that if you give it a try.&lt;/li&gt;
&lt;li&gt;To convert a string to the new type, you need to cast latter to it. Creating a value of this type another way is impossible because you cannot assign anything to never. Normally you’ll have to do this in your tests, during url parameter parsing or (maybe) when converting your &lt;a href="https://en.wikipedia.org/wiki/Representational_state_transfer"&gt;REST&lt;/a&gt; resources.&lt;/li&gt;
&lt;li&gt;I write a factory method like this for the casting normally: export &lt;code&gt;const toUserId = (userId: string) =&amp;gt; userId as UserId;&lt;/code&gt;. This factory method is nice, because now you can search for the places where &lt;code&gt;UserId&lt;/code&gt; values are created.&lt;/li&gt;
&lt;li&gt;A big advantage is that this trick does not change the runtime behavior of your code. The sanity check is done only during compile time. Because it’s still a &lt;code&gt;string&lt;/code&gt; during runtime, nothing bad will happen if you forget to migrate a place in your code (and which expects a &lt;code&gt;string&lt;/code&gt; in our example above).&lt;/li&gt;
&lt;li&gt;It can be used for other types too, not only strings.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;So let’s see this type in action:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight typescript"&gt;&lt;code&gt;&lt;span class="k"&gt;export&lt;/span&gt; &lt;span class="kd"&gt;type&lt;/span&gt; &lt;span class="nx"&gt;UserId&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kr"&gt;string&lt;/span&gt; &lt;span class="o"&gt;&amp;amp;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="c1"&gt;// name of the following field needs to be unique. If it &lt;/span&gt;
  &lt;span class="c1"&gt;// were not unique and you would reuse it for another type, &lt;/span&gt;
  &lt;span class="c1"&gt;// both types would be compatible!&lt;/span&gt;
  &lt;span class="na"&gt;____doesNotMatter_UserId&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nx"&gt;never&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;};&lt;/span&gt;

&lt;span class="c1"&gt;// you can't create new values of type UserId, so you'll need &lt;/span&gt;
&lt;span class="c1"&gt;// this converter function:&lt;/span&gt;
&lt;span class="k"&gt;export&lt;/span&gt; &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;toUserId&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;userId&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kr"&gt;string&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="nx"&gt;userId&lt;/span&gt; &lt;span class="k"&gt;as&lt;/span&gt; &lt;span class="nx"&gt;UserId&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="c1"&gt;// an example function which expects our new type&lt;/span&gt;
&lt;span class="k"&gt;export&lt;/span&gt; &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;isSuperUser&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;userId&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nx"&gt;UserId&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; 
                                   &lt;span class="nx"&gt;userId&lt;/span&gt; &lt;span class="o"&gt;===&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;superuser&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="c1"&gt;// a function we forgot to migrate and which still get's a string&lt;/span&gt;
&lt;span class="k"&gt;export&lt;/span&gt; &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;unmigratedIsGuestUserFn&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;userId&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kr"&gt;string&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; 
                                       &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="nx"&gt;userId&lt;/span&gt; &lt;span class="o"&gt;===&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;guest&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="c1"&gt;// some examples&lt;/span&gt;
&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;aUserId&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nx"&gt;UserId&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;toUserId&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;u1111&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

&lt;span class="nx"&gt;isSuperUser&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;aUserId&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt; &lt;span class="c1"&gt;// works and return false&lt;/span&gt;

&lt;span class="nx"&gt;isSuperUser&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;superuser&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt; &lt;span class="c1"&gt;// Compile time error: Argument of type&lt;/span&gt;
 &lt;span class="c1"&gt;// 'string' is not assignable to parameter of type 'UserId'. &lt;/span&gt;
 &lt;span class="c1"&gt;// Type 'string' is not assignable to type '{ &lt;/span&gt;
 &lt;span class="c1"&gt;// ____doesNotMatter_UserId: never; }'.&lt;/span&gt;

&lt;span class="nx"&gt;unmigratedIsGuestUserFn&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;aUserId&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt; &lt;span class="c1"&gt;// no compile time errors &lt;/span&gt;
&lt;span class="c1"&gt;// because at runtime our new type is just a string :-). &lt;/span&gt;
&lt;span class="c1"&gt;// So this type refactoring is very safe&lt;/span&gt;

&lt;span class="c1"&gt;// warning - don't reuse your ___doesNotMatter attributes:&lt;/span&gt;
&lt;span class="k"&gt;export&lt;/span&gt; &lt;span class="kd"&gt;type&lt;/span&gt; &lt;span class="nx"&gt;Email&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kr"&gt;string&lt;/span&gt; &lt;span class="o"&gt;&amp;amp;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="c1"&gt;// DO NOT DO THIS:&lt;/span&gt;
  &lt;span class="na"&gt;____doesNotMatter_UserId&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nx"&gt;never&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;};&lt;/span&gt;

&lt;span class="c1"&gt;//  Email and UserId are compatible because they have the same&lt;/span&gt;
&lt;span class="c1"&gt;//  signature, so we don't get compiler errors here:&lt;/span&gt;
&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;email&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nx"&gt;Email&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;toUserId&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;superuser&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="nx"&gt;isSuperUser&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;email&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

&lt;span class="c1"&gt;// So -&amp;gt; always use unique names for these &lt;/span&gt;
&lt;span class="c1"&gt;// ____doesNotMatter attributes&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;I found this approach to be especially useful, if values of a type are used in many places but are created only in few cases. For instance, I expect that I would only need to call the  factory function toUserId to convert strings to the new UserId type during:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;converting a rest resource to our domain model (should be one place)&lt;/li&gt;
&lt;li&gt;parsing a url parameter (should be few places)&lt;/li&gt;
&lt;li&gt;in tests
But there might be lots of places, were a function gets a value our new type as parameter and just passes it around. So through this approach I get the former described benefits of a richer type model.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Acknowledgements
&lt;/h2&gt;

&lt;p&gt;I learned about this trick during an &lt;a href="https://angular.io/"&gt;Angular&lt;/a&gt; meetup held by Thiele Leonard in 2020. I found a &lt;a href="https://www.youtube.com/watch?v=9yd0iha2F6M"&gt;recording of the same „Angular at scale“ talk&lt;/a&gt; hold on a different occasion, which contains many more tricks, so have a look.&lt;/p&gt;

</description>
      <category>typescript</category>
      <category>functional</category>
      <category>webdev</category>
      <category>refactorit</category>
    </item>
    <item>
      <title>Functional programming + DDD = ❤</title>
      <dc:creator>Meinert Schwartau</dc:creator>
      <pubDate>Thu, 25 Feb 2021 18:13:08 +0000</pubDate>
      <link>https://dev.to/mschwartau/functional-programming-ddd-29nn</link>
      <guid>https://dev.to/mschwartau/functional-programming-ddd-29nn</guid>
      <description>&lt;p&gt;Using &lt;a href="https://en.wikipedia.org/wiki/Domain-driven_design"&gt;Domain Driven Design&lt;/a&gt; (in short DDD) it is common to follow the principles of &lt;a href="https://alistair.cockburn.us/hexagonal-architecture/"&gt;hexagonal&lt;/a&gt;, &lt;a href="https://jeffreypalermo.com/2008/07/the-onion-architecture-part-1/"&gt;onion&lt;/a&gt; or &lt;a href="https://alistair.cockburn.us/hexagonal-architecture/"&gt;ports and adapters&lt;/a&gt; architecture. This means that your domain logic should be independent from how it is connected to the outside world. For instance you shouldn’t see any messaging or &lt;a href="https://en.wikipedia.org/wiki/Representational_state_transfer"&gt;REST&lt;/a&gt; specific logic in domain logic.  Even though this sounds easy, in past projects I came across loads of messy code when connecting the outside world (like a REST Endpoint) with the domain. Doing it in a more &lt;a href="https://en.wikipedia.org/wiki/Functional_programming"&gt;functional way&lt;/a&gt; using functions solves a lot of problems and leads to cleaner code. I want to share this in this blog post.&lt;/p&gt;

&lt;h1&gt;
  
  
  The problem
&lt;/h1&gt;

&lt;p&gt;Data always has to be mapped. There often exists something like the following:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Especially if your are using java and &lt;a href="https://en.wikipedia.org/wiki/Jakarta_Persistence"&gt;JPA&lt;/a&gt; you have to differentiate between creating new objects or updating existing ones. This is necessary because in the same &lt;a href="https://en.wikipedia.org/wiki/Jakarta_Persistence"&gt;JPA&lt;/a&gt; context there should exist only one object with the same id. &lt;/li&gt;
&lt;li&gt;When your domain object has a list of other objects (e.g. your order may have a list of orderpositions), you don’t want to throw away the whole list and create a new one which may lead to lots of deletes and updates just because the customer wanted to increase the amount. Instead, only the relevant orderposition entry should be updated in the database and the others left unchanged.&lt;/li&gt;
&lt;li&gt;When your domain object has a list of other objects (e.g. your order may have a list of orderpositions), you don’t want to throw away the whole list and create a new one which may lead to lots of deletes and updates just because the customer wanted to increase the amount. Instead, only the relevant orderposition entry should be updated in the database and the others left unchanged.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;So what’s the problem? The problem (at least in Java) is how to convert between your adapter model (REST resource or message) to your domain model. Having to read the domain object from the database in a class which converts the REST resource to your domain object is very cumbersome. Furthermore you may have duplicated code in other parts of your code, e.g.  where messages are parsed and converted to your domain object. Last but not least I normally don’t want to care whether the objects exist or not when I write such converters. The domain logic should handle that. &lt;/p&gt;

&lt;h1&gt;
  
  
  Some messy attempts
&lt;/h1&gt;

&lt;p&gt;In the past I saw the following approaches:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Writing intermediate objects. Instead of mapping something like your REST Resource to your domain object, you map your REST object to an intermediate object and pass this to your business logic. The intermediate object can be created by different adapters. This leads to writing lots of mapper code and you are unable to use the fancy domain methods which you have written. Furthermore naming this intermediate objects is often hard which is a bad sign.&lt;/li&gt;
&lt;li&gt;You pass both, the domain object and the REST Resource, to your converter. This leads to an ugly / more complicated interface of your services.&lt;/li&gt;
&lt;li&gt;During the transformation, the converters lookup the domain objects in the database itself to handle the case of updating versus inserting them. This leads to the disadvantages mentioned before. In some cases the code is not too bad, but can become very ugly. At least this lookup code may be duplicated in different converters.&lt;/li&gt;
&lt;/ul&gt;

&lt;h1&gt;
  
  
  The better solution
&lt;/h1&gt;

&lt;p&gt;The solution is simple, just pass functions. Your converters in the different adapters don’t create or update the domain object immediately. Instead they return a function which expects the domain object as input and updates it. This function is then passed to the domain logic which then applies it and hence updates the domain object. Such a converter may look like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// these lombok annotations if you don't know them are generating 
// gettes and builder methods ...
@Builder 
@Getter 
public class CatalogArticleUpdate {
     // the functions which update the domain object, may never be applied!
     // You create an own interface which extends Function&amp;lt;&amp;gt; if you like
     private final Function&amp;lt;Article, Article&amp;gt; articleUpdate;
     // some other fields which the domain services needs to figure out to which 
     // domain object, the update needs to be applied  
     private final Catalogue catalogue;  
     private final ExternalDocId externalDocId;  
}


public class CatalogueAricleChangedMessageConverter {

    // this method does not convert the message immediately but instead returns
    // a function which does this when it is applied
    public CatalogArticleUpdate convert(final CatalogueAricleChangedMessage message) {        
        return CatalogArticleUpdate.builder()
                .catalogue(Catalogue.valueOf(message.getCatalogueId())) 
                .externalDocId(ExternalDocId.valueOf(message.getDocId()))
                .articleUpdate(article -&amp;gt; {
                    // if the domain service calls this method, it provides the domain 
                    // object (see article parameter) so we don't need to lookup 
                    // it ourselves :-)
                    article.updateTitle(ArticleTitle.valueOf(message.getTitle())):
                    article.updateCataloguePrices(convertePrices(message));
                    // much more updates ....
                     return article;
                })
                .build();
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This approach has several advantages:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;More business logic can be put in the domain layer.&lt;/li&gt;
&lt;li&gt;The domain layer can even decide to ignore the update. In that case the update function is not executed. For instance, in my current project we get a lot of price and metadata updates from a catalogue which contains lots of articles. For our service, only a small amount of these updates are relevant. So the domain service may decide to ignore an update. Or it may decide to create a new one. Or it may decide to update several domain objects in the database because there exist different ones for different tenants. The point is, this logic how to apply the update belongs into the domain layer&lt;/li&gt;
&lt;li&gt;Code in the domain layer may be reused. The example above creates a CatalogArticleUpdate for a message. A batch job, for instance, may load updates via feed and converts the result from the feed to an instance of CatalogArticleUpdate and calling the same domain service. &lt;/li&gt;
&lt;li&gt;No unnecessary intermediate objects are needed so there is no need to write mapping code for them.&lt;/li&gt;
&lt;li&gt;Very flexible, all of your fancy domain methods can be used.&lt;/li&gt;
&lt;li&gt;Easy to test, just apply the function to something.&lt;/li&gt;
&lt;li&gt;The resulting code is not so cumbersome.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;In my current project we have used this style to just return functions instead of doing the conversion in the converters immediately for some time and it turned out nicely.  &lt;/p&gt;

</description>
      <category>functional</category>
      <category>codequality</category>
    </item>
    <item>
      <title>Troubleshooting karma (node) performance problems</title>
      <dc:creator>Meinert Schwartau</dc:creator>
      <pubDate>Mon, 25 Nov 2019 20:25:03 +0000</pubDate>
      <link>https://dev.to/mschwartau/troubleshooting-karma-node-performance-problems-3a0i</link>
      <guid>https://dev.to/mschwartau/troubleshooting-karma-node-performance-problems-3a0i</guid>
      <description>&lt;p&gt;After some months of nothing but backend development I started to work on my customers &lt;a href="https://angular.io/" rel="noopener noreferrer"&gt;Angular&lt;/a&gt; frontend application again. I noticed that starting a single &lt;a href="https://karma-runner.github.io/" rel="noopener noreferrer"&gt;karma&lt;/a&gt; test took way longer than it used to be. A simple test for a pure function in headless chrome took about half a minute, in which the actual test only took some milliseconds. That was really annoying, because in my current refactoring task I have to execute lots of tests very often. Searching, browsing the &lt;a href="https://karma-runner.github.io/" rel="noopener noreferrer"&gt;karma&lt;/a&gt; issues and so on didn’t help, so I want to describe, how I found out what has been causing the problems. &lt;/p&gt;

&lt;h2&gt;
  
  
  1. Find out  where the time is spend
&lt;/h2&gt;

&lt;p&gt;At first it is necessary to figure out, where the time is spend. Fortunately &lt;a href="https://nodejs.org/" rel="noopener noreferrer"&gt;node&lt;/a&gt; has a really good built in profiler. Their &lt;a href="https://nodejs.org/es/docs/guides/simple-profiling/" rel="noopener noreferrer"&gt;simple profiling guide&lt;/a&gt; is quite good and describes how to find out the problematic calls. I won’t repeat its content here but assume that you read it or are familiar with profiling. &lt;/p&gt;

&lt;p&gt;So I followed their guide and added the &lt;code&gt;--prof&lt;/code&gt; flag to the &lt;a href="https://nodejs.org/" rel="noopener noreferrer"&gt;node&lt;/a&gt; options (in intellij this option can be added in the run configuration):&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fblog.schwartau.hamburg%2Fwp-content%2Fuploads%2F2019%2F11%2FBildschirmfoto-2019-11-22-um-20.56.50-1536x1036.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fblog.schwartau.hamburg%2Fwp-content%2Fuploads%2F2019%2F11%2FBildschirmfoto-2019-11-22-um-20.56.50-1536x1036.png" alt="IntelliJ Run Configuration"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;If you are using the command line, you could add it there too:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;node --prof ./node_modules/@angular/cli/bin/ng test ...
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;After execution of the test a &lt;code&gt;isolate-&amp;lt;some integer&amp;gt;-v8.log&lt;/code&gt; file is created in the project folder. This can be feed into node to create a report from it:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;❯ node --prof-process ./isolate-0x10264e000-v8.log
...

ticks parent name
1327 44.1% T _fcntl$NOCANCEL

728 24.2% T v8::internal::IncrementalMarking::Step(unsigned long, 
v8::internal::IncrementalMarking::CompletionAction, v8::internal::StepOrigin, 
...
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The &lt;a href="https://nodejs.org/es/docs/guides/simple-profiling/" rel="noopener noreferrer"&gt;simple profiling guide&lt;/a&gt; in the documentation gave me some tips how to interpret this output. But basically we see here that 44,1% of the time is spend in a C++ method called &lt;code&gt;_fcntl$NOCANCEL&lt;/code&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  2. What is the method doing?
&lt;/h2&gt;

&lt;p&gt;Now we need to find out what this heavy load method is doing. Fortunately, this is a very specific search term, so using Google I found a stack overflow answer which said that &lt;code&gt;_fcntl$NOCANCEL&lt;/code&gt; is related to file system operations. &lt;/p&gt;

&lt;h2&gt;
  
  
  3. Why is the method being called so often?
&lt;/h2&gt;

&lt;p&gt;Such a simple test shouldn’t lead to lots of file system operations. Now we need to find out which files are accessed so heavily. Unfortunately the &lt;a href="https://karma-runner.github.io/" rel="noopener noreferrer"&gt;karma&lt;/a&gt; logging isn’t really helpful and we don’t know if we can trust it. Fortunately for linux there exists &lt;a href="https://strace.io/" rel="noopener noreferrer"&gt;strace&lt;/a&gt; and for mac os (which I’m using) there exist &lt;a href="http://dtrace.org/blogs/about/" rel="noopener noreferrer"&gt;dtrace&lt;/a&gt; and dtruss. Basically these programs just show you the system calls your program executes and their parameters. Hereby you don’t have to rely on the logging of the program but you can see what is really going on. This is not a &lt;a href="https://strace.io/" rel="noopener noreferrer"&gt;strace&lt;/a&gt; or &lt;a href="http://dtrace.org/blogs/about/" rel="noopener noreferrer"&gt;dtrace&lt;/a&gt; guide, but there exist a lot of how to guides out there (like &lt;a href="https://8thlight.com/blog/colin-jones/2015/11/06/dtrace-even-better-than-strace-for-osx.html" rel="noopener noreferrer"&gt;this one for dtrace / dtruss for mac os&lt;/a&gt;). &lt;/p&gt;

&lt;p&gt;There are two dtruss options which we will be using:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;-f &amp;lt;command&amp;gt;&lt;/code&gt; When this option is provided, dtruss follows child processes. We’ll use this option to start the &lt;a href="https://nodejs.org/" rel="noopener noreferrer"&gt;node&lt;/a&gt; process. Even when the &lt;a href="https://nodejs.org/" rel="noopener noreferrer"&gt;node&lt;/a&gt; process starts child processes, we’ll see the system calls they execute.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;-t &amp;lt;syscall&amp;gt;&lt;/code&gt; We know that file system operations slow down the test execution. If we would log all system calls our process is executing, we would probably see nothing. So we’ll use this flag to only examine the problematic file &lt;code&gt;open_nocancel&lt;/code&gt; system call.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;To only execute the single test, we annotate it with &lt;a href="https://jasmine.github.io/2.1/focused_specs.html" rel="noopener noreferrer"&gt;fdescribe&lt;/a&gt;. Afterwards we start the test via dtruss like this and see at lot of accesses to &lt;a href="https://sass-lang.com/" rel="noopener noreferrer"&gt;scss&lt;/a&gt; files (we even see which are accessed):&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;❯ sudo dtruss -t open_nocancel -f node ./node_modules/@angular/cli/bin/ng test lisa
# ...
82846/0x11de5b: open_nocancel(".../generated_material_theme.scss\0", 0x0, 0x1B6) = 29 0
# ....
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Other than that, only the test files are accessed. So our stylesheet &lt;a href="https://sass-lang.com/" rel="noopener noreferrer"&gt;scss&lt;/a&gt; files seems to be the cause for the problem. That the tests even needs the &lt;a href="https://sass-lang.com/" rel="noopener noreferrer"&gt;scss&lt;/a&gt; Stylesheet files is unexpected, because our unit test just tests the code and the html template. So there ist no reason why the Saas &lt;a href="https://sass-lang.com/" rel="noopener noreferrer"&gt;scss&lt;/a&gt; files should be compiled.&lt;/p&gt;

&lt;h2&gt;
  
  
  4. Verification
&lt;/h2&gt;

&lt;p&gt;Now we need to test, if the performance will be faster without these Saas &lt;a href="https://sass-lang.com/" rel="noopener noreferrer"&gt;scss&lt;/a&gt; files. Even though they aren’t needed by the tests they are referenced by the &lt;a href="https://angular.io/" rel="noopener noreferrer"&gt;Angular&lt;/a&gt; components so we can’t simply delete them. The fastest way to verify our hypothesis that they are causing the problems is to overwrite them with empty files. This can be done by using the following bash command:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;find . -iname "*.scss" -exec sh -c 'echo {}' \;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now I compared the execution time of the tests:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Before with the original scss

&lt;ul&gt;
&lt;li&gt;Executing all tests via command line took 6min and 20 secs&lt;/li&gt;
&lt;li&gt;Executing a single test via Intellij took 20 secs&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;

&lt;li&gt;With empty scss files

&lt;ul&gt;
&lt;li&gt;Executing all tests via command line took 2min and 30 secs&lt;/li&gt;
&lt;li&gt;Executing a single test via Intellij took 6 secs&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;

&lt;/ul&gt;

&lt;p&gt;So it is three times faster. The single test execution in Intellij is acceptable now.&lt;/p&gt;

&lt;h2&gt;
  
  
  5. The quick fix
&lt;/h2&gt;

&lt;p&gt;I already spent too much time on the issue. As a quick fix I wrote one function which just overwrites the &lt;a href="https://sass-lang.com/" rel="noopener noreferrer"&gt;scss&lt;/a&gt; files so that they are empty. And another one to restore the &lt;a href="https://sass-lang.com/" rel="noopener noreferrer"&gt;scss&lt;/a&gt; files, because I need them if I want to run the &lt;a href="https://angular.io/" rel="noopener noreferrer"&gt;Angular&lt;/a&gt; application. I added these functions to my .zshrc (or .bashrc if you are using bash instead of zsh) so that I can execute them in my terminal:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function scss_empty {
  local scssFileName
  for scssFileName in `find . -iname "*.scss"`
  do
    local newFileName=${scssFileName//\.scss/.original_non_empty_scss}
    mv -v $scssFileName $newFileName
    echo &amp;gt; $scssFileName
  done
  echo "scss renamed. restore original files via scss_restore."
}

function scss_restore {
  local fileName
  for fileName in `find . -iname "*.original_non_empty_scss"`
  do
    local newFileName=${fileName//\.original_non_empty_scss/.scss}
    mv -v $fileName $newFileName
  done
  echo "scss restored. "
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Before test driving my code, I  execute the &lt;code&gt;scss_empty&lt;/code&gt; function to overwrite the &lt;a href="https://sass-lang.com/" rel="noopener noreferrer"&gt;scss&lt;/a&gt; files. Before committing or before starting the &lt;a href="https://angular.io/" rel="noopener noreferrer"&gt;Angular&lt;/a&gt; application, I excecute the &lt;code&gt;scss_restore&lt;/code&gt; function. Our build pipeline now always overwrites the &lt;a href="https://sass-lang.com/" rel="noopener noreferrer"&gt;scss&lt;/a&gt; files before executing the unit tests, which speeds up the build by several minutes.&lt;/p&gt;

&lt;p&gt;There might exist other solutions. I found no easy one like just setting one option, but in one &lt;a href="https://stackoverflow.com/questions/54805196/angular-unit-testing-ignore-stylesheets" rel="noopener noreferrer"&gt;stackoverflow thread someone suggested to change the resolver for scss files to return only empty strings if tests are executed&lt;/a&gt;. But that we’ll try out in future in a dedicated task. The quick fix solves my immediate problem so that I can execute the tests fast enough and often.&lt;/p&gt;

&lt;h2&gt;
  
  
  6. Conclusion
&lt;/h2&gt;

&lt;p&gt;Thanks to the tools provided by &lt;a href="https://nodejs.org/" rel="noopener noreferrer"&gt;node&lt;/a&gt; and thanks to the good &lt;a href="https://nodejs.org/es/docs/guides/simple-profiling/" rel="noopener noreferrer"&gt;simple profiling guide&lt;/a&gt;, finding the culprit method is very easy. Thanks to &lt;a href="https://strace.io/" rel="noopener noreferrer"&gt;strace&lt;/a&gt; for Linux or &lt;a href="http://dtrace.org/blogs/about/" rel="noopener noreferrer"&gt;dtrace&lt;/a&gt; / dtruss for mac os is a very easy way to see what’s going on – even when the logging of the &lt;a href="https://nodejs.org/" rel="noopener noreferrer"&gt;node&lt;/a&gt; program like &lt;a href="https://karma-runner.github.io/" rel="noopener noreferrer"&gt;karma&lt;/a&gt; is not sufficient. It’s nice that you can even see the parameters of the system calls so that, for example, it is obvious which files are accessed. Especially the strace or &lt;a href="http://dtrace.org/blogs/about/" rel="noopener noreferrer"&gt;dtrace&lt;/a&gt; / dtruss tools are tools to have in you sleeve.&lt;/p&gt;

</description>
      <category>node</category>
      <category>angular</category>
      <category>linux</category>
    </item>
  </channel>
</rss>
