<?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 piotr szybicki on Medium]]></title>
        <description><![CDATA[Stories by piotr szybicki on Medium]]></description>
        <link>https://medium.com/@piotr.szybicki?source=rss-b9d374def95a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*BXOA3IYv65thkcoWn1HOPg.png</url>
            <title>Stories by piotr szybicki on Medium</title>
            <link>https://medium.com/@piotr.szybicki?source=rss-b9d374def95a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 13:55:39 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@piotr.szybicki/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[CSS. All the ways to align elements left and right.]]></title>
            <link>https://medium.com/12-developer-labors/css-all-the-ways-to-align-elements-left-and-right-52ecce4a4af9?source=rss-b9d374def95a------2</link>
            <guid isPermaLink="false">https://medium.com/p/52ecce4a4af9</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[css]]></category>
            <category><![CDATA[html]]></category>
            <category><![CDATA[html-css]]></category>
            <category><![CDATA[web-design]]></category>
            <dc:creator><![CDATA[piotr szybicki]]></dc:creator>
            <pubDate>Fri, 22 Nov 2019 18:51:51 GMT</pubDate>
            <atom:updated>2019-11-22T18:51:51.314Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pZF9Wu0hoXi8DJ7z.jpg" /><figcaption>source: <a href="https://www.andiamo.co.uk/resources/right-to-left-languages/">https://www.andiamo.co.uk/resources/right-to-left-languages/</a></figcaption></figure><p>A short history lesson that probably most front-end devs know. But I didn’t so I decided to share. Plus there is a little trick at the end that might be surprising for some of you.</p><h3>Problem description</h3><p>Let’s say that we have the following elements to style.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/838/1*1a29tfNr1gYsdwtBRM2jdA.png" /></figure><p>And the desired end effect will be:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/823/1*qkFzKVGTTpKx6vF84pvGSA.png" /></figure><p>Hope my PAINT skills are enough to illustrate the problem. Two items on the left and one item on the right. Let’s take a look at our options. :) HTML code is at the bottom of this article.</p><h3>CSS 1.0</h3><p>Historically how it was done (and you still have that option). You can use floats. In order to achieve what you want you can wrap the div 1 and 2 in a parent div and this is what you get:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/612/1*DB5BQ_Veb6tzgvAUtIoJ0w.png" /><figcaption>The black border is a border on parent div that you have to add and orange are borders around the elements themself.</figcaption></figure><p>This will work however, there 2 problems with this approach.</p><ul><li><strong>One </strong>if one of the elements turns out to be bigger then the container it will go beyond its border (after all the element is floated so removed from the normal rendering of the DOM). So we have to apply a <a href="https://www.w3schools.com/howto/howto_css_clearfix.asp">clearfix</a>.</li><li><strong>Two </strong>without appropriate <strong>media queries</strong> the elements will start to overlap one another. If the user shrinks the browser too much.</li></ul><p>As I mentioned both problems have a solution but still it is something that you have to think about. But if you have to support some ancient browser you got to do what you got to do :(.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/29f544201ece2d2010d374d78a02a176/href">https://medium.com/media/29f544201ece2d2010d374d78a02a176/href</a></iframe><p><strong>CSS 2.1:</strong></p><p>And extension to the previous version of the spec. It brought the property: <strong>positioning</strong>. It can take a couple of values. But the one that interests us is: <strong>absolute </strong>and <strong>relative</strong>. How it works it described well all over the <a href="https://css-tricks.com/absolute-positioning-inside-relative-positioning/">internet</a>. So I will not try to reinvent a wheel.</p><p>All I have to do is set the <strong>relative </strong>positioning on the container and <strong>absolute </strong>on the right wrapper (left wrapper will be aligned to the left automatically) and then set <strong>right </strong>property to 0. Meaning zero pixels from the right. The effect will be basically the same as above but no need for a <strong>clearfix</strong>. The browser will automatically adjust parent dimensions to fit all the children.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/59dbfd00f4db6c09fa5560c445ff71a0/href">https://medium.com/media/59dbfd00f4db6c09fa5560c445ff71a0/href</a></iframe><p>The elements, however, will still overlap if we shrink the browser. This is a good solution. It will work in all browsers. But still, let’s explore other options.</p><h3>CSS 3: Flex+ justify-content: space-between</h3><p>So in CSS3, we got the new way of positioning elements aka: flexbox. It is a powerful and intuitive tool. That again volumes have been written about. The article I like the most about can be found under that <a href="https://css-tricks.com/snippets/css/a-guide-to-flexbox/">link</a>. All I have to do is put the <strong>display: flex</strong> on the container element and add <strong>justify-content: space-between</strong>. All it means is will put even space between child elements along the <strong>main axis </strong>(default is the horizontal line). And since we have just two elements (left-wrapper and right-wrapper) it works. As even space in case of just two elements means max available space.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ef541a5c9927da3d55f6867d576755ce/href">https://medium.com/media/ef541a5c9927da3d55f6867d576755ce/href</a></iframe><p>Again this is a good solution. If you don’t have to support IE6. As the elements will not overlap. The scroll bar will appear. Again modern responsive design should take that into account but mistakes happened and at least this way the content is still usable.</p><h3>Flex grow 1</h3><p>There is more than one way to skin a cat. Especially with flexbox. Let’s assume that for some bazar reason you can’t use the wrapping div. Tha the tree div`s that contain the number is all you got (This is a good interview question :) ).</p><p>Again we can use <strong>flex:1</strong> on the second element. This is a shorthand notation for the<strong> flex: 1 0 auto;</strong> or you can just write <strong>flex-grow: 1</strong>. All it means that we want element 2 to grow as much as possible without breaking line. This, however, has a problem if you want to add hover effect on the second element it will be placed on the entire large element and it may or may not look desirable. The workaround would be of course to add a 4&#39;th element between 2 and 3 and grow it. As I said there is more than one way to skin a cat.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/591/1*RWkSFbL_O72DbCLpCbxJ9Q.png" /></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/718e9aac7a42d3bbae75fb47e2bc71ae/href">https://medium.com/media/718e9aac7a42d3bbae75fb47e2bc71ae/href</a></iframe><h3>Final the most clever solution:</h3><p>If for some reason you don&#39;t want to add an extra element. All you have is a container and 3 divs you can do something very clever. Place the display: flex on the container and then margin-right: auto on the second element.</p><p>It will get you this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/594/1*Eqp9HByKPJMKJEYXHo8Pww.png" /></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8f3b52ac9d3557964ed5559198c83346/href">https://medium.com/media/8f3b52ac9d3557964ed5559198c83346/href</a></iframe><p>And that’s it I obviously didn’t cover some other ways to do this most notably <strong>CSS grid</strong> or using <strong>display: table</strong> or fiddling with the <strong>flex-basis</strong> property. But that is because I believe those solutions are overkill. And way too complicated for something this simple. And as I like to quote the master: <strong>simplicity is a prerequisite for reliability</strong>.</p><h3>HTML Code</h3><p>With the wrappers:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e45892f6eea813acfac2a2d854794cf3/href">https://medium.com/media/e45892f6eea813acfac2a2d854794cf3/href</a></iframe><p>Without the wrappers:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/50f8da121e9f2f077c6a6d9fb493c2e4/href">https://medium.com/media/50f8da121e9f2f077c6a6d9fb493c2e4/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=52ecce4a4af9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/12-developer-labors/css-all-the-ways-to-align-elements-left-and-right-52ecce4a4af9">CSS. All the ways to align elements left and right.</a> was originally published in <a href="https://medium.com/12-developer-labors">12 developer labors</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Passing function as arguments in Angular]]></title>
            <link>https://medium.com/12-developer-labors/passing-function-as-arguments-in-angular-ed28ae1cb45?source=rss-b9d374def95a------2</link>
            <guid isPermaLink="false">https://medium.com/p/ed28ae1cb45</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[js]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[piotr szybicki]]></dc:creator>
            <pubDate>Sun, 29 Sep 2019 14:59:44 GMT</pubDate>
            <atom:updated>2019-09-29T14:59:44.818Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/400/0*8PMephc1AXNEC_CA.jpg" /></figure><h4>How components can talk back to each other.</h4><p>This is going to be a short one. In angular (although probably all the modern frameworks React, Vue.js) you can embed quite a complex login in the HTML template. Via the structural directives<strong> *ngFor, *ngIf</strong> and the third one that no one uses :), we can express quite a complex presentation logic. Let me give you a quick example.</p><pre>&lt;h4&gt;NgSwitch&lt;/h4&gt;<br>&lt;ng-container <strong>*ngIf</strong>=&quot;currentUser.isAdmin else <strong>regularUser</strong>&quot; &gt;<br>&lt;div <strong>*ngFor</strong>=&quot;let person of people&quot;<br>    <strong>[ngSwitch]</strong>=&quot;person.country&quot;&gt;<br>  &lt;uk-user  <strong>*ngSwitchCase</strong>=&quot;&#39;UK&#39;&quot;  [person]=&quot;person&quot;&gt;&lt;/uk-user&gt;<br>  &lt;usa-user <strong>*ngSwitchCase</strong>=&quot;&#39;USA&#39;&quot; [person]=&quot;person&quot;&gt;&lt;/usa-user&gt;<br>&lt;/div&gt;<br>&lt;/ng-container&gt;</pre><pre>&lt;ng-template <strong>#</strong><strong>regularUser</strong>&gt;<br>&lt;div&gt;  <br>   &lt;default-user [person]=&quot;currentUser&quot;&gt;&lt;/default-user&gt;<br>&lt;/div&gt;<br>&lt;/ng-template&gt;</pre><pre>&lt;button (clicked)=&quot;perfomActionInChildCompoenets()&quot;&gt;&lt;/button&gt;</pre><p>You have to read the code for a minute to understand what is going on. But here goes a real problem. Let’s assume that at the end of this I add a button that when clicked some action has to be performed in every component that is displayed.</p><p>Maybe we can leverage the fact that in JavaScript the <strong>functions are first-class citizens</strong> and can be pass just like variables. Angular fully embrace TypeScript we can declare the contract for those functions and have to compiler enforce adherence to that contract.</p><p>Essentially what I&#39;m proposing is the implementation of the callback pattern. So we need a way to <strong>register </strong>and <strong>unregister</strong> the function that will be our callback. We can do that in two scenarios. Either Provide the <strong>register function</strong> or <strong>register event</strong> depending on the place where the function is physically written and physically called. Confused? Let&#39;s go-to examples.</p><h4>Register Function</h4><p>With the register function, a function that is going to be called is <strong>defined in the child componen</strong>t and <strong>executed in the parent</strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/90bd523671cb4ff8cfd6cdf83ed0f88d/href">https://medium.com/media/90bd523671cb4ff8cfd6cdf83ed0f88d/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c0b6aab9eb5721cc2f9784a20172f557/href">https://medium.com/media/c0b6aab9eb5721cc2f9784a20172f557/href</a></iframe><p>So as input to a child component, we provide two functions: <strong>registerFunction</strong> and <strong>unregisterFunction</strong>. As a way for registering by the child, a function that is going to be called when a parent decides to ‘lunchNukes’. Inside of that function, we simply iterate over all the function that has been registered and calling it one by one, console.log-ing the output. The benefit of that approach that we can take advantage of the lexical context within that function was declared (<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures">closure</a>) and use the private variables that reside inside of the component. Also, each component can provide its own implementation. Going back to the if-else example at the beginning we can imagine US citizen and the UK citizen have a different implementation for launching nukes.</p><h4>Register Event</h4><p>With the registered event, a function that is going to be called is <strong>defined in the parent componen</strong>t and <strong>executed in the child</strong>. This is a variation on the Observable pattern that I mentioned before but this is a bit simpler.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9f5c10ef7071e58cb570be02fbc1c8d2/href">https://medium.com/media/9f5c10ef7071e58cb570be02fbc1c8d2/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2c950beab65d6dc43b5371547d8cd21e/href">https://medium.com/media/2c950beab65d6dc43b5371547d8cd21e/href</a></iframe><p>Here we can see something unusual. Usually, the EventEmitter is declared with the @Output decorator:). Not in this case. We create EventEmitter in the parent and pass it to the child. Where you have to subscribe and unsubscribe in order to listen. And this is very very important <strong>you have to unsubscribe !!!!</strong>. Otherwise, even if the component gets removed from the DOM it will still have a strong reference to the parent so it won’t be garbage collected and it will still receive events. Also, the event emitter has to be recreated every time the child component <strong>calles <em>complete </em>on it the emitter becomes useless</strong>. The rest is straight forward. The event payload is a function that a child component can invoke. To be honest <strong>Bahvioral Subject</strong> from RxJs could be a better choice here.</p><h4>Summary</h4><p>Is this a bit overkill? might be. And it also might be that there are easier ways to solve that problem(Although I did it this way). The point of this article was to remind developers that function in JavaScript can be passed around. And we can take advantage of that. If I have to do what I described using a more standard approach available in Angular my parent and child component would end up hopelessly coupled. With a lot of duplication of state.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ed28ae1cb45" width="1" height="1" alt=""><hr><p><a href="https://medium.com/12-developer-labors/passing-function-as-arguments-in-angular-ed28ae1cb45">Passing function as arguments in Angular</a> was originally published in <a href="https://medium.com/12-developer-labors">12 developer labors</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[When to use inheritance.]]></title>
            <link>https://medium.com/12-developer-labors/when-to-use-inheritance-83b656c502ab?source=rss-b9d374def95a------2</link>
            <guid isPermaLink="false">https://medium.com/p/83b656c502ab</guid>
            <category><![CDATA[lessons-learned]]></category>
            <category><![CDATA[best-practices]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[design]]></category>
            <dc:creator><![CDATA[piotr szybicki]]></dc:creator>
            <pubDate>Sun, 26 May 2019 20:33:32 GMT</pubDate>
            <atom:updated>2019-05-26T20:35:10.547Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*MWoAcY0JyRi0I4-Q.jpg" /></figure><h3>When to use inheritance (In JAVA).</h3><blockquote>“Favor ‘object composition’ over ‘class inheritance’.” (Gang of Four 1995:20)</blockquote><p>It is a quote from a book that has been published over 20 years ago. “<em>Design Patterns: Elements of Reusable Object Oriented Software.</em>” And originally I had another introduction in mind but then during research for this article I encountered the following post on StackExchange from <a href="http://object-mechanics.com/">Seven A. Lowe</a>. And I decided to quote it fully here. <a href="https://softwareengineering.stackexchange.com/a/65209/321358">Link to the original post</a>.</p><blockquote>Though I think I’ve heard composition-vs-inheritance discussions long before GoF, I can’t put my finger on a specific source. Might have been Booch anyway.</blockquote><blockquote>Ah but like many mantras, this one has degenerated along typical lines:</blockquote><blockquote>it is introduced with a detailed explanation and argument by a well-respected source who coins the catch-phrase <em>as a reminder of the original complex discussion</em></blockquote><blockquote>it is shared with a knowing part-of-the-club wink by a few in-the-know for a while, generally when commenting on n00b mistakes</blockquote><blockquote>soon it is repeated mindlessly by thousands upon thousands who never read the explanation, but <strong><em>love using it as an excuse not to think</em></strong>, and as a cheap and easy way to feel superior to others</blockquote><blockquote>eventually, no amount of reasonable debunking can stem the “meme” tide — and the paradigm degenerates into religion and dogma.</blockquote><blockquote>The meme, originally intended to lead n00bs to enlightenment, is now used as a club to bludgeon them unconscious.</blockquote><blockquote>Composition and inheritance are very different things, and should not be confused with each other. While it is true that composition can be used to simulate inheritance <em>with a lot of extra work</em>, this does not make inheritance a second-class citizen, nor does it make composition the favorite son. The fact that many n00bs try to use inheritance as a shortcut does not invalidate the mechanism, and almost all n00bs learn from the mistake and thereby improve.</blockquote><blockquote>Please <strong>THINK</strong> about your designs, and stop spouting slogans.</blockquote><p>We all know <strong>how</strong> to implement composition, we all know <strong>how</strong> to implement inheritance. But <strong>how</strong> is an easy part and it’s just a wrapper, layer around <strong>why/when </strong>do it. I hope to give you recap argument when to use one over the other. As they both have its usages. And <strong>favor one over the other</strong> does not mean <strong>use one and never the other</strong>.</p><h4>What are we talking about?</h4><p>I’m Java developer and this article will talk about both concepts in the context of that language. And before I proceed with any arguments I want to explain some things. When I talk about inheritance I have a word <strong>extends</strong> in mind. Meaning I have a class or abstract class that is the <strong>base class</strong> for <strong>child class</strong>. Interface base inheritance is just a tool for polymorphism and nowhere near that dangerous.</p><p>When I talk about the composition I mean that the creation of fields of a certain type. Those types have a method/field that can be used by a parent object. Composition can be realized in many ways: Dependency Injection (EJB 3.0, Spring) where instantiation is managed by your run-time, via direct construction of the object using <strong>new</strong> keyword, etc.</p><h4>What’s the problem?</h4><p>And that is a tricky thing to answer. The argument about class (subtype) inheritance is 50 years old. And what’s more even the creator of the OO paradigm had reservations about it and left it out from the original specification (<a href="http://userpage.fu-berlin.de/~ram/pub/pub_jf47ht81Ht/doc_kay_oop_en">link</a>).</p><p>Classic OO concepts: classes, encapsulation, polymorphism don’t get the same heated discussions. They are there and what’s more important all OO languages implement them in a similar way. Where for inheritance it’s all over the map.</p><p>Go for example has no inheritance. C++ has ‘multiple inheritance’, JAVA has a single class inheritance, Ruby has mixins, JavaScript has prototype patching, and this article talks about traits (<a href="http://scg.unibe.ch/archive/papers/Scha02bTraits.pdf">link</a>). And for me, that is a sign of trouble. If the smartest guys in the industry working for over 50 years can’t seem to agree on something how average developers know what to do. I later parts I will have rules that I use when choosing between inheritance and composition.</p><p>For me, class-based inheritance realizes two orthogonal purposes. (The exact terms are stolen from this article <a href="https://www.thoughtworks.com/de/insights/blog/composition-vs-inheritance-how-choose">link</a>)</p><ol><li>Semantical</li><li>Mechanical</li></ol><p><strong>Semantical</strong> can be further split into two parts.</p><ul><li>One. It expresses the position of a given class in a bigger structure of relations. Where each entity is connected by <strong>is a</strong> relationship. (<strong>Person</strong> is a <strong>human</strong> is a <strong>mammal</strong> is an <strong>animal</strong> is <strong>livingThing. </strong>Would be an example). The problem is that <em>thing A</em> really has just one <strong>is a</strong> relationship with the <em>thing B</em>. (Person <strong>is a</strong> human and <strong>is a</strong> teacher) And not always that relationship is 100% match (Usually we inherit but we want just part of <strong>thing B</strong>).</li><li>Two. It expresses the contract of the class (At least partially, if we are dealing with abstract classes). The class that inherits from some other class takes responsibility for all public API of a parent class.</li></ul><p><strong>Mechanical </strong>is where<strong> </strong>inheritance is all about sharing behavior. All the fields and method implementation form the base class are appended to the child class. Thus making them available for reuse and augmentation. This makes our implementation <strong>tightly coupled</strong> with the base class. And therefore more brittle. This is especially apparent in deep hierarchies. Where a change in one class leads to changes in 10 other classes. Resulting in a code smell called <strong>shotgun surgery</strong>.</p><p>I think this duality of meaning is where most trouble lies. As some developers use it for <strong>code re-usability</strong> and some others as a tool for <strong>dynamic dispatch (i.e. contract definition)</strong>. They meet, work on a single project and then accidents happen.</p><h3>The definitive test for inheritance:</h3><p>I originally wanted to write a list, how inheritance can fail but it would have less educational value. So instead</p><h4>When “is a” relationship is violated.</h4><p>Most common test for an inheritance, that is, why it is first. If you can’s make sense from the statement objectA is objectB. ObjectA can’t inherit from objectB.</p><pre>public class Car extends Wheel{}</pre><p>Above example is gibberish. You can’t say Car is a Wheel with a straight face. What you want to say is car <strong>has a</strong> wheel. And if you are not going to take anything else from this article please remember this.</p><ul><li>“is a” = inheritance (Teacher is a Person)</li><li>“has a” = composition (Car has a Wheel, Teacher has a Pen)</li></ul><h4>When Liskov Substitution Principle is violated.</h4><p>So we can say “Electric Duck” <strong>is a</strong> Duck. Or a Penguin <strong>is a</strong> Bird. But the first one has to be “turn on” and another can’t “fly”. In these situations, it is the LSP that stop’s us from using inheritance to model that relations. Instead of bringing up the original definition I will quote Venkat’s interpretation:</p><blockquote><strong>Services of a derived class should require no more and promise no less than the corresponding services of a base class</strong>.</blockquote><p>I think it makes things simple. If you feel like you have to modify the contract, or you can fulfill the contract, of the parent class then delegation is something that might be more suitable for your situation.</p><p>In business applications, every entity and value object has a set of <strong>invariances</strong>. For example, Circle has a radius and can’t stretch in one direction. And if you feel like implementing a method would violate one of the promises. <strong>Rethink your design</strong>.</p><p>On a more practical note. I often see this in the code.</p><pre>public class ElectricDuck extends Duck{<br>   @Override public void fly(){...}<br>   @Override public int altitude(){...}<br>   public void charge(){...}<br>}</pre><p>And somewhere else:</p><pre>if(duck instanceof ElectricDuck){<br>   ElectricDuck electricDuc = (ElectricDuck) duck;<br>   electricDuck.charge();<br>}</pre><p>If you see that you have to do any type of conditional logic base on the incoming type you are probably violating LSP.</p><p>Another classic example is when you throw an exception. Because the contracts of the two classes do not match.</p><pre>public class Penguin extends Bird { <br>   @Override <br>   public void fly(){ <br>      throw new MethodInvocationException(&quot;I can&#39;t fly&quot;);<br>   }<br>}</pre><p>LSP is a very complicated and nuanced subject I highly recommend further reading.</p><h4>When there is no dynamic dispatch.</h4><p>And this is the final point. Let’s assume that your inheritance passes the above-mentioned test. But you use inheritance without polymorphism. Don’t. Your model might be correct but, and I can’t emphasize this enough, <strong>inheritance is a complexity buster of massive proportions</strong>. And should be a choice of a last resort.</p><pre><strong>public class </strong>Figure {<br><br>   @Override<br>   <strong>public </strong>String toString() {<br>      <strong>return &quot;Figure&quot;</strong>;<br>   }<br><br>   <strong>public static class </strong>Circle <strong>extends </strong>Figure {<br><br>      @Override<br>      <strong>public </strong>String toString() {<br>         <strong>return super</strong>.toString();<br>      }<br>   }<br><br>   <strong>public static class </strong>Ellipse <strong>extends </strong>Circle {<br><br>   }<br><br>}</pre><p>Can you immediately tell me what will be printed when I log each instance of the above class. (this is the simplest example I could think.)</p><p>If at call site there is a possibility for only one method to be invoked. You are using inheritance only as a tool for code reuse (Mechanical). And in those cases don’t do that. There is just no benefit.</p><h4>When to use inheritance:</h4><p>When a <strong>child object</strong> is a <strong>parent object </strong>(#1). Parent object methods are either properly overridden or left alone (#2). There is more than one <strong>child object</strong> that extends <strong>parent object</strong> and <strong>parent object</strong> interface is used (#3). The problem is that all these conditions are not met all that often. And that is the reason that you should <strong>favor composition over inheritance</strong>. To bring back what was said at the beginning, the phrase only exists as a reminder of a complex logic behind it. And I hope that n00bs now can be led back on the path of enlightenment. I’m going to do a second part to this called dangers of inheritance. To supplement this one. But I don’t what to cram too much.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=83b656c502ab" width="1" height="1" alt=""><hr><p><a href="https://medium.com/12-developer-labors/when-to-use-inheritance-83b656c502ab">When to use inheritance.</a> was originally published in <a href="https://medium.com/12-developer-labors">12 developer labors</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Authentication using OAuth2 Implicit Flow using Azure Active Directory]]></title>
            <link>https://medium.com/12-developer-labors/authentication-using-oauth2-implicit-flow-using-azure-active-directory-78ccaebc620?source=rss-b9d374def95a------2</link>
            <guid isPermaLink="false">https://medium.com/p/78ccaebc620</guid>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[azure-active-directory]]></category>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[piotr szybicki]]></dc:creator>
            <pubDate>Mon, 15 Apr 2019 08:58:00 GMT</pubDate>
            <atom:updated>2019-04-15T08:58:00.827Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/860/1*_Gvc44N3u4eXr4XCpnOKoQ.png" /></figure><p>I recently begun to work in a new company. And unlike my previous job the goto cloud provider is the Microsoft Azure. We have plans to develop Angular application that spark my question how to secure it. So I set out to do it. Given that I have pretty good understanding of the OAuth2 and OpenIDConnect Authorization Code Flow I more or less knew what I want to achieve. Turn out is was simpler then I originally suspected. As Microsoft does not have a history of making my life easier. If you want to fallow along with me pleas prepare the set up in AD first. The azure docs do pretty good job so I will not bother:</p><p><a href="https://docs.microsoft.com/en-us/java/azure/spring-framework/configure-spring-boot-starter-java-app-with-azure-active-directory?view=azure-java-stable">How to use the Spring Boot Starter for Azure Active Directory</a></p><p>Pleas follow only the steps done from the azure console I will help with the rest. One thing when they ask you to provide redirect URI just type: <a href="http://localhost:4200/">http://localhost:4200</a></p><h4>Authorization Code Flow</h4><p>First let me tell you right of the bat that Microsoft implements OAuth2 spec in a confusing way as it can be used both for delegated authorization (something it was designed for) and delegated authentication (something that original spec was missing). Plus for both the same endpoint is used, which doesn’t help. In my opinion this is a historical mistake as there was a point in time when the OAuth2 was adopted as a guarantor of user identity. However every company (Google, Microsoft, LinkedIn, Twitter) did it slightly different way. And that is why additional 5% on top of OAuth was added and called OpenIDConnect. Mainly around retrieving user information.</p><p>The title of this peace read ‘Authentication …’ so that would suggest OpenIDConnect flow will be presented however Microsoft has a TypeScript library that uses the OAuth2 Implicit Flow for authorization. And I struggle with a though for a while to go against the current and write my own but I decided to be lazy and not reinvent the wheel.</p><p>OK. So now a little bit of theory. When I say <strong>implicit flow</strong> (type of the OAuth2 flow there are 3 more) what I actually mean is a bunch of http request exchange between browser and identity provider (in this case Azure AD).</p><p>So let’s analyze thous requests, first we go to <a href="http://localhost:4200/">http://localhost:4200</a> where js code checks if the user is logged in, it is not the it’s redirected to following url:</p><pre>GET <a href="https://login.microsoftonline.com/%7Btenant%7D/oauth2/authorize">https://login.microsoftonline.com/</a><strong>689c417e-2596-4b1e-ad56-976712af76a1</strong><a href="https://login.microsoftonline.com/%7Btenant%7D/oauth2/authorize">/oauth2/authorize</a>?<br><strong>client_id</strong>=52342c78-c557-48ef-8f09-be40c2093edf<br>&amp;<strong>response_type</strong>=id_token<br>&amp;<strong>redirect_uri</strong>=http%3A%2F%2Flocalhost%3A4200<br>&amp;<strong>state</strong>=b597dbdf-7c80-4aa2-bb4e-6e76a100cffe<br>&amp;<strong>client-request-id</strong>=9905b985-ae8a-4e0b-9c41-b40a4d301672<br>&amp;<strong>x-client-SKU</strong>=Js&amp;x-client-Ver=1.0.17<br>&amp;<strong>nonce</strong>=7362CAEA-9CA5–4B43–9BA3–34D7C303EBA7</pre><p>let’s analyze what is passed first thing that is boded is the <strong>tenatId</strong>. This is an unique id for your active directory. <strong>Client_id</strong> is the id of the registered app. <strong>respons_type</strong> is the required parameter and it has to be id_token, token, code. <strong>redirect_uri</strong> where you should be redirected to after successful login. <strong>Nonce </strong>is a random value design to prevent replay attacks.</p><p>And this is where things got a little bit confusing for me as couple of things ware missing: scope (spec says that it have to be comma separated values and the first have to be openid) and response_mode (methods that specified the resulting authentication code back) but it turns out that in their absence the azure AD has reasonable defaults.</p><p>OK so now after this long explanation user is on the login page enters credentials and after successful login the 302 Moved Temporarily redirect is issued to the following address:</p><pre><a href="http://localhost:4200/#id_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6Ik4tbEMwbi05REFMcXdodUhZbkhRNjNHZUNYYyIsImtpZCI6Ik4tbEMwbi05REFMcXdodUhZbkhRNjNHZUNYYyJ9.eyJhdWQiOiI1MjM0MmM3OC1jNTU3LTQ4ZWYtOGYwOS1iZTQwYzIwOTNlZGYiLCJpc3MiOiJodHRwczovL3N0cy53aW5kb3dzLm5ldC82ODljNDE3ZS0yNTk2LTRiMWUtYWQ1Ni05NzY3MTJhZjc2YTEvIiwiaWF0IjoxNTU1MjM1Nzc5LCJuYmYiOjE1NTUyMzU3NzksImV4cCI6MTU1NTIzOTY3OSwiYWlvIjoiNDJaZ1lEaGk3SEM3amp2NnpaR2FlTGJhQzlyZU5YWm1BdFcycnpZZlVlbSt5bE51UEFjQSIsImFtciI6WyJwd2QiXSwiaXBhZGRyIjoiMTQ1LjYyLjY0LjEwMCIsIm5hbWUiOiJwaW90cmVrIiwibm9uY2UiOiJkYWZhNWY4My01YWRkLTQ5OWQtYTA1Ny02YzMyNmQ2ZDNjNzUiLCJvaWQiOiI2YzkyNzI1ZS03NTk5LTQ0YmUtOTJmOC1kOTc2MGRjNzM5NTIiLCJzdWIiOiJNQWRyUXFXUTNGaV92RjhGbWFqaUZCRzhjQWs4Snp1OWVlTl9DbFVRakpnIiwidGlkIjoiNjg5YzQxN2UtMjU5Ni00YjFlLWFkNTYtOTc2NzEyYWY3NmExIiwidW5pcXVlX25hbWUiOiJ1c2VyQHBzenliaWtja2lhZC5vbm1pY3Jvc29mdC5jb20iLCJ1cG4iOiJ1c2VyQHBzenliaWtja2lhZC5vbm1pY3Jvc29mdC5jb20iLCJ1dGkiOiJLcTNQWGdycXAwdVp0dFNCZnVFWkFBIiwidmVyIjoiMS4wIn0.XtKvYyeZUfxKBVn_c4TYyrFYLmDGgscUknW33rhPd8q5b_VepzwgEZZBVmQ-IraB47U_EzO7dSoDTS8vP8mxxR7EJQBNkYNEDQVb2NykHKD7RrIV3oLaSZPzS4r2hTvvP7eWDtrZGAarmOObTqVlyNKXsAr_oduET3gpbPctaCdOCrRIZb7ssmILD8gZp_gy9ZrLTZEb54v3Bi_rJMz45S9jFKaw_obGWu9vq0tddFY4_DXPMPns_BWgHmzMEhUB6WNrDQw7OykiR-CB_0MWD1kbsDAX6vOzro8UDTF9SGs7-vzlhFRKuJSZwJPDyRbr6e3KYcxyfHhmOrkbZh49Cw&amp;state=b597dbdf-7c80-4aa2-bb4e-6e76a100cffe&amp;session_state=70bffd08-5390-444b-9b9d-6cbb3bf5e554">http://localhost:4200/#<strong>id_token</strong>=eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6Ik4tbEMwbi05REFMcXdodUhZbkhRNjNHZUNYYyIsImtpZCI6Ik4tbEMwbi05REFMcXdodUhZbkhRNjNHZUNYYyJ9.eyJhdWQiOiI1MjM0MmM3OC1jNTU3LTQ4ZWYtOGYwOS1iZTQwYzIwOTNlZGYiLCJpc3MiOiJodHRwczovL3N0cy53aW5kb3dzLm5ldC82ODljNDE3ZS0yNTk2LTRiMWUtYWQ1Ni05NzY3MTJhZjc2YTEvIiwiaWF0IjoxNTU1MjM1Nzc5LCJuYmYiOjE1NTUyMzU3NzksImV4cCI6MTU1NTIzOTY3OSwiYWlvIjoiNDJaZ1lEaGk3SEM3amp2NnpaR2FlTGJhQzlyZU5YWm1BdFcycnpZZlVlbSt5bE51UEFjQSIsImFtciI6WyJwd2QiXSwiaXBhZGRyIjoiMTQ1LjYyLjY0LjEwMCIsIm5hbWUiOiJwaW90cmVrIiwibm9uY2UiOiJkYWZhNWY4My01YWRkLTQ5OWQtYTA1Ny02YzMyNmQ2ZDNjNzUiLCJvaWQiOiI2YzkyNzI1ZS03NTk5LTQ0YmUtOTJmOC1kOTc2MGRjNzM5NTIiLCJzdWIiOiJNQWRyUXFXUTNGaV92RjhGbWFqaUZCRzhjQWs4Snp1OWVlTl9DbFVRakpnIiwidGlkIjoiNjg5YzQxN2UtMjU5Ni00YjFlLWFkNTYtOTc2NzEyYWY3NmExIiwidW5pcXVlX25hbWUiOiJ1c2VyQHBzenliaWtja2lhZC5vbm1pY3Jvc29mdC5jb20iLCJ1cG4iOiJ1c2VyQHBzenliaWtja2lhZC5vbm1pY3Jvc29mdC5jb20iLCJ1dGkiOiJLcTNQWGdycXAwdVp0dFNCZnVFWkFBIiwidmVyIjoiMS4wIn0.XtKvYyeZUfxKBVn_c4TYyrFYLmDGgscUknW33rhPd8q5b_VepzwgEZZBVmQ-IraB47U_EzO7dSoDTS8vP8mxxR7EJQBNkYNEDQVb2NykHKD7RrIV3oLaSZPzS4r2hTvvP7eWDtrZGAarmOObTqVlyNKXsAr_oduET3gpbPctaCdOCrRIZb7ssmILD8gZp_gy9ZrLTZEb54v3Bi_rJMz45S9jFKaw_obGWu9vq0tddFY4_DXPMPns_BWgHmzMEhUB6WNrDQw7OykiR-CB_0MWD1kbsDAX6vOzro8UDTF9SGs7-vzlhFRKuJSZwJPDyRbr6e3KYcxyfHhmOrkbZh49Cw&amp;<strong>state</strong>=b597dbdf-7c80-4aa2-bb4e-6e76a100cffe&amp;<strong>session_state</strong>=70bffd08-5390-444b-9b9d-6cbb3bf5e554</a></pre><p>The Id token is whet we requested earlier. It’s something called JWT (JSON Web Token) and you can copy/paste it (<a href="https://jwt.io/">https://jwt.io/</a>) to decode it into something more readable:</p><pre>{<br>  &quot;aud&quot;: &quot;52342c78-c557-48ef-8f09-be40c2093edf&quot;,<br>  &quot;iss&quot;: &quot;<a href="https://sts.windows.net/689c417e-2596-4b1e-ad56-976712af76a1/">https://sts.windows.net/689c417e-2596-4b1e-ad56-976712af76a1/</a>&quot;,<br>  &quot;iat&quot;: 1555235779,<br>  &quot;nbf&quot;: 1555235779,<br>  &quot;exp&quot;: 1555239679,<br>  &quot;aio&quot;: &quot;42ZgYDhi7HC7jjv6zZGaeLbaC9reNXZmAtW2rzYfUem+ylNuPAcA&quot;,<br>  &quot;amr&quot;: [<br>    &quot;pwd&quot;<br>  ],<br>  &quot;ipaddr&quot;: &quot;145.62.64.100&quot;,<br>  &quot;name&quot;: &quot;piotrek&quot;,<br>  &quot;nonce&quot;: &quot;dafa5f83-5add-499d-a057-6c326d6d3c75&quot;,<br>  &quot;oid&quot;: &quot;6c92725e-7599-44be-92f8-d9760dc73952&quot;,<br>  &quot;sub&quot;: &quot;MAdrQqWQ3Fi_vF8FmajiFBG8cAk8Jzu9eeN_ClUQjJg&quot;,<br>  &quot;tid&quot;: &quot;689c417e-2596-4b1e-ad56-976712af76a1&quot;,<br>  &quot;unique_name&quot;: &quot;<a href="/service/mailto:user@pszybikckiad.onmicrosoft.com">user@pszybikckiad.onmicrosoft.com</a>&quot;,<br>  &quot;upn&quot;: &quot;<a href="/service/mailto:user@pszybikckiad.onmicrosoft.com">user@pszybikckiad.onmicrosoft.com</a>&quot;,<br>  &quot;uti&quot;: &quot;Kq3PXgrqp0uZttSBfuEZAA&quot;,<br>  &quot;ver&quot;: &quot;1.0&quot;<br>}</pre><p>This is just the middle of three parts that comprise the JWT. The last one is a cryptographic signature that allows us to verify that the token has not been tampered with. You can do it yourself go to the <a href="https://jwt.io/">https://jwt.io/</a> paste the full token to decode it the go to:</p><pre><a href="https://login.microsoftonline.com/689c417e-2596-4b1e-ad56-976712af76a1/.well-known/openid-configuration">https://login.microsoftonline.com/{tanant_id}/.well-known/openid-configuration</a></pre><p>there you will have the link to retrieve the public key</p><pre>&quot;jwks_uri&quot;: &quot;<a href="https://login.microsoftonline.com/common/discovery/keys">https://login.microsoftonline.com/common/discovery/keys</a>&quot;</pre><p>and then you can copy/paste the public key (the long string)</p><pre><em>-----BEGIN CERTIFICATE-----<br>content of the </em> x5c field<em><br>-----END CERTIFICATE-----</em></pre><p>and you can paste that into a verification window beck on the page where you copy the full token. If all goes well you should see:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*fiiva19O9GjnvHos2GZa1A.png" /></figure><p>That token can be used to access the backend API :). Up until this point we ware only talking about the authentication. But in the setup you ware asked to assigned some roles, now different users can have different roles, and they are not encoded in the JWT. But that is not a problem our backed (spring security) can contact the Azure AD and retrieve them and then see if the user has permission to this or that.</p><h4>The code.</h4><p>OK now that all is explained. Let’s do some code. The application can be found on GitHub and the link at the end.</p><h4>Angular:</h4><p>Install the Active Directory Authentication Library (ADAL) for Angular 6+ (Angular 6.X.X and Angular 7.X.X):</p><pre>npm i microsoft-adal-angular6</pre><p>and then configure MsAdalAngular6Module. We have to pass the same values that ware mentioned in the tutorial. And replace <strong>tenant </strong>and <strong>clientId</strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ba94111a4d2b0f74fc3133b386c63e87/href">https://medium.com/media/ba94111a4d2b0f74fc3133b386c63e87/href</a></iframe><p>We have to set up two more things first authentication on startup and then enrich every HTTP request with JWT Token</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/884e9f75bc3c354224f0efbacc5cf24c/href">https://medium.com/media/884e9f75bc3c354224f0efbacc5cf24c/href</a></iframe><p>We achieve that by specifying HTTP_INTERCEPTORS and APP_INITIALIZER tokens (different token :) ). Then we can freely call the the backend using regular httpClient syntax available in angular.</p><h4>Spring:</h4><p>First notice that i had to use the 2.0.3.RELEASE of the spring boot. And that is because there is a bug in the following versions ( <a href="https://github.com/Microsoft/azure-spring-boot/issues/530">https://github.com/Microsoft/azure-spring-boot/issues/530</a>) that cause error:</p><pre>Caused by: java.lang.ClassCastException: java.lang.String cannot be cast to java.util.List<br> at com.nimbusds.oauth2.sdk.util.URLUtils.serializeParameters(URLUtils.java:101) ~[oauth2-oidc-sdk-6.0.jar:6.0]<br>....</pre><p>So if you see that downgrade.</p><p>In spring we have to duplicate the configuration a little bit. Not sure why is that but either spring or the Microsoft lib was complaining if I removed one of this.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6d6465163f472244208dd52076c6a538/href">https://medium.com/media/6d6465163f472244208dd52076c6a538/href</a></iframe><p>And the configuration of the</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/85d4c1fd90161c6bd54cb991f0fb3a8e/href">https://medium.com/media/85d4c1fd90161c6bd54cb991f0fb3a8e/href</a></iframe><p>And the rest endpoint:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2f1882a9c262c29cab5d1ec76d45e892/href">https://medium.com/media/2f1882a9c262c29cab5d1ec76d45e892/href</a></iframe><p>as you can see user has only one role. So when you try to access one endpoint from the angular app you can see the response in the console and you get the error for the other.</p><h4>Code:</h4><p><a href="https://github.com/piotr-szybicki/blog_posts/tree/master/azure-b2c-login">piotr-szybicki/blog_posts</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=78ccaebc620" width="1" height="1" alt=""><hr><p><a href="https://medium.com/12-developer-labors/authentication-using-oauth2-implicit-flow-using-azure-active-directory-78ccaebc620">Authentication using OAuth2 Implicit Flow using Azure Active Directory</a> was originally published in <a href="https://medium.com/12-developer-labors">12 developer labors</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Must(read) on Optional(type)]]></title>
            <link>https://medium.com/12-developer-labors/must-read-on-optional-type-b171e1b397bb?source=rss-b9d374def95a------2</link>
            <guid isPermaLink="false">https://medium.com/p/b171e1b397bb</guid>
            <category><![CDATA[developer]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[design]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[piotr szybicki]]></dc:creator>
            <pubDate>Thu, 04 Apr 2019 06:42:50 GMT</pubDate>
            <atom:updated>2019-04-04T07:32:23.992Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Pr7rdKSPVe-1pgmU.jpg" /><figcaption>source: <a href="https://i.redd.it/zt0mrocw5mw11.jpg">https://i.redd.it/zt0mrocw5mw11.jpg</a></figcaption></figure><h4>This article is long time coming. It culmination my 4 year struggle to understand proper usage of the optional type.</h4><p>The optional type that I’m going to talk about was introduce in Java 8 to solve a very specific problem. Some methods, mostly around streams API, had a uncertain result ( I’m talking about <strong>findFirst()</strong> and <strong>findAny() </strong>) that uncertainty if left unchecked would brought a ghost of Tony Hoare us (<a href="https://www.infoq.com/presentations/Null-References-The-Billion-Dollar-Mistake-Tony-Hoare">Null References: The Billion Dollar Mistake</a>). I image with time we could get use to syntax like this:</p><pre>List&lt;String&gt; numbers= ImmutableList.of(&quot;ONE&quot;, &quot;TWO&quot;, &quot;THREE&quot;);<br>String numberThatImLookingFour = <br>numbers.stream()<br> .filter(number -&gt; &quot;FOUR&quot;.equals(number))<br> .findAny();</pre><pre>if(numberThatImLookingFour != null){<br> return numberThatImLookingFour.toLowerCase();<br>}else{<br> return &quot;not found&quot;;<br>}</pre><p>But the above code is full of cutter and more than a few people would write that code like this:</p><pre>List&lt;String&gt; numbers= ImmutableList.of(&quot;ONE&quot;, &quot;TWO&quot;, &quot;THREE&quot;);<br><br>return numbers.stream()<br> .filter(number -&gt; &quot;FOUR&quot;.equals(number))<br> .findAny()<br> .toLoweCase();</pre><p>Resulting in too many NullPointerExceptions. We needed something better. So Brian Goetz and Steward Marks (Java Language Architects) got together and wrote the following paragraph:</p><blockquote>Our intention was to provide a limited mechanism for library method return types where there needed to be a clear way to represent “no result”, and using null for such was overwhelmingly likely to cause errors.</blockquote><p>I will come back to this quote later. And so the Optional&lt;T&gt; was added. It wasn’t really a new concept (Guava had optional) I think the history goes back to a Maybe monad from Haskell. And suddenly we got JDK approved way of representing value that might or might not be there. And as usual, developers went nuts, using the new capability everywhere. To a point that is a good thing as it allows is to figure out the boundaries of an idea. And I really was pushing it. The Null reference, for me is the source of uncounted bugs, and generally not really a good representation of non existence. The big part on how we should deal with the problem comes from DDD. Where the at the entry to the <strong>bounded context</strong> we say: ‘<strong>You shall not pass</strong> ’</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/794/1*z6oIoPYaXWC_wNGouU7KHw.png" /></figure><p>Meaning at the entry to the domain all the variables that are needed to execute business logic are present. But that help us only at reducing the amount of if(obj==null) that we have to write. We still have to interact with the outside world (database queries, rest endpoints etc..) and execute logic based on the output of thous interactions. There, <strong>if used properly</strong> Optional can help.</p><h4>What‘s’Optional?</h4><ul><li>It is box type, holds reference to another object.</li><li>Is Immutable,and non serializable</li><li>Has no public constructor</li><li>Can Only be <strong>present</strong> or <strong>absent</strong></li><li>Created via: of(), ofNullable(), empty() static methods.</li></ul><h4>How can we retrieve the value from the box?</h4><ul><li>get()</li><li>orElse()</li><li>orElseGet()</li><li>orElseThrow()</li></ul><p>There is a catch as temptation to call get() to get the value. We all know getters/setters :). And there is a expectation that if we call get…() we get something. You never expect any exception to be thrown when calling getter. However if you call get on optional and that optional is empty, exception NoSuchElementException will be thrown. Brian Goetz went on a rant during his interview <a href="https://www.youtube.com/watch?v=Su1ijHLvuNE">https://www.youtube.com/watch?v=Su1ijHLvuNE</a> how this was a big mistake :). And the methods should be called getOrThorwSomeHorribleError(). Out of that comes the first and second rule:</p><h4>#1 Don’t assign null to Optional.</h4><p>I’m not even going to comment on that. Just remember every time you do this little bunny dies. And it’s probably this one:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*3UHX7aHldvF10zUd.jpg" /></figure><h4><strong>#2 Avoid use Optional.get(). And never, ever call get() if you can’t prove that optional is present.</strong></h4><p>Usually we can achieve what you want with <strong>orElse()</strong>, <strong>orElseGet()</strong>, <strong>orElseThrow()</strong>. So we can refactor pattern like that:</p><pre>String variable = fetchSomeVaraible();<br>if(variable == null){<br> <strong>1.</strong> throw new IllegalStateException(&quot;No such variable&quot;);<br> <strong>2.</strong> return createVariable();<br> <strong>3. </strong>return &quot;new variable&quot;;<br>} else { <br> ... <br> 100 lines of code<br> ...<br>}</pre><p>into:</p><pre><strong>1.</strong> <br>Optional&lt;String&gt; variableOpt = fetchOptionalSomeVaraible();<br>String variable = variableOpt.orElseThrow(() -&gt; new Exeption(&quot;&quot;)) <br>... 100 lines of code ...<br><strong>2.</strong><br>Optional&lt;String&gt; variableOpt = fetchOptionalSomeVaraible();<br>String variable = variableOpt.orElseGet(() -&gt; createVariable()) <br>... 100 lines of code ...<br><strong>3.</strong><br>Optional&lt;String&gt; variableOpt = fetchOptionalSomeVaraible();<br>String variable = variableOpt.orElse(&quot;new variable&quot;) <br>... 100 lines of code ...</pre><p>There is a little caveat that I should mention here. The orElse(..) is evaluated eagerly. Meaning the following code</p><pre>Optional&lt;Dog&gt; optionalDog = fetchOptionalDog();<br>optionalDog<br> .map(this::<strong>printUserAndReturnUser</strong>)<br> .orElse(this::<strong>printVoidAndReturnUser</strong>)</pre><p>Will execute both methods if the value is present and only the last one if the value is absent. To handle those cases we have method <strong>orElseGet()</strong> that takes a supplier as parameter. And is evaluated lazily.</p><h4>#3 Don’t use optional in fields, method parameters, collections.</h4><p>As part of my own craze for optional I use them in all, above mentioned, cases. This is a bad idea for several reasons.</p><p>One it make the code more messy. For example I had to wite one of two setters with either logic in them (code smell, it breaks the contract of the setter, which states that what I set is what I get)</p><pre>public void setThatField(ThatFieldType thatField){<br>  this.thatField = Optional.ofNullable(thatField);<br>}</pre><p>or I had to force all my callers to pack the object in to optional (Maybe less smelly, but also not nice)</p><pre>public void setThatField(Optional&lt;ThatFieldType&gt; thatField){<br>  this.thatField = thatField;<br>}<br>...<br>setThatField(Optional.ofNullable(thatField));</pre><p>It led to many problems, many misunderstanding and many bugs.</p><p>Two it is also a performance problem. You create extra object. So there is increased GC pressure. And<strong> </strong>you create extra level of indirection.</p><p><em>Disclaimer: My description is massive simplification. I’m thinking about writing how java is executed on modern hardware but it will take me some time.</em></p><p>So what are those level of indirection. In the end if we want to operate on a value, that value has to find itself in the CPU registers but the registers can only talk to the L1 Cache. If the value is not found in the L1 Cache (here skipping some steps) the load instruction is issued into main memory. We call it a <strong>cache miss</strong>. In modern hardware that instruction takes around 300 clock cycles. So the following code will take around 900 clk.</p><pre>object.getListOfObjects().get(0);</pre><p>We have three references that we have to fetch from main memory. First to get <strong>object</strong> then to get the <strong>list</strong> and then to get <strong>first object</strong> in that list. And the bad part: there is not way to cheat here CPU can’t guess the address and you can’t make it run in parallel. With performance improvements to modern CPU like speculative branch prediction, out of order executions etc. CPU runs from one cache miss to the other, and gets bored in between. Note if you add optional to the mix that means another level of indirection and another cache miss. Let’s say 4 in total. JVM especially JIT can do stuff here to optimize things (escape analysis) but it’s limited. We are waiting for project Valhalla but who knows when that comes around.</p><p>Going back, so you can imagine if you have a collection of even modest size, of optionals containing objects that have an optional field you might see a performance degradation pretty quickly.</p><p>Also don’t pass optional as argument. It just gives you nothing. First of all you can’t be sure that your caller did not violate the rule number 1. But also when you pass some object to the method presumably you want to do something with that object so you will most certainly end up with this code optional.isPresent(){optional.get()}.If you want to execute some logic based on the presence or absence of that parameter <strong>move that burden to the caller.</strong> And make him/here choose a method to either create or update some resource. Your expectation (assuming you are inside your bounded context) is that in order to invoke the method, you have all you need..</p><p>An exception to that rule could be private methods. Those are usually created to group some functionality together, not part of API surface area and in that case do whatever will result in less code.</p><h4>#4 Use Optional only as return type. But <a href="http://nukk/">every</a> time when the result is uncertain.</h4><p>To be honest this is the only good place to use optional. I will copy paste a quote from the creator of the class himself:</p><blockquote>Our intention was to provide a limited mechanism for library method <strong>return types</strong> where there needed to be a <strong>clear way to represent “no result”</strong>, and using null for such was <strong>overwhelmingly likely to cause errors</strong>.</blockquote><p>This time I bolded some stuff. This sums up perfectly why to use upotional. Notice that I said don&#39;t use optional on fields I said nothing about return from getter :). It is a sacrilege for some people to modify IDE generated getter but it is a way to go.</p><p>Here is the great presentation Victor Rentea(Lead IBM Architect for Java)<a href="https://www.youtube.com/watch?v=YnzisJh-ZNI&amp;feature=youtu.be&amp;t=847">https://www.youtube.com/watch?v=YnzisJh-ZNI&amp;feature=youtu.be&amp;t=847</a> Where he proposes the same thing. I recommend watching the whole thing, just slow it down to 75% speed, guy has serious ADHD.</p><h4>#5 Don’t be afraid to use map and filter.</h4><p>There is more general development practice that is worth to follow called <strong>SLA-p</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/0*Uxyj_b3fK1Katkfo" /></figure><p>It means <strong>S</strong>ingle <strong>L</strong>ayer of <strong>A</strong>bstraction. I don’t want to get too much off track here but I settle the discussion of weather method is tool long or not (5 line vs 10 lines vs 20 lines) by seeing how many times its body is indented.One indentation is one level of abstraction. Two is two and it’s too much. As our brain is running out of cache lines (we have only 4–7 of those). So the following code:</p><pre>Dog dog = fetchSomeVaraible();<br>String dogString = dogToString(dog);</pre><pre>public String dogToString(Dog dog){<br> if(dog == null){<br>   return &quot;DOG&#39;d name is : &quot; + dog.getName();<br> } else { <br>   return &quot;CAT&quot;;<br> }<br>}</pre><p>can become:</p><pre><strong>Optional&lt;Dog&gt; dog = fetchDogIfExists();<br>String dogsName = dog<br> .map(this::</strong>convertToDog<strong>)<br> .orElseGet(this::convertToCat)</strong></pre><pre>public void convertToDog(Dog dog){<br>   return &quot;DOG&#39;d name is : &quot; + dog.getName();<br>}</pre><pre>public void convertToCat(){<br>   return &quot;CAT&quot;;<br>}</pre><p>This is the very simple case but you can imagine how much clearer the syntax become if you can phrase it in this more declarative way.</p><p><strong>Filter</strong> can be useful fold syntax like this:</p><pre>Dog dog = fetchDog();<br>if(optionalDog != null &amp;&amp; optionalDog.isBigDog()){<br>  doBlaBlaBla(optionalDog);<br>}</pre><p>into this:</p><pre>Optional&lt;Dog&gt; optionalDog = fetchOptionalDog();<br>optionalDog<br> .filter(Dog::isBigDog)<br> .ifPresent(this::doBlaBlaBla)</pre><p>And that brings me to the rule number 4:</p><h4>#6 Don’t create optional just to chain methods on it.</h4><p>One of the thing to watch out for when using optional is a temptation to chain methods. Things might look so pretty when we chain methods just like in builder pattern :). But pretty not always equal to more readable. So don’t do that:</p><pre>Optional<br> .ofNullable(someVariable)<br> .ifPresent(this::blablabla)</pre><p>It’s not good for performance, and it’s not good for readability. We should avoid the null references when possible. But when they occur (for example you call 3rd party library) deal with them in familiar way.</p><h4>#7 Make all expression a single line lambdas.</h4><p>This is more general rule that I think should be applied to streams as well.But this article is about Optional. In this more declarative style offered us by methods on Optional it is important to remember that the left side of the equation is as much as important to us as the right. But the code will be so hard to follow if we do this</p><pre>Optional<br> .ofNullable(someVariable)<br> .map(variable -&gt; {<br>   try{<br>      return someREpozitory.findById(variable.getIdOfOtherObject());<br>   } catch (IOException e){<br>     LOGGER.error(e); <br>     throw new RuntimeException(e); <br>   }})<br> .filter(variable -&gt; { <br>   if(variable.getSomeField1() != null){<br>     return true;<br>   } else if(variable.getSomeField2() != null){<br>     return false;   <br>   } else { <br>     return true;<br>   }<br>  })<br> .map((variable -&gt; {<br>   try{<br>      return jsonMapper.toJson(variable);<br>   } catch (IOException e){<br>     LOGGER.error(e); <br>     throw new RuntimeException(e); <br>   }}))<br> .map(String::trim)<br> .orElseThrow(() -&gt; new RuntimeException(&quot;something went horribly wrong.&quot;))</pre><p>So instead extract all those block lambda to separate methods:</p><pre>Optional<br> .ofNullable(someVariable)<br> .map(this::findOtherObject)<br> .filter(this::isThisOtherObjectStale)<br> .map(this::convertToJson)<br> .map(String::trim)<br> .orElseThrow(() -&gt; new RuntimeException(&quot;something went horribly wrong.&quot;));</pre><h4>Summary</h4><p>That would be it. Optional is not here to replace a null reference it’s here to help us deal with the uncertainty of the result. And thus making the code more readable. And to be honest that is the point when writing code. With a proper usage we won’t pollute the code with a bunch of <a href="https://en.wikipedia.org/wiki/Defensive_programming">defensive coding</a>. If you have to fail do it gracefully and don’t try to handle all the transitions of the gigantic state machine that is you application. Remember in the end <strong>complexity is our biggest enemy</strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b171e1b397bb" width="1" height="1" alt=""><hr><p><a href="https://medium.com/12-developer-labors/must-read-on-optional-type-b171e1b397bb">Must(read) on Optional(type)</a> was originally published in <a href="https://medium.com/12-developer-labors">12 developer labors</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Optimizing database inserts in java. Pointers for spring and JPA users.]]></title>
            <link>https://medium.com/12-developer-labors/optimizing-database-inserts-in-java-pointers-for-spring-and-jpa-users-3015c55ca2a5?source=rss-b9d374def95a------2</link>
            <guid isPermaLink="false">https://medium.com/p/3015c55ca2a5</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[hibernate]]></category>
            <category><![CDATA[spring-data]]></category>
            <category><![CDATA[persistence]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[piotr szybicki]]></dc:creator>
            <pubDate>Sun, 20 Jan 2019 12:11:42 GMT</pubDate>
            <atom:updated>2019-01-20T12:11:42.245Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*QgjySVrFlK_E6We5.jpg" /><figcaption><a href="http://www.picpedia.org/highway-signs/images/database.jpg">http://www.picpedia.org/highway-signs/images/database.jpg</a></figcaption></figure><h4>As queue is not always a solution :)</h4><p>I met a lot of engineer over the years. And I’m not talking about the software engineers but construction, agriculture, bio etc. We all share one thing in common. We can solve any problems with<em> </em><strong><em>the tools that we know of</em></strong>. Student with 0 years of experience can solve the same problems using for loops and if statements as they guy that sits on a bench since 1985 and will use functors and monads. The difference will always be in a quality of that solution. In how extensible , how readable code , how performant the solution will be.</p><p>The reason for this overly long introduction and the main focus of this article is that part above that i put in bold <strong>“The tools that we know of”</strong>. You see the value of experience in any profession comes form expanded knowledge. It is very hard to think about something that we have never thought before. But it’s quite easy to do the opposite. Think about something that already crossed our mind. There is a linear dependency between how much we know and how much we are worth in a job market.</p><p>In this peace I want to expand your understanding how inserts are done and what we can do to optimize them. This was the problem I encounter many years ago when I was still a rooke. And back then I totally over-engineer the solution. Fortunately I have enough notes. So I can recreate a problem and this time solve it better.</p><h3>Don’t trust tutorials</h3><p>To protect privacy of my work I will show a fake entities. But the rest is real I promise. The full code to this article can be found in my github repo at the bottom of this page. The basic diagram is shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/688/1*HnjQyjnryNCN6umW9Xhkvg.png" /></figure><p>And The classes (parts of it that matter)</p><pre>@Entity(name=&quot;movie_separate_sequence&quot;)<br>@Table(name=&quot;movie_separate_sequence&quot;)<br>public class Movie {<br><br>    @Id<br>    @GeneratedValue<br>    private <strong>Long</strong> id;<br><br>    @OneToOne(mappedBy = &quot;movie&quot;, cascade = CascadeType.<em>ALL</em>,<br>            fetch = FetchType.<em>LAZY</em>, optional = false)<br>    private <strong>MovieDetails</strong> movieDetails;<br>...<br>}</pre><p>—</p><pre>@Entity(name = &quot;movie_details_separate_sequence&quot;)<br>@Table(name = &quot;movie_details_separate_sequence&quot;)<br>public class MovieDetails {<br><br>    @Id<br>    @GeneratedValue<br>    private <strong>Long</strong> id;<br><br>    @OneToOne(fetch = FetchType.<em>LAZY</em>, cascade = CascadeType.<em>ALL</em>)<br>    @JoinColumn(name = &quot;movie_id&quot;)<br>    private <strong>Movie</strong> movie;<br><br>    @OneToMany(<br>            cascade = CascadeType.<em>ALL</em>,<br>            orphanRemoval = true<br>    )<br>    private <strong>List&lt;Actor&gt;</strong> actors = new ArrayList&lt;&gt;();<br>...<br>}</pre><p>—</p><pre>@Entity(name = &quot;actor_separate_sequence&quot;)<br>@Table(name = &quot;actor_separate_sequence&quot;)<br>@NoArgsConstructor<br>@AllArgsConstructor<br>@Data<br>public class Actor {<br><br>    @Id<br>    @GeneratedValue<br>    private <strong>Long</strong> id;<br>...<br>}</pre><p>This set up in various forms can be found in hibernate tutorials all over net. And it has one basic advantage it is simple. All annotations translate to plane english we can understand what is going on. But do we really let’s take a look at the log with the sql statements enabled:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9ca3323db6d83756807cc7fa3b65abfc/href">https://medium.com/media/9ca3323db6d83756807cc7fa3b65abfc/href</a></iframe><p>Whaat? 18 sql statements have been executed to insert a 5 records . When I lunch my performance test (I will talk later), The target response time below 50 ms was never met. The fastest response time was above 100 ms. And around 20 concurrent users I actually stated to receive timeouts. And I had db and my app on the same server if I were to add the network latency things would be much worse. So what can we do about that. Well first if we have truly one to one relationship there is no need for separate id for move and movie_details. We do it by removing @GeneratedValue from the id field and adding @MapsId.</p><pre>public class MovieDetails {<br><br>    @Id<br>    private Long id;<br><br>    @OneToOne(fetch = FetchType.<em>LAZY</em>)<br>    @MapsId<br>    private Movie movie;<br>...<br>}</pre><p>This cut’s the number of executed statements to 16. Strill not not great. But this is the first lesson thing about the Id. Aside from the fact that you don’t have to go to the db to fetch next id you are also saving memory. Remember that the id columns are often index and in order for index to be performant it has to sit in memory. And in order to sit in memory it has to fit there first.</p><p>What else can we do. Well if you take a look at the listing above you see that there are two statements executed every time we need a new id. That’s no good. Fortunately we can enable sequence caching. More in this blog post:</p><p><a href="https://vladmihalcea.com/hibernate-hidden-gem-the-pooled-lo-optimizer/">Hibernate pooled and pooled-lo identifier generators - Vlad Mihalcea</a></p><p>So now our movie class look somthing like that:</p><pre>public class Movie {<br><br>    @Id<br>    @GenericGenerator(<br>            name = &quot;movieSequenceGenerator&quot;,<br>            strategy = &quot;enhanced-sequence&quot;,<br>            parameters = {<br>                    @org.hibernate.annotations.Parameter(<br>                            name = &quot;optimizer&quot;,<br>                            value = &quot;pooled&quot;<br>                    ),<br>                    @org.hibernate.annotations.Parameter(<br>                            name = &quot;initial_value&quot;,<br>                            value = &quot;1&quot;<br>                    ),<br>                    @org.hibernate.annotations.Parameter(<br>                            name = &quot;increment_size&quot;,<br>                            value = &quot;20&quot;<br>                    )<br>            }<br>    )<br>    @GeneratedValue(<br>            strategy = GenerationType.<em>SEQUENCE</em>,<br>            generator = &quot;movieSequenceGenerator&quot;<br>    )<br>    private <strong>Long</strong> id;<br>....<br>}</pre><p>With that optimization now our insert look like that:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c9e5231c557e6e4850c6e27ae11da1df/href">https://medium.com/media/c9e5231c557e6e4850c6e27ae11da1df/href</a></iframe><p>So we already cut our number of statements executed by half. Now it is time to turn our eye on the @OneToMany relation between movie details and actors. As we can see hibernate executes two and insert to some intermediate table. That table hold the mapping of movie id to actor id.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/269/1*Nt15s-psUxs179uSbBzYJQ.png" /></figure><p>We don’t need that it’s just we se establish one way mapping. If we want to keep this as one way relation we can do that but only partially we will stlee execute six statements it’s just 3 of them are updates. This is because of a flush order put in hibernate. First are all the inserts then all the updates. If you are interested more on this can be found here:</p><p><a href="https://vladmihalcea.com/the-best-way-to-map-a-onetomany-association-with-jpa-and-hibernate/">The best way to map a @OneToMany relationship with JPA and Hibernate - Vlad Mihalcea</a></p><p>In order to avoid all of that we have to use have a bidirectional OneToMany. Our example is not ideal for this as in reality we want to have many actors assigned to many moves. But for the sake of arguments let&#39;s say that it’s not the case. And Between Movie Details and the actors there is truly one to many relationship.</p><pre>//MovieDetails.java<br>@OneToMany(<br>        mappedBy = &quot;movieDetails&quot;,<br>        fetch = FetchType.<em>LAZY</em>,<br>        cascade = CascadeType.<em>ALL</em>,<br>        orphanRemoval = true<br>)<br>private <strong>List&lt;Actor&gt;</strong> actors = new ArrayList&lt;&gt;();</pre><pre>//Actor.java<br>@ManyToOne(fetch = FetchType.<em>LAZY</em>)<br>@JoinColumn(name = &quot;movie_details_id&quot;)<br>private <strong>MovieDetails</strong> movieDetails;</pre><p>By adding this code statement log looks like this</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d120a3eb6f79149cfb3e0ba05721a5fa/href">https://medium.com/media/d120a3eb6f79149cfb3e0ba05721a5fa/href</a></iframe><p>Five inserts for five records. I guess we can’t do much better. Well we can add more hardware to db. SSD disk more RAM and more CPU but in the end we will hit that limit. And what to do then. Well the reason the insert to db are so expensive is because they have to transit from one consistent state to the other, and they have to be durable, meaning the power shutdown would not result in data loss. And if we are not willing to compromise that there is little we can do.</p><h4>So what is importland</h4><p>On the other hand if speed is essentially we have to pay for it with consistency. And this is really a question to the business what will cost us more. For domains like hospitals, or nuclear missiles we can’t compromise. I mean it’s better for the patient operation to be delayed 5 minutes then to cut off the wrong leg. It’s not like you can send email after and say that you are “sorry, here is 50 % discount for the next operation”.</p><p>But we can send email in we sell tickets to to movie and we book the same sit twice. Here the situation is reversed the anxious teenager will go to different site if he/she have to wait 20 second for a transaction to be confirmed.</p><p>For the second situation we can implement a queue. Basically put the records to a list and then in the background put those record into a database. No real magic but because all that will happen in-memory it can be lightning fast.</p><h4>Tests and results</h4><p>I’m not going to bother you with all the intermediate stages just present the worst and the best result. As you can see the difference is quite substantial.</p><p>On the horizontal axis you have the response time and on the vertical line the percentage of all request that were fulfilled in that time. Bacues I slowly ramp up the users from 0 to 40. There was the point at witch I started to receive timeouts and 30% requests timeout.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/888/1*XGduvT6_T-8M9whPUlGfcw.png" /><figcaption>No optimizations done at all</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*7GvhmYNSUSFXDBdCEFtt1w.png" /><figcaption>all of the optimizations</figcaption></figure><p>So there you have it. The comparison of two solutions. The funny thing is that the first one can be found in so many tutorials on the internet. So many examples on stack overflow that are probably mindlessly copied to production code. We have to stop doing that. Making changes that we do not fully understand. Because we might pay a price and not even know it.</p><h3>Curious case of Spring CRUD repository</h3><p>Let’s say we have the following case. I have a mobile app that can send a purchase orders from many, many clients. And as a form of optimization I want a client app to be able to generate id for that sale that will be unique and I want to use that id as primary key in my database. Wheel the randomly generated <a href="https://en.wikipedia.org/wiki/Universally_unique_identifier">UUID</a> is perfect candidate for that. So I have to modify my Entities:</p><pre>@Id<br>@Column(<strong>columnDefinition = &quot;BINARY(16)&quot;</strong>)<br>private UUID id;<br><br>@OneToOne(mappedBy = &quot;movie&quot;, cascade = CascadeType.<em>ALL</em>,<br>        fetch = FetchType.<em>LAZY</em>, <strong>optional = true</strong>)<br>private MovieDetails movieDetails;</pre><p>I had to switch optional to true. This is because hibernate flush order (I don’t want to get in to that) and change the type of the column. There is something to notice here. The UUID will take more space in memory then Long. And as I mentioned before it is important to keep index size small. Then I had my spring repository:</p><pre>@Repository<br>public interface MovieSameIdUUIDAssignedRepository extends CrudRepository&lt;Movie, UUID&gt; {<br>}</pre><p>And service:</p><pre>@Autowired<br>private MovieSameIdUUIDAssignedRepository repository;</pre><pre>@PostMapping(&quot;/sameIdUUIDAssigned&quot;)<br>public UUID createAll(@RequestBody Movie movie){<br>    Movie saved = repository.save(movie);<br>    return saved.getId();<br>}</pre><p>but when I called that service I got:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/75d6e58fb3e7c20bc9e220db9b8266c2/href">https://medium.com/media/75d6e58fb3e7c20bc9e220db9b8266c2/href</a></iframe><p>What why there are five selects? Well as it turns out there are two methods on EntityManager (JPA interface that interact with persistent context) one is called <strong>merge(T entity)</strong> and another is called <strong>persist(T entity)</strong>. The main difference is that merge will call select and then if entity is found it will execute update if not insert. On the other hand persist will always execute insert and if the record with that id is already in the db it will throw error. When we are using spring repo and we have assigned id to entity already it will always choose merge (bellow is part of source code of the two spring classes):</p><pre>//AbstractEntityInformation.java<br>public boolean <strong><em>isNew</em></strong>(T entity) {<br><br>   ID id = getId(entity);<br>   Class&lt;ID&gt; idType = getIdType();<br><br>   if (!idType.isPrimitive()) {<br>      return id == null;<br>   }<br><br>   if (id instanceof Number) {<br>      return ((Number) id).longValue() == 0L;<br>   }<br>......<br>}</pre><pre>//SimpleJpaRepository.java<br>if (entityInformation.<strong><em>isNew</em></strong>(entity)) {<br>   <strong>em.persist(entity);</strong><br>   return entity;<br>} else {<br>   return <strong>em.merge(entity)</strong>;<br>}</pre><p>But in this case we want to persist, we know that this record do not exist in the db. Well the best thing we can do it to go around repo directly to the source</p><pre>@Autowired<br>private EntityManager entityManager;<br>...<br>entityManager.persist(movie);</pre><p>And the log get back to normal</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f27908c275978b561963def032a44c7c/href">https://medium.com/media/f27908c275978b561963def032a44c7c/href</a></iframe><h4>The cost of ignorance.</h4><p>I also did the performance test for case above. It is a different set up. In order to show the cost I had to instantiate my database in the could in order to show the cost of those additional selects. When you have a small dataset and your db is local the result ware almost identical. But when network latency kicked in this is what I saw.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/889/1*buIUagJrTFWmgm2CC5IISw.png" /><figcaption>using repo</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/882/1*CAHjU-ADIxERxuRaULAa9w.png" /><figcaption>Using entity manager</figcaption></figure><h3>Summary</h3><p>To be honest I have only one thing to say</p><pre>spring.jpa.show-sql=true<br>spring.jpa.properties.hibernate.format_sql=false</pre><p>are your friends enable them when you develop and analyze the logs see if thy makes sense because you might be paying a price for ignorance. I cured my by reading Vlad’s blong a lot of in this article is from his work.</p><h3>Resources.</h3><h4>The gatling script</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9fab36be614809e9fe0ed0d757909247/href">https://medium.com/media/9fab36be614809e9fe0ed0d757909247/href</a></iframe><h4>movieDetails.json</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/80595a1df8d00bc7ddc1a4ac420b73ab/href">https://medium.com/media/80595a1df8d00bc7ddc1a4ac420b73ab/href</a></iframe><h4>Java project used for testing</h4><p><a href="https://github.com/kwaspl/blog_posts/tree/master/insert-performance">kwaspl/blog_posts</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3015c55ca2a5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/12-developer-labors/optimizing-database-inserts-in-java-pointers-for-spring-and-jpa-users-3015c55ca2a5">Optimizing database inserts in java. Pointers for spring and JPA users.</a> was originally published in <a href="https://medium.com/12-developer-labors">12 developer labors</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring Boot, file upload via Rest Controller.]]></title>
            <link>https://medium.com/12-developer-labors/spring-boot-file-upload-via-rest-controller-6dcc7e5d6e54?source=rss-b9d374def95a------2</link>
            <guid isPermaLink="false">https://medium.com/p/6dcc7e5d6e54</guid>
            <category><![CDATA[spring]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[http-request]]></category>
            <category><![CDATA[lessons-learned]]></category>
            <dc:creator><![CDATA[piotr szybicki]]></dc:creator>
            <pubDate>Sat, 22 Dec 2018 14:18:22 GMT</pubDate>
            <atom:updated>2018-12-22T14:18:22.589Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*fA6oOl3SZrjjQIk0.png" /><figcaption>source: <a href="https://www.elegantthemes.com/blog/wp-content/uploads/2014/10/UploadLimit-Header.png">https://www.elegantthemes.com/blog/wp-content/uploads/2014/10/UploadLimit-Header.png</a></figcaption></figure><h3>Spring, file upload via multipart/form-data</h3><p>Two days ago I started on a new story on a project that i’m involved in. And frankly I told on stand up on Tuesday that I will be done in 2 hours and after that I will pick up a new task from the back log. Today is Saturday evening I spend total of 26 hours on that problem and ultimately I had to debug spring source code to get to the bottom of this. And I hadn&#39;t his much fun in a long time. And I thought I share what I have learned.</p><p>The requirement was: In a web page build a form that will contain one text input field and one input for file upload. Simple enough. This is the form:</p><pre>&lt;form id=”data” <strong><em>method=”PATCH”</em></strong> action=”/f” &gt;<br>   &lt;input <strong><em>type=&quot;text&quot;</em></strong> required name=&quot;company&quot; &gt;<br>   &lt;input <strong><em>type=&quot;file</em></strong>&quot; required name=&quot;definition&quot; /&gt;<br>&lt;/form&gt;</pre><p>and the metod in my RestController</p><pre>@RequestMapping(value = <strong>&quot;/f&quot;</strong>,method = <strong><em>PATCH</em></strong>)<br><strong>public void </strong>upload(<br>      @RequestPart(<strong>&quot;definition&quot;</strong>) MultipartFile definition,<br>      @RequestPart(<strong>&quot;</strong>company<strong>&quot;</strong>) String company<br>) {...}</pre><p>Notice the method it is <strong>PATCH </strong>(as per requirement) not <strong>POST</strong> it will become relevant in a little bit. And part of the requirement it was to be ajax request not form submit. At first i used jquery but as I was going lower in to the problem i used the following code:</p><pre>var fileInput = ...; //this is html element that holds the files<br>var textInput = ...; //thi is the string</pre><pre>var fd = new FormData();<br>fd.append(&#39;definition&#39;,fileInput.files[0]);<br>fd.append(&#39;name&#39;, textInput );<br>xhr = new XMLHttpRequest();<br>xhr.open( &#39;PATCH&#39;, uploadForm.action, true );<br>xhr.send( fd );</pre><p>But whatever I do I couldn’t make it to work. I always got the following exception:</p><pre>MissingServletRequestPartException: Required request part ‘definition’ is not present</pre><p>First thing i did was to streap this problem to the bare mimum. So I changed the request type to post and deleted the textInput. That seem to work after I changed my implementation of MultiPart resolver from org.springframework.web.multipart.support.StandardServletMultipartResolver to org.springframework.web.multipart.commons.CommonsMultipartResolver</p><pre>@Configuration<br><strong>public class </strong>MyConfig {<br><br>   @Bean<br>   <strong>public </strong>MultipartResolver multipartResolver() {<br>      <strong>return new </strong>CommonsMultipartResolver();<br>   }<br>}</pre><p>That also requires addition of <strong>commons-fileupload</strong> library to your classpath. Ok so I had the basic example working but whenever I added a string variable back the error returned (now the the error was about the string field not the file field). For some reason the multi part request resolver couldn’t find that part. Here what actually came to rescue was the documentation to the FormData object. In it you can read that the <strong>append</strong> method (i was using it, as that is most of the examples on the net that I have seen). Append method invoked on the FormData object accepts two parameters name and value (there is a third but is not important) The value field can be a <a href="https://developer.mozilla.org/en-US/docs/Web/API/USVString">USVString</a> or <a href="https://developer.mozilla.org/en-US/docs/Web/API/Blob">Blob</a> (including subclasses such as <a href="https://developer.mozilla.org/en-US/docs/Web/API/File">File</a>). When I changed the java code to:</p><pre>var fileInput = ...; //this is html element that holds the files<br>var textInput = = new Blob([&#39;the info&#39;], {<br>   type: &#39;text/plain&#39;<br>});</pre><pre>; //thi is the string</pre><pre>var fd = new FormData();<br>fd.append(&#39;definition&#39;,fileInput.files[0]);<br>fd.append(&#39;name&#39;, textInput );<br>xhr = new XMLHttpRequest();<br>xhr.open( &#39;PATCH&#39;, uploadForm.action, true );<br>xhr.send( fd );</pre><p>It suddenly started to work :). So what was going on. As explanation is really helpful here. To answer this question we have to take a look at what browser is sending.</p><pre>— — — WebKitFormBoundaryHGN3YjdgsELbgmZH</pre><pre>Content-Disposition: <strong>form-data; name=”definition”; filename=”test.csv” Content-Type: text/csv</strong></pre><pre>this is the content of a file, browser hides it.<br>— — — WebKitFormBoundaryHGN3YjdgsELbgmZH Content-Disposition:<strong> form-data; name=”name” </strong></pre><pre>this is the string<br>— — — WebKitFormBoundaryHGN3YjdgsELbgmZH —</pre><p>Can you notice what is missing in the content disposition header? Two things filename (that one is not so important, I told you that append accepts 3 parameters filename is that third). And much more important Content-Type. Every entry in multi-part form, during processing by the servlet , becomes a <strong>MultipartFile</strong>. And I order to be converted to that file it has to have a content type. Deep inside the <strong>commons-fileupload</strong> library there is a line of code:</p><pre>String subContentType = headers.getHeader(<strong><em>CONTENT_TYPE</em></strong>);<br><strong>if </strong>(subContentType != <strong>null ... ){}</strong></pre><p>This get’s the content type and if it’s null processing goes via different path that turn our part into MultipartParameter (that is put in a different map and spring is not looking at it) instead of MultipartFile. And later spring creates the separate instance for every parameter form the form that we want to bind when invoking our rest method. Using class RequestPartServletServerHttpRequest. In it constructor we can find the where the exception is thrown.</p><pre>HttpHeaders headers = <strong>this</strong>.<strong>multipartRequest</strong>.getMultipartHeaders(<strong>this</strong>.<strong>partName</strong>);<br><strong>if </strong>(headers == <strong>null</strong>) {<br>   <strong>throw new </strong>MissingServletRequestPartException(partName);<br>}</pre><p>I spare the reader the rest of the spring source code, it is just important to know that getMultipartHeaders only looks at multipart files not parameters. So that is why adding the blob with specific type solve issue number 1 (Most tutorials on the internet are missing that part, they only deal with the form that has one file field).</p><pre>var textInput = = new Blob([&#39;the info&#39;], {<br>   type: &#39;text/plain&#39;<br>});</pre><p>Now taking a step back i mentioned that i had to switch to using POST when i changed to PATCH the problem came back. Error was the same. And I was puzzled. So I dived back to the source code (After all thi is ultimate documentation). The answer was a bit simpler this time. Remember that I switched to the CommonsMultipartResolver at the beginning of this article. It turns out that during request processing this method is invoked:</p><pre><strong>public static final boolean </strong>isMultipartContent(<br>        HttpServletRequest request) {<br>    <strong>if </strong>(!<strong><em>POST_METHOD</em></strong>.equalsIgnoreCase(request.getMethod())) {<br>        <strong>return false</strong>;<br>    }<br>    <strong>return </strong>FileUploadBase.<em>isMultipartContent</em>(<strong>new </strong>ServletRequestContext(request));<br>}</pre><p>So where is waldo? If you study the code for 5 seconds it is obvious. If it’s not a POST request it is immediately determined that this request do not have multipart content. I got around that by overriding method that is calling the static methods above.</p><p>So now by config bean looks like this:</p><pre>@Bean<br><strong>public </strong>MultipartResolver multipartResolver() {<br>   <strong>return new </strong>CommonsMultipartResolverMine();<br>}<br><br><br><strong>public static class </strong>CommonsMultipartResolverMine <strong>extends </strong>CommonsMultipartResolver {<br><br>   @Override<br>   <strong>public boolean </strong>isMultipart(HttpServletRequest request) {<br>      <strong>final </strong>String header = request.getHeader(<strong>&quot;Content-Type&quot;</strong>);<br>      <strong>if</strong>(header == <strong>null</strong>){<br>         <strong>return false</strong>;<br>      }<br>      <strong>return </strong>header.contains(<strong>&quot;multipart/form-data&quot;</strong>);<br>   }<br><br>}</pre><h3>Summary</h3><p>And that is it. The whole things works like a charm :) I think the biggest lesson from all of it is to not be afraid to investigate in depth. There is a crop of developers out there that would just try solution from Stack Overflow (you would not believe how much bullshit is there) until one of them works. This is not the correct approach. In order to be a good developer you have to understand both the consequences of a change and the reason for bug. Before you type a single letter.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6dcc7e5d6e54" width="1" height="1" alt=""><hr><p><a href="https://medium.com/12-developer-labors/spring-boot-file-upload-via-rest-controller-6dcc7e5d6e54">Spring Boot, file upload via Rest Controller.</a> was originally published in <a href="https://medium.com/12-developer-labors">12 developer labors</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Some things I wish I knew before I start to work with Angular: NgRx]]></title>
            <link>https://medium.com/12-developer-labors/some-things-i-wish-i-knew-before-i-start-to-work-with-angular-ngrx-6c51b9596751?source=rss-b9d374def95a------2</link>
            <guid isPermaLink="false">https://medium.com/p/6c51b9596751</guid>
            <category><![CDATA[ngrx]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[angular2]]></category>
            <dc:creator><![CDATA[piotr szybicki]]></dc:creator>
            <pubDate>Sun, 09 Dec 2018 14:12:35 GMT</pubDate>
            <atom:updated>2019-01-02T09:45:51.824Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Znalezione obrazy dla zapytania ngrx" src="https://cdn-images-1.medium.com/proxy/1*hj71wy_fVD1qIG8q9mnPjg.png" /><figcaption>source: <a href="https://cdn-images-1.medium.com/max/1200/1*hj71wy_fVD1qIG8q9mnPjg.png">https://cdn-images-1.medium.com/max/1200/1*hj71wy_fVD1qIG8q9mnPjg.png</a></figcaption></figure><p>It will be final peace on my series abut lessons learned in angular. I will write other pieces but they won’t be about basic building blocks of angular.</p><p>As soon as we start to move beyond writing hello world application in angular. We start to run in to serious problem, how do we manage state in our application.</p><p>There are two problem with the state in the angular application, first it has to be expressed (written down) using objects (that becomes our data model), and it has to be shared between components.</p><p>One solution is to use @Input, @Output annotations and data binding to communicate state changes to other components. Two problems with that approach: <strong>one </strong>if application has more that 3 components the task becomes tedious and complicated (and as the title of this blog suggest I hate complexity) two you can’t pass or emit event from components that are used as router path. To that option is out the window for anything more complicated the home page that I doing for my grandpa :).</p><p>Second option is to use services. Now that one is more viable. You at least don’t have the worry about &lt;router-outlet&gt; if you get your scopes right you can inject service everywhere you need it. The problem is that is simple only at the beginning. As your application grows so is the number of services. Object that represent the state mutate under you(you can fix that with immutable.js) introducing hard to track bugs. And the whole thing becomes a mess that someone will want to rewrite.</p><p>There is a third option, my recommendation, and that is to use <strong>NgRx</strong>. It is very simple library that allows us to hold the state in one place and inject single service that allows us to listen to the changes. It uses the RxJS to communicate change to our state, data model so it fits the opinionated angular landscape. It is immutable so all those bugs that offend appear when dealing with complicated state disappear. If your project is going to be big I recommend to introduce NgRx right from the start. It is way easier to refactor when new businesses requirement forces developer to change his/her beautifully thought out structures :). I will not consider that over-engineering as you will see in the minute using NgRx is just using services but more tidy.</p><h3>How to start</h3><p>There is plenty of good tutorials, but I want to make this articles consistent. And this will be part of demonstration how simple using ngrx is. Install it:</p><pre>npm install @ngrx/store</pre><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*yIyrhmpwsDxgmUnU5fgCyw.png" /></figure><p>Then we need two things action and reducer. <strong>Action</strong> is an object that you dispatch when you want your application state to change. That is passed to the <strong>reducer</strong>, function that’s job is to take the action and use it’s payload to create new <strong>state</strong>. State is immutable and is persisted to the store. Where it can be retrieved from by other components. The diagram below shows this very simple flow. (There are also selectors that allow us to do some narrowing of the results, thus keeping out code cleaner. I will talk about the, leater.)</p><pre>//AddToMenu.action.ts<br>export class AddToMenu implements Action {<br>  readonly type:string = &#39;[Menu] addToMenu&#39;<br>  constructor(payload:any){<br>    this.payload = payload;<br>  }<br>}</pre><pre>//MenuReducer.reducer.ts<br>export function menuReducer(state = {appState:null}, action:Action){<br>  <strong>if(action.type == &#39;[Menu] addToMenu&#39;){</strong><br>    return {appState: action.payload};<br>  }<br>}</pre><pre>//Menu.component.ts<br>export class MenuComponent implements OnInit {<br>  constructor(private store$:Store&lt;Action&gt;){}<br>  ngOnInit(){<br>    this.store$<br>      .subscribe(t =&gt; console.log(t.payload))<br>  }<br>}</pre><p>Then you have to register that reducer, but I don&#39;t want to write fully functioning example, as there are plenty of good resource out there (<a href="https://ngrx.io/guide/store">https://ngrx.io/guide/store</a>). The point that I’m trying to make is that using NgRx is really easy to start with. But things get a little bit complicated :)</p><h3>As we grow !!!</h3><p>The big benefit of NgRx is the fact that the store is immutable. That means that everytime the reducer runs int has to return the entire new state (not for the entire application but for that pece the it is responsible). The state of our application is just <strong>json</strong> object and every reducer creates entry on the first level. So using example below to represent state in our application:</p><pre>{<br>  &quot;image&quot;:<br>  {<br>     &quot;url&quot;: &quot;images/0001.jpg&quot;,<br>     &quot;width&quot;: 200,<br>     &quot;height&quot;: 200<br>  },<br>  &quot;thumbnail&quot;:<br>  {<br>     &quot;url&quot;: &quot;images/thumbnails/0001.jpg&quot;,<br>     &quot;width&quot;: 32,<br>     &quot;height&quot;: 32<br>  },<br>  &quot;batters&quot;:<br>  {<br>    &quot;batter&quot;:<br>      [<br>	{ &quot;id&quot;: &quot;1001&quot;, &quot;type&quot;: &quot;Regular&quot; },<br>	{ &quot;id&quot;: &quot;1002&quot;, &quot;type&quot;: &quot;Chocolate&quot; }<br>      ]<br>    },<br>    &quot;topping&quot;:<br>      [<br>	<strong>{ &quot;id&quot;: &quot;5001&quot;, &quot;type&quot;: &quot;None&quot; },</strong><br>	{ &quot;id&quot;: &quot;5002&quot;, &quot;type&quot;: &quot;Glazed&quot; },<br>	{ &quot;id&quot;: &quot;5005&quot;, &quot;type&quot;: &quot;Sugar&quot; }<br>      ]<br>   }<br>}</pre><p>We can isolate 3 reducers: Image.reducer.ts, Thumbnail.reducer.ts and Batters.reducer.ts. Now if we want to add, or modify the highlighted topping then means that entire butters object has to be returned from the reducer. with that one property updated. As you can imagine your reducer can get complicated very fast with a lot nested if else statements. So my <strong>advice 1</strong>: If you have access to the entire object pass it on to your reducer (Not just changes and try to figure out what to update). It will keeps things simple. <strong>advice 2</strong>: Think about state structure constantly and refactor if necessary. As a former database developers I can tell that there is general fear when it comes to refactoring existing data model. Developers prefer to put a ton of code just to avoid messing it up. And as storage is a little like database (with only one user) I urge you to keep it as flat as possible. Better to have many reducers that are short and concise then one gigantic. The clean code evangelist preach short method for a long time and as reduces are just methods they should obey the same principles.</p><h3>As we grow part 2 :)</h3><p>In part two we will be talking about the other part of the equation. Reading state. In the example above I wrote:</p><pre>export class MenuComponent implements OnInit {<br>  constructor(private store$:Store&lt;Action&gt;){}<br>  ngOnInit(){<br>    this.store$<br>      .subscribe(t =&gt; console.log(t.payload))<br>  }<br>}</pre><p>That console.log will be triggered every time there is any change to the store. And this is not what we want. This component should be notified only when changes that are of interest to it happened. In the diagram above there is a circle just under component that reads selectors. And this is exactly what we are going to use.</p><pre>export class MenuComponent implements OnInit {<br>  constructor(private store$:Store&lt;Action&gt;){}<br>  ngOnInit(){<br>    this.store$<strong>.pipe(select(&#39;batters&#39;))</strong><br>      .subscribe(t =&gt; console.log(t.payload))<br>  }<br>}</pre><p>The above code will be triggered only when the change to the batters part of our model is made. Although we pass select to the pipe method it is not a function from RxJs. This operator is provided by the ‘@ngrx/store’. So <strong>advice 3</strong>: take to only things you need. ‘It&#39;s not how you store, it’s how you ask for it’.</p><h3>But it is about what you store. aka: S.H.A.R.I.</h3><p>To be honest this paragraph will be a ripoff of this <a href="https://youtu.be/t3jx0EC-Y3c">talk</a>. But as picasso said: “Good artists borrow great artists steal.” :). Plus I’ve been using the <strong>S.H.A.R.I.</strong> principle and I found it complete. Let’s face it NgRx is complicated (it is as complicated as it has to be to preserve clarity and verbosity) so it doesn’t make sense to put everything in the store. This are some principles to guide us thru the decision process.</p><p><strong>Shared</strong> — Shared state meaning that is not consumed by one element. I am a big advocate of separating business and display logic in to smart and presentation components. And I prefer to have one to one relationship. One presentation component wrapped around one smart component. And they have they own way of sharing data. So when I used term element I ment a grouping of the two. Great example of shared state is authorization data. It will be needed everywhere.</p><p><strong>Hydrated</strong> — as it has to be available next time you have to boot up. So this is all the cases where sessionstorage or localstorage come to play. User preferences are a good example of this.</p><p><strong>Available</strong> — I mentioned before that state that is access only form one component should not be persisted in the storage, but there is an exception. If the data to render this one component come from the route. Especially if you have to hit backend for that information.</p><p><strong>Retrieved</strong> — I touched on this before. If you call the external API to retrieve some data, that data becomes good candidate for storage. To be honest this one is a little bit of a judgment call. There are other ways to cache and re-emit data that have been fetched using <em>http.get(‘htps://…’). </em>For example using publishReplay(1), refCount(). There is a cool mechanizm in NgRx ecosystem that allows to move those side effects to a different peace of code. Thus keeping our components pure, called <strong>@ngrx/effects</strong> but I will not talk about here.</p><p><strong>Impact</strong> — state that is impacted by actions from other stores. To be honest i think that this one is a little bit redundant (folds nicely with the shared state) and i think the outhores just wanted to spell that mnemonic device a certain way. Just like S.H.I.L.D.</p><p>So now to the world of my personal opinions. What we should not put in the store. Number one forms. This is a little bit controversial. For example this <a href="https://www.youtube.com/watch?v=kPkTXdToYV0">talk</a> gives a different view point. But I feel like the Angular reactive forms API (that i recommend using) is it’s own from of storage. However forms are full of state full information, and we know that these are good candidate for persistence. I hear that argument but wat ultimately convinces me it that the context is usually self contain it is not shared anywhere. Also angular controls that make the form are nighter serializable or immutable, they will change without your knowing. <strong>Advice 4</strong>: Think what to put in a store.</p><h3>Naming convention and some useful patterns.</h3><p>This paragraph is going to be a link. Victor Savkin is one of the smartest guys in the angular community. In this article he gives a great advice on how some of the most popular messaging patterns translate into NgRX. He takes the examples from the book co-authored by Martin Fowler, and translate the mechanisms that can be found in big and small data centers across organizations into to localized one user pattern. And I can’t really improve on that.</p><p><a href="https://blog.nrwl.io/ngrx-patterns-and-techniques-f46126e2b1e5">NgRx: Patterns and Techniques</a></p><h3>NgRx is not a silver bullet. Summary.</h3><p>Fred Brooks in 1989 wrote and article ‘No silver bullet — essence and accident in software engineering’. There he explores the reasons why developers productivity can’t scale with the sames speed as moore’s law describes scaling hardware. It boils down to that we are dealing with real world problems that are as complicated as the are. And we can’t make them any simpler. I mean creating a bank account takes 50 steps (required by the regulators, parent company etc) and we will never be able to reduce that number. They are the essence of the business problem that we are trying to solve. We we aptly call it <strong>essential complexity</strong>. There is also <strong>accidental complexity</strong> this one it totally reducible as it is a fault of developer. This blog is my way of fighting that particular form of stupidity.</p><p>Anyway as i started to drift away from the subject. I believe the NgRx when used properly (or at least consistently) can help us reduce accidental complexity. By helping us avoid service injection hell and mutation hell that will inevitably happen if we try to solve them by yourself.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6c51b9596751" width="1" height="1" alt=""><hr><p><a href="https://medium.com/12-developer-labors/some-things-i-wish-i-knew-before-i-start-to-work-with-angular-ngrx-6c51b9596751">Some things I wish I knew before I start to work with Angular: NgRx</a> was originally published in <a href="https://medium.com/12-developer-labors">12 developer labors</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why we can’t inject TeplaterRef into a directive?]]></title>
            <link>https://medium.com/12-developer-labors/why-we-cant-inject-teplaterref-into-a-directive-b4c50e2bb0a4?source=rss-b9d374def95a------2</link>
            <guid isPermaLink="false">https://medium.com/p/b4c50e2bb0a4</guid>
            <category><![CDATA[angular]]></category>
            <dc:creator><![CDATA[piotr szybicki]]></dc:creator>
            <pubDate>Sun, 02 Dec 2018 09:13:27 GMT</pubDate>
            <atom:updated>2018-12-08T11:03:00.260Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/856/1*U5MC1pwNSArq0tn1qMDh_g.png" /></figure><h3>‘ <strong><em>No provider for TemplateRef</em></strong>’ Explained.</h3><p>Recently I started answering questions on stack overflow. I found this very rewarding as well as useful to retain the knowledge. As various projects or job changes may lead us in to a different avenues of massive field, that is programming.</p><p>I stumbled upon question that gave me pause. The error message read: ‘ <strong><em>No provider for TemplateRef</em></strong>’. I was interested. Especially that under a comment one of the guru in Angular community wrote: ‘ You missed basic knowledge about TemplateRef’. Which meant that I also lack some basic knowledge in that area. I didn’t like that at all. So i started my research. In this short article I will use directive (both structural and regular) to illustrate my point.</p><p>So we all know the structural directives. We use them all the time <strong>*ngIf</strong>, <strong>*ngFor</strong>, and maybe not so often used <strong>*</strong><a href="https://angular.io/api/common/NgSwitch"><strong>ngSwitch</strong></a>. Notice something very interesting. All those have the <strong>*</strong> in front of them. That star is used to do something very specific. It turn this:</p><pre>&lt;div *directive=&quot;3000&quot;&gt;Tesla was robbed !!!!&lt;/div&gt;</pre><p>into this:</p><pre>&lt;!--bindings={<br>  &quot;ng-reflect-directive-somevariable&quot;: &quot;3000&quot;<br>}--&gt;<br>&lt;div&gt;Tesla was robbed !!!!&lt;/div&gt;</pre><p>with and intermediate stage:</p><pre>&lt;ng-template [SomeVariable]=&quot;3000&quot;&gt;   <br>   &lt;div&gt;Tesla was robbed !!!!&lt;/div&gt;<br>&lt;/ng-template&gt;</pre><p>And this is declaration of our directive.</p><pre>@Directive({<br>    selector: &#39;[appStructural]&#39;<br>})<br>export class StructuralDirective {</pre><pre>constructor(<br>    private templateRef: TemplateRef&lt;any&gt;,<br>    private viewContainerRef: ViewContainerRef<br>){}</pre><pre>@Input(&#39;appStructural&#39;)<br>set someVariable(time: ViewContainerRef) {<br>    <strong>this.viewContainerRef.createEmbeddedView(this.templateRef);</strong><br>  }<br>}</pre><p>The line in bold is very important without it we will not see our component render on the DOM tree. And on the subject of this article. <strong>This is the only way we can inject a TemplateRef via the constructor</strong>. If we try to do this for the components or directives we will get the error <strong>NullInjectorError: No provider for TemplateRef!.</strong> This makes sense so far? Because smart or dumb person could ask. Ok if angular desugars the tag with the structural directives in to that &lt;compoent-tag&gt; and &lt;template&gt; then if I place my component inside &lt;ng-template&gt; manually</p><pre>&lt;ng-template&gt;   <br>   &lt;app-component&gt;&lt;/app-component&gt;<br>&lt;/ng-template&gt;</pre><p>I should be able to inject, the TemplateRef into that component. Sorry but no. That component is sill created by the View component factory and you can access it via ElementRef. More on this:</p><ul><li><a href="https://blog.angularindepth.com/exploring-angular-dom-abstractions-80b3ebcfc02">Exploring Angular DOM manipulation techniques using ViewContainerRef</a></li><li><a href="https://blog.angularindepth.com/here-is-what-you-need-to-know-about-dynamic-components-in-angular-ac1e96167f9e">Here is what you need to know about dynamic components in Angular</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b4c50e2bb0a4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/12-developer-labors/why-we-cant-inject-teplaterref-into-a-directive-b4c50e2bb0a4">Why we can’t inject TeplaterRef into a directive?</a> was originally published in <a href="https://medium.com/12-developer-labors">12 developer labors</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Some things I wish I knew before I start to work with Angular. Part 2. (Performance)]]></title>
            <link>https://medium.com/12-developer-labors/some-things-i-wish-i-knew-before-i-start-to-work-with-angular-part-2-performance-47cd834dc409?source=rss-b9d374def95a------2</link>
            <guid isPermaLink="false">https://medium.com/p/47cd834dc409</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[performance]]></category>
            <dc:creator><![CDATA[piotr szybicki]]></dc:creator>
            <pubDate>Fri, 23 Nov 2018 20:48:51 GMT</pubDate>
            <atom:updated>2018-11-23T20:48:51.282Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*sc-ZyNM_C9ik57jp.jpg" /><figcaption>source: <a href="https://www.techadvisor.co.uk/how-to/broadband/test-internet-speed-3521885/">https://www.techadvisor.co.uk/how-to/broadband/test-internet-speed-3521885/</a></figcaption></figure><p>Link to <a href="http://Some things I wish I knew before I start to work with Angular.">part 1.</a></p><p>A while ago I wrote a article about HTTP Caching and how to make our app load faster.</p><p><a href="https://medium.com/12-developer-labors/http-caching-with-hazelcast-and-other-trics-how-to-make-my-angular-app-load-faster-aeaa90562e94">HTTP caching with hazelcast, and other trics how to make my angular app load faster.</a></p><p>This one will be set in the world of performance. We will focus on performance of the code in the angular. And some coding styles that can help us write more user friendly application. As well as write more maintainable code. Because, whether intentionally or not, taking performance in to account make it also more readable.</p><h3><strong>Change Detection, understand it.</strong></h3><p>Change detection. A mysterious beast that abstracts away the re rendering of component whenever we update our model. I will not try to explain the entire process as the article from angular university does great job.</p><p><a href="https://blog.angular-university.io/how-does-angular-2-change-detection-really-work/">Angular Change Detection - How Does It Really Work?</a></p><p>But basically every component has it’s own change detector and it can be set to <strong>Default </strong>or <strong>OnPush</strong>. Default means that when change detection is triggered the properties of the model (all the bindings <em>[someObject]=”object”</em> ) are compared property by property (this is quite slow). You have to know that change detection pass can be executed hundred’s of times a second.</p><p>Let’s say you bind an object with 100 fields to be displayed in a child component wouldn&#39;t it be better if you can just <em>oldObject === newObject</em>. Quick reference check is way faster. And this is exactly what <strong>OnPush </strong>does. I strongly encourage to set this property on all your components. Because it demand from the developer to fallow the concept they should be following anyway:</p><h4>Immutability</h4><p>The backend developers got clever some time ago and said ‘from now on our apps will be stateless’. This was very clever on their part as a lot of bugs want away but that complexity has to go somewhere (there is no free lunch). Some of it want to DB but most of it was put to the front. And suddenly the same bugs that java developers had to deal with start poping up in work of Angular, React, Vue.js developers. Decent way to attack the problem for the backend developers was to create immutable data-structures with immutable objects in them. So Facebook engineers, clever beast they are, create a library called Immutable.js that helps you do exactly that but in java script.</p><p><a href="https://facebook.github.io/immutable-js/">Immutable.js</a></p><p>You see I lie to you a little bit earlier when i said that state, and state mutation is bad. Hidden state mutation is bad. As it makes harder to track the changes to an object in your application. Immutability is not really about removing state it is about making state changes more explicit. Immutable.js helps us to achieve exactly that. By creating collections, objects that can’t change. the only way is to go from state 1 -&gt; state 2 is to recreate original object with new properties.</p><p>That also means that the address in memory, reference adders will change. And that we are going back the full circle. Remember when I told you the onPush does quick reference check :) that is why using immutalbe.js is so advantageous.</p><p>So how we can use it. Well we have collections and the elements in those collections and depending on your use case you might need to make them both immutable.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c2afb0dc225c443015aead661d9abd06/href">https://medium.com/media/c2afb0dc225c443015aead661d9abd06/href</a></iframe><p>This is how you work with the simple object, in my case it is a very simple address object. There is a lot of boilerplate involved but this is the price we pay. But to quote a scene from one of my favorites movies ‘Equilibrium’: “Havy cost, I pay it gladly”. To be honest it is a little bit of hack that we have to use as there is nothing baked in to a language it’s self that would allow us to protect the access.</p><p>There is a world read-only in typescript spec but let’t be honest without a run-time check it is pretty useless. As I demonstrate it in the above example (line 27).</p><p>Fortunately we don’t have to play around with the collections that much. And to be honest we need it far more than the immutable objects. Especially that more often then not we pass observable to the component rather then bind the object itself. But we will deal with that later. So back to collections. Aside a few exceptions (and you will find them pretty fast if you depend on a behavior like pop) they work just like the collection native to javascript.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f77ff78c6aa690b4d7466827d6175770/href">https://medium.com/media/f77ff78c6aa690b4d7466827d6175770/href</a></iframe><p>As you can see there are no difference. I encourage you to take a look at the documentation it is well written and with many examples.</p><h4>Usage of trackBy</h4><p>Of course we can’t talk about the collection and not talk about this little guy. Because let’s say we have a following scenario. We have a list of 100 elements. And we are not paging it. Everything gets displayed at once. And now assume that we have to add one list to that element (BTW immutable.js has nothing to do with this, the same can be expected when using native collections) Then if we are using structural directive *ngFor:</p><pre>&lt;ul&gt;<br>    &lt;li *<a href="https://angular.io/api/common/NgForOf">ngFor</a>=&quot;let hr of heroes&quot;&gt;{{hr.name}}&lt;/li&gt; <br>&lt;/ul&gt;</pre><p>All elements will be re-rendered. Angular just has no way of knowing which has changed. There is no notion of identity. And we have to provide it. Using cool function called trackedBy.</p><pre>&lt;ul&gt;<br>   &lt;li *<a href="https://angular.io/api/common/NgForOf">ngFor</a>=&quot;let hr of heroes;trackBy: trackByFn&quot;&gt;{{hr.name}}&lt;/li&gt;<br>&lt;/ul&gt;</pre><p>And then in component:</p><pre>trackByFn(index, item) {    <br>   return item.id  <br>}</pre><p>It will course only a inserted element to be re-rendered. And if we delete the element the browser rendered will not be triggered. Very nice blog post:</p><p><a href="https://netbasal.com/angular-2-improve-performance-with-trackby-cc147b5104e5">Angular 2 — Improve Performance with trackBy</a></p><h4>Pure pipes</h4><p>OK, So we covered some cases where using property binding with <strong>onPush </strong>strategy can help us. But it is not always enough. You see i keep important information for the patient ones :). It is not only when the reference binding changes angular trigger the change detection. It is also when the event is fired from the component. And the behavior is the same both for custom and the javascript events(the one that bubble). And that is a good thing, there is no way of knowing if our event make some changes in that component (it could do that without changing bindings).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9391216c5190559678cb83ad12874e50/href">https://medium.com/media/9391216c5190559678cb83ad12874e50/href</a></iframe><p>Lets take a look at the above code. We have a list of components (that display movie titles, as buttons) and when user clicks on the button it removes it form the list and consequently from the page.</p><p>In lines there are 3 possible implementations of this component (line: 9, 12, 15). Les’t say that we have businesses requirement to make all the titles uppercase ( stupid but it’t to illustrate a point). We have 3 options to make it happen. Function(line 9), Pipe(line 15) or modify the value before we pass it to the component (line 12).</p><p>The solution where we modify the value before it is bind is pretty ridged. It prevents re-usability of the data, plus it moves part of the display logic that belongs to this component outside of it. Not a good idea. Although there is no performance hit that I will be talking about in the next paragraph.</p><p>So it is between the pipe and function. But there is a problem. I told you that angular uses a reference check, so when the change detection pass gets to our movie component it has to re-run the function to obtain that reference. No imagine that you actually run more complex logic inside of that function or call backend for some additional data. No to mention that almost always the function will return object that will be in new location in memory thus re-rendering the component. The solution to that are pipes, more concretely pure pipes.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/edf82000e221900d3e61cc99eee5a1fb/href">https://medium.com/media/edf82000e221900d3e61cc99eee5a1fb/href</a></iframe><p>By default all pipes in angular are considered pure. So the line 3 in code above is not necessary. Angular can do all sorts of optimizations on when pure pipes are used. One it create a single instance of that pipe and shares it among components, second it can cache the input, output relationship and when the same input is passed angular will not recalculate the output.</p><p>Further reading:</p><p><a href="https://blog.angularindepth.com/the-essential-difference-between-pure-and-impure-pipes-and-why-that-matters-999818aa068">The essential difference between pure and impure pipes in Angular and why that matters</a></p><h4>Observable result caching and sharing</h4><p>This might be of limited use, but there ware couple of use cases in the past where I found it useful. In my case I was pulling a lot of data from the backend but the data have never changed. It was either a dictionary of some sort or list of items that I didn’t need to pull every time. Normally when you subscribe to regular observable all methods will be executed from the beginning (remember observable are just methods, well to be technical they are IO monads, I like to split hairs). And this might not always be what you need.</p><p>I found that making the observable into a shared, or connectable observable and buffering the output solves the issue.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7280682bf451e156ffd0e0d76ee31c7e/href">https://medium.com/media/7280682bf451e156ffd0e0d76ee31c7e/href</a></iframe><p>In the above example we subscribe to observable twice but http.get will be called only once because publishReplay(1), refCount().</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=47cd834dc409" width="1" height="1" alt=""><hr><p><a href="https://medium.com/12-developer-labors/some-things-i-wish-i-knew-before-i-start-to-work-with-angular-part-2-performance-47cd834dc409">Some things I wish I knew before I start to work with Angular. Part 2. (Performance)</a> was originally published in <a href="https://medium.com/12-developer-labors">12 developer labors</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>