<?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 Maciej Sikora on Medium]]></title>
        <description><![CDATA[Stories by Maciej Sikora on Medium]]></description>
        <link>https://medium.com/@macsikora?source=rss-ae51491fd44a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*PuyWYUyalvOmpGjMUg1BgA.jpeg</url>
            <title>Stories by Maciej Sikora on Medium</title>
            <link>https://medium.com/@macsikora?source=rss-ae51491fd44a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 04:10:54 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@macsikora/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[Algebraic Structures Explained — Part 1 — Base Definitions]]></title>
            <link>https://medium.com/@macsikora/algebraic-structures-explained-part-1-base-definitions-5aa36add8183?source=rss-ae51491fd44a------2</link>
            <guid isPermaLink="false">https://medium.com/p/5aa36add8183</guid>
            <category><![CDATA[elm]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[functional-programming]]></category>
            <dc:creator><![CDATA[Maciej Sikora]]></dc:creator>
            <pubDate>Wed, 25 Sep 2019 09:26:40 GMT</pubDate>
            <atom:updated>2019-09-25T09:26:40.507Z</atom:updated>
            <content:encoded><![CDATA[<h3>Algebraic Structures Explained — Part 1 — Base Definitions</h3><h3>Introduction</h3><p>The article is a opening of the series <strong>Algebraic Structures Explained</strong>. In the series I will try to cover useful programming abstractions which are grounded in math and specifically in the <a href="https://en.wikipedia.org/wiki/Abstract_algebra">abstract algebra</a>. The series is addressed to front-end devs, as I will show examples mostly in front-end based languages, but it doesn’t mean that somebody with different background can’t benefit from the content.</p><h4>Expectations</h4><p>I am not a mathematician, I am a developer, that is why this series is focuses more at the usage of those constructs rather than strict math theory. I will do my best in order to connect those two worlds, and present the topic in the most friendly way.</p><p>Jargon used in the series will not be strict or mathematical, also description of constructs can be less deep and accurate, I will explain them in my own way :wink:, if you see a mistake in any article from the series, please don’t hesitate to leave a comment.</p><p>Topics will be presented with code examples. I will use many programming languages, in most it will be TypeScript and Elm, but also be prepared for others, and the choose really depends from the topic and my mood 😀, yes really. But don’t be scary if you don’t know languages in which I write examples, code should be straight forward. Every snippet will be marked by language name. Code parts which are not marked will be pseudo code.</p><h4>Code standards</h4><p>I will provide code examples which will focus on the presented topic. I will sometimes skip some constructs like TS variable declarations(const,let,var), or module imports, sometimes I will also leave some code part as … in order to show that it is less important for the given subject.</p><h3>Base definitions — What is a set</h3><p>First of all, I am not talking about set as any specific implementation like <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set">set data structure in JS</a>, but set as more abstract mathematical concept — <a href="https://en.wikipedia.org/wiki/Set_(mathematics)">set</a><a href="https://en.wikipedia.org/wiki/Set_(mathematics)).">.</a></p><p>Set is just a collection of objects which have some common characteristic or are just listed as set members <em>S = {a,b,c}, Nat = {1,2,3…}</em>. We can understand common characteristic as a function which for a given object as an input, will return if the object is a member of the set or not.<em> isInSet: (a: Anything) -&gt; Yes | No</em></p><p>Ok, so what this characteristic can be? It can be literally anything which can be verified and brought to simple yes/no answer. To keep it simple we can assume that set can be created from any kind of elements, set can be created even from nothing, and this set is empty set <strong>∅</strong>, or in more software terms — <strong>void</strong>.</p><blockquote><strong>Exercise for the reader</strong> — void is an empty set, and what about null ?</blockquote><h3>Base definitions — What is a type</h3><p>What does it have to programming at all? Quite a lot. As we can think that type is a set. Taking into consideration type theory, type is a type, not a set. But for simplicity we can assume those terms are equal. Check out this great explanation about types as sets — <a href="https://guide.elm-lang.org/appendix/types_as_sets.html">Elm — types as sets</a>. So primary types in for example TypeScript, like number, bool, string, object are sets of some possible values with common characteristic, the same applies to other programming languages, even to dynamic typed ones, but there types are implicit. To give an illustration I will take the number type from TypeScript.</p><pre>[TS] isNumber = (a): a is number =&gt; typeof a === ‘number’</pre><p>Function <strong>isNumber</strong> is the number set <strong>characteristic function</strong>. The type definition of this function is [TS](a:unknown):a is number =&gt; boolean. It takes as argument value from type <em>unknown </em>and returns an answer if the given value is a type of <em>number</em>, in other words if an element is a member of the <em>number </em>set. Take a look at a <em>“is number”</em> part, it is very explicit information that <em>“a”</em> is a member of a number type/set.</p><blockquote><strong>Note</strong> Unknown type in TypeScript is really a union of all types available in the codebase. So all types are subtypes of the unknown type.</blockquote><h4>Composed types are also sets</h4><p>Not only primary types are sets. But every new type in the code also forms a set. Custom type can be a composition of other types, in other words it is created by some operations on sets. There are two common compositions of types — Product and Sum. Product creates new type by <em>“and”</em> operation, sum by <em>“or”</em> operation.</p><h4>Product type</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*Wn9qUaHxClyiajqOQufJUw.png" /><figcaption>Product type — all sub-types values required</figcaption></figure><p>Products type is a type created from other types in such a way that in order to create instance of the product, all instances of sub-types are required. Product or Cartesian product is terms of the set theory is the result of joining two or more sets into one by putting them into tuple. Product of sets A, B and C is a 3-tuple — (A,B,C).</p><p>The simplest example of the product type is a Pair (2‑tuple). Pair is just two values (a:A, b:B), one from type A, one from type B (B can be equal A). To create such a pair, both values are required. Also the amount of possible values is a multiplication of sizes of these two sub-types — A and B. So <em>size(Pair&lt;A,B&gt;) equals size(A) * size(B).</em> Size of a set, number of set elements has more proper name — <a href="https://en.wikipedia.org/wiki/Cardinality">cardinality</a>.</p><pre>[TS]<br>// tuple<br>type Triangle = [number, number, number] // Product Int*Int*Int<br>// record — labeled tuple<br>type User = { name: string, age: number } // Product String*Int</pre><p>Surprisingly almost the same syntax for products exists in Elm.</p><pre>[Elm]<br>--tuple<br>type alias Triangle = (Int, Int, Int) --Product Int*Int*Int<br>--record — labeled tuple<br>type alias User = { name : String, age : Int } --Product String*Int</pre><p>In order to create member of the Triangle set, there needs to be provided an input in the form of 3 values from Int set. Amount of possibilities is equal Int*Int*Int.</p><blockquote><strong>Note </strong>Every product type can be considered as <a href="https://www.britannica.com/science/isomorphism-mathematics">isomorphic</a> to the tuple type. Any record/map is just a tuple with additional label, and we can create such — (name, lastname) -&gt; {name:name, lastname:lastname} and we can define reverse operation — {name:name, lastname:lastname} -&gt; (name, lastname).</blockquote><h4>Sum type</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*vWJi3U7rx8e5bLmVoQyoWA.png" /><figcaption>Sum type — only one value from sub-type available</figcaption></figure><p>Sum type is a type created from other types in such a way that in order to create an instance of the sum, only one instance from sub-types is required.</p><p>The simplest example of the sum type is Boolean type. If something is Boolean, it can be or <em>True</em>, or <em>False</em>, never both. Tipical understanding of this construct is just a set with listed possible elements, so this goes into our set definition where we define what is inside the set — <em>BoolSet = {True, False}</em>. But how then we can name this construct as a sum type, if there is only one type with two possible values?</p><p>It is very interesting question. Sum type holds here true only if we consider <em>True </em>and <em>False </em>as single value sets — <a href="https://en.wikipedia.org/wiki/Singleton_(mathematics)">singletons</a> with one element inside, and this is fully correct reasoning.</p><pre>[Elm]<br>type Boolean = True | False</pre><p>Also the amount of possible values is a sum of cardinality in all sub-sets. As for Boolean <em>True</em> and <em>False </em>represent sets with one element each, then the Boolean type contains exactly two values.</p><p>The most important feature of the sum type is that value can belong only to one type. It is not possible to sum two types with any shared elements. Sum types force tag on every sub-type. In order to create a type which has representation of type String or type Int, we need to create tagged versions of those types.</p><pre>[Elm]<br>--type definition<br>type StrOrInt = Str String | In Int<br>--usage<br>x = Str 12 <br>—-x has a type StrOrInt and is represented as tagged String type</pre><h4>Sum type implementation details</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/731/1*EAjTVyXk54TwV7KgR5F5VA.png" /></figure><p>Consider above diagram. There are two explanation of Elm definition of the sum type. First is based on types/sets where the sum is a union of disjoint sets, where even element <strong>C</strong> is also considered as a set with one element. The second shows definitions in terms of value constructors. In other words on the right side of the declaration we have functions which provide us the value of type <strong>Sum</strong>. Even <strong>C</strong> is presented here as function without arguments, this kind of function has a name — <strong>const</strong>. And because it is <strong>const</strong>, the value here is evaluated eagerly, for other constructors, they remain as functions (are lazy) and need an argument to create the value of type <strong>Sum</strong>.</p><blockquote><strong>Note </strong>Sum type has many names, it is also disjoint union, discriminated union, tagged union or variant</blockquote><blockquote><strong>Note </strong>Sum type in Category Theory is named — [Coproduct](<a href="https://en.wikipedia.org/wiki/Coproduct">https://en.wikipedia.org/wiki/Coproduct</a>).</blockquote><blockquote><strong>Note</strong> Union type with possible intersection is possible in TypeScript — [union](<a href="https://www.typescriptlang.org/docs/handbook/advanced-types.html#union-types">https://www.typescriptlang.org/docs/handbook/advanced-types.html#union-types</a>) — it is not a sum type as we cannot differentiate from which union type value comes from — `string | number | string ≡(equal) string | number`</blockquote><h4>Composing sums and products</h4><p>Sums and products are in not any way different types then others. That is why further compositions are possible. We can create products including other products and sums, sums containing other products and sums.</p><pre>[Elm]<br>type ResultStatus = Pending | Ok | Error<br>--product created from sum type Boolean and sum type ResultStatus<br>type alias UserProduct = { active: Boolean, age: Int, status: ResultStatus }</pre><pre>--sum created from product types tagged by Regular and Visitor tags<br>type UserSum<br> = Regular String Int<br> | Visitor String Int</pre><p>In above code snippet, the last two variants — <strong>Regular </strong>and <strong>Visitor </strong>can be confusing. These variants represent truly product types, as there needs to be provided value from type String and from type Int in order to fulfill the value constructor. So it is isomorphic to tagged tuple — <em>Regular String Int ≈(isomorphic) Regular (String, Int)</em>. And as we know, tuple is a most basic representation of the product type</p><p>More detail about algebraic data types can be found in this very nice explanation — <a href="https://qr.ae/TWy0Is">What is an algebraic data type? by Tikhon Jelvis</a>.</p><blockquote><strong>Note </strong>Third common algebraic data type is Exponential type. As functions in most modern languages can be passed as values, values need to have types, and these types for functions are exactly exponential types. Having a function type `A -&gt; B`, type can be presented as B&lt;sup&gt;A&lt;/sup&gt;, so the type represents value of type B on given A.</blockquote><h3>Base definition — what is an algebraic structure</h3><p>Ok, now we know what is set, we know that we work with sets in programming and we call those sets — types. Types can be mixed and mingled with each other, these compositions are products or sums, or sums of products, or products of sums.</p><p>We have a set, however to have algebraic structure we need one thing more. And this things is a operation on the set. In other words <strong>algebraic structure</strong> is a set + operation/s working with this set. Simple as that.</p><p>For instance int set has operation of adding elements, then int set with adding operation — binary function <em>int + int -&gt; int</em>, creates an algebraic structure, and in this example it is <strong>Semigroup</strong>. Also there exists neutral element for this operation and it is 0 as adding anything to it will not change the value <em>a + 0 = a and 0 + a = a</em>, taking these two properties — neutral element and adding operation we created another algebraic structure — <strong>Monoid</strong>.</p><h3>What next in the series</h3><p>In next articles from the series, I will cover specific algebraic structures which are useful in programming. First on the table is <strong>Setoid</strong>.</p><p>If you are interested in notifications about next articles please follow me on <a href="https://medium.com/@macsikora">medium </a>and <a href="https://twitter.com/macsikora">twitter</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5aa36add8183" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The State of Immutability]]></title>
            <link>https://medium.com/dailyjs/the-state-of-immutability-169d2cd11310?source=rss-ae51491fd44a------2</link>
            <guid isPermaLink="false">https://medium.com/p/169d2cd11310</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[immutability]]></category>
            <dc:creator><![CDATA[Maciej Sikora]]></dc:creator>
            <pubDate>Sat, 30 Dec 2017 21:41:44 GMT</pubDate>
            <atom:updated>2019-01-31T14:25:15.864Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*4877k4Hq9dPdtmvg9hnGFA.jpeg" /></figure><p>Immutability is a hot subject in modern JavaScript. The reason why this topic is so popular now is of course the functional programming paradigm.</p><p>Immutable data is tightly connected with a functional approach where any mutation is considered as an unwanted side effect. Without further ado, let’s dive into details of mutability and immutability.</p><h4>About immutable data structures in JavaScript</h4><p>In JavaScript, and many different languages, an assign statement works in two ways. For primary types (string, number, bool) assignment is passing the value, for complex types (objects) it is passing the reference(memory pointer). For complex types, any change will impact all occurrences because they really are only pointers to the same place. In the effect only primary types are immutable and can be safely changed, everything beyond primary types is mutable by default.</p><p>That said, let’s think what is the point in being immutable at all. JavaScript doesn’t have this immutability out of the box, there are no immutable structures for composites, and even no future plans for introducing that into the language. Why should you care, if the language doesn’t care?</p><h4><strong>You should care, because the trust matters</strong></h4><p>Using mutable structures is a reason of the trust deficit. Mutation can be done in every code part with the access to the reference.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*DgkLOiPBH95QmZiHDx47Tw.png" /></figure><p>JavaScript is very flexible, it means that any object can be transformed on the fly into something really different.</p><p>In one line it can be an object representing a dog, and in the next line the dog can be mutated into a chicken. Such situation enhances fears about state shape and code predictability.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZrJKJqBsksWd-8uKM9OvgA.png" /></figure><h3>Few words about mutation</h3><p>The opportunity of mutation provides no guaranty that something will stay unchanged. The worst scenario takes place when some structure is used in separate parts of the application, then any mutation in one component can create a bug in the other one. Such bug is really hard to track, because the source of the problem lies out of the scope of the failure. This is an example of a bad side effect.</p><h4><strong>Mutation is a cause of side effects</strong></h4><p>Side effect is anything which has impact on the outside of the current scope. If many parts of the code are dealing with the same reference then any change will impact all the parts. Side effects are bad, of course those unwanted ones, because code starts to be tightly coupled, code fragments instead of following single responsibility rule, are doing uncontrolled things outside their scope, they have impact on wider application context . Touching outside is always risky and has unpredictable consequences. When a bug will be found the questions will be risen — Where it was changed? What exactly was changed? Who also have access to the reference? But no history of change is available and questions can’t be easily answered.</p><h4>Mutation provides only current state</h4><p>When one reference is being many times changed, there is no history of these changes. No access to the previous state. Changing the object attributes is really rewriting the memory, old values are lost. The problem related to lack of the knowledge about changes is growing with number of places having access to the same mutable structure. It stays unknown how the structure is changing in the time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*brDhDYoDkpUEcWJcMyeP1w.png" /><figcaption>Transformation car object into bike object— no parking spot monitoring!</figcaption></figure><h4>Mutation is a cause of unpredictable state</h4><p>If mutation procedure contains many steps, many attributes are being changed then it is fairy possible that procedure can brake in the middle. In such case, the state needs to have rollback to previous valid version, or if not the state will be left in unknown shape. An unknown and unpredictable state can turn into a crash in a place where this structure is consumed.</p><h4>On the other hand mutation reuse the memory and is fast</h4><p>Yes that is true, mutation is reusing the memory. Mutation is beneficial for performance and memory usage. But we are in 21-century, memory is cheap and in micro scale of the front-end development it does not matter if some object will be copied or not. No risk that our immutable copies will impact the performance. Garbage collector will clean not used references for us, so no worries about memory leaks or unnecessary memory occupying.</p><p>…To be clear I am referring to the front-end side problems, it is understandable that there are many other kind of software, where the memory matters the most.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*KASeYPfcVcz0pgkiY-oxjg.jpeg" /><figcaption>We have plenty of memory</figcaption></figure><h4>Place Oriented Programming — PLOP</h4><p>The term presented by <a href="https://twitter.com/richhickey?lang=en">Rich Hickey</a> exactly capture the sense of using mutability. If guarantee about value not exists, then our object is only a pointer to the place in the memory, nothing more. Object was created in a shape A, but during the code execution it was transformed into a shape B, C, D and so on. Variables are representing memory not values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZrJKJqBsksWd-8uKM9OvgA.png" /></figure><h3>Immutability is about values</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F-6BsiVyC1kM%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D-6BsiVyC1kM&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F-6BsiVyC1kM%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/e2c7d9d462729b8f1b0ab9a417d6483f/href">https://medium.com/media/e2c7d9d462729b8f1b0ab9a417d6483f/href</a></iframe><p>Immutability means literally that nothing can be mutated, I can go further — mutation just doesn’t exist. Variable is representing single unchangeable value. No transformation of value because <em>valueA !== valueB</em>.<strong> Value is a fact and facts are unchangeable.</strong> If something was declared with specific value then rest of the code can fully trust that this exact value is there. This guarantee enables to say, that no side effects and no unpredictable state can be observed, most important is rebuilding the trust, and even if some parts of the code needs slightly different structure, they will not touch the original one, but work on own versions. Using values provides guarantee and a solid contract. Using memory pointers provides no guarantee and no contract.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/786/1*dDKknPgTRj7QFrQczwJxYw.png" /><figcaption>Immutable structure vs Mutable structure</figcaption></figure><h4>Value Oriented Programming — VOP</h4><p>Contrary to PLOP, VOP is about values only. Code is operating on values not on pointers in the memory. Anything representing different value should be separated structure. The value remains unchanged from its creation until its destruction. <strong>Every pure functional language is value oriented.</strong></p><h4>Any difference should be reflected in the new value</h4><p>Change doesn’t mean mutation, change means — generate new version of the state which reflects the change. But is it applicable to all cases? This is were some developers, also me, have problems with immutability. The problem starts when exists something big, like a big collection of data, and only small change needs to be done. In such case creating new structure feels wrong, it feels that the memory is used in very non effective way. Why I need to create the whole new structure of the data, if really only single element needs to be added or one field needs to be changed?</p><p>And answer for this question is — because the changed structure is representing the different value. These two collections, the previous and the changed one, are not the same. <strong>The fact can not be changed, despite from the size of the value, value is unchangeable fact.</strong></p><p>So if you start thinking in terms of values, then such doubt should not bother you. If doubt doesn’t go away then Immutable.js comes into rescue, few words about that in the next chapter.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZrJKJqBsksWd-8uKM9OvgA.png" /></figure><h3>Value Oriented Programming in JavaScript</h3><p>VOP can be implemented in JavaScript. As said before JavaScript has no immutable structures, but immutability can be achieved by principles and rules.</p><h4>Freeze your objects</h4><p>Object.freeze method give opportunity to block the object from further mutation.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3a02724dc94b1a2a9107ba5a3938caec/href">https://medium.com/media/3a02724dc94b1a2a9107ba5a3938caec/href</a></iframe><p>In above freeze example I’ve tried to mutate frog attributes, but in the result object stays unchanged. Very important is the fact that Object.freeze blocks mutation only in the object fields, in other words it is shallow freeze. Shallow means that any complex structure inside the object can be still mutated.</p><h4>Create new instance instead of doing changes</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/42aecefbcc74457d7db3911952421f24/href">https://medium.com/media/42aecefbcc74457d7db3911952421f24/href</a></iframe><p>The <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator">spread operator</a> can be used for creating new values from arrays and objects. It is very handy tool, code looks also very clear, it is visible what was changed and what was reused.</p><p>Spread operator is doing shallow copy, it means that root object reference is changed but all fields(object) or rows(arrays) are re-used. It also means that this approach is using memory in efficient way.</p><h4>Use immutable data structures</h4><p>JavaScript has no immutable structures out of box but there are third party implementation of such. The most popular are <a href="https://facebook.github.io/immutable-js/">Immutable.js</a> and <a href="http://swannodette.github.io/mori/">mori</a>. Both are base on trie data structure which is kind of search tree structure. Such structures allows for very efficient way of creating new instances without copying.</p><p>From my personal point of view using trie data structures can be handy for really complex structures. For anything else I would prefer spread operator. And until you will see performance issues, I would not really consider any third party solutions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZrJKJqBsksWd-8uKM9OvgA.png" /></figure><h3>Is immutability bound to the functional programming</h3><p>No is not. VOP can be used in other programming paradigms. Nowadays experts and evangelist of Object Oriented Programming also are talking about immutable and stateless objects. Here VOP gives the same benefits as in functional programming. Object without state or object with immutable state gives guarantee and trust for all parties consuming it. Immutable objects are amplifying single responsibility rule because of the need of passing all dependencies into the constructor. Immutability blocks any state change during object live cycle. In other words you are sure that object stays in unchangeable state from beginning to the end.</p><p>Forget about setters, and create immutable objects in your OOP. Below some great talk about the subject, it is related to Java language, by <a href="http://www.yegor256.com/">Yegor Bugayenko</a>.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fp7m7_iiqaHI%3Fstart%3D3038%26feature%3Doembed%26start%3D3038&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Dp7m7_iiqaHI&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fp7m7_iiqaHI%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/ed27d2a11acfeb2565991615e1b62cb7/href">https://medium.com/media/ed27d2a11acfeb2565991615e1b62cb7/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZrJKJqBsksWd-8uKM9OvgA.png" /></figure><h3>Are you ready for immutability?</h3><p>All things considered — immutability can be achieved by rules and principles. JavaScript doesn’t have immutability builded in, spread operator and external libs can easily help in implementing it though. If immutability is about rules, then everything is in the developer hands. If you see the value of value, then from this moment, the mutation should be gone in your application.</p><p>However the problem is in bad habits, bad habits mostly from object oriented programming. Bad practices are in our minds, under our skin. Bad practices like setters in the object, methods mutating the object state, object as state, huge polymorphic objects and so on, these things should be considered as wrong and never used again.</p><p>Change your way of thinking, see the value of value. Choosing immutability is a big step towards predictable, more efficient and less buggy programs.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=169d2cd11310" width="1" height="1" alt=""><hr><p><a href="https://medium.com/dailyjs/the-state-of-immutability-169d2cd11310">The State of Immutability</a> was originally published in <a href="https://medium.com/dailyjs">DailyJS</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to test private functions of CommonJs module]]></title>
            <link>https://medium.com/@macsikora/how-to-test-private-functions-of-es6-module-fb8c1345b25f?source=rss-ae51491fd44a------2</link>
            <guid isPermaLink="false">https://medium.com/p/fb8c1345b25f</guid>
            <category><![CDATA[test-driven-development]]></category>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[es6]]></category>
            <category><![CDATA[tdd]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Maciej Sikora]]></dc:creator>
            <pubDate>Tue, 24 Oct 2017 08:46:41 GMT</pubDate>
            <atom:updated>2019-09-26T06:39:00.151Z</atom:updated>
            <content:encoded><![CDATA[<p>CommonJs modules give great feature, local scope of variables and functions. This feature helps to encapsulate private resources and block access to them from outside. How to, in this circumstances test such functions hidden inside a module, do we really need to export them all in order to manage unit tests, even though it will break the private scope? Or maybe let’s test only public api of the module?</p><p>I will start from the second idea — test only public api. In my opinion it is wrong for many reasons, first of all in tdd (test driven development) tests are first, or should be written in the same time. If private methods are not tested, indeed it means that those functions weren’t created in tdd way. In the result it is harder to write single responsibility functions inside the module due to lack of a way to check them as an single units.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/704/1*Ibg1QBq7vZsVwpyTf-z2RA.png" /><figcaption>Creating functions without testing</figcaption></figure><p>Second possible option — give everything you got there. Export all private resources to have access to them in tests.</p><p>Answer for that is simple — No, don’t do that. Don’t export private functions outside the module. Don’t, because the module will loose very crucial attribute — public api which should be smart and contain only functions prepared to be public and planned for the outside use.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tkimBK_Wozxx526NvWTO7w.png" /><figcaption>Export everything vs export smart</figcaption></figure><p>How then eat the cake and have the cake? With the help comes <strong>rewire </strong>(<a href="https://github.com/jhnns/rewire">https://github.com/jhnns/rewire</a>). It is a library created to solve such problems. It gives a possibility to read module and extract private resources in due to use them while testing.</p><p>How to use it then. Let’s take example module.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ce42d9fccc782a226917f7624dde9a25/href">https://medium.com/media/ce42d9fccc782a226917f7624dde9a25/href</a></iframe><p>Example user.js module has inside four private functions and one public. In order to have efficient and useful module let’s export only single public function, others are left as local scope functions.</p><p>Great, now it is module with encapsulated functions, and clearly extracted public api. How test it then?</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3688d8898fcd932c73daee4f00cf9a39/href">https://medium.com/media/3688d8898fcd932c73daee4f00cf9a39/href</a></iframe><p>This is full test file, with fully covered functions from private and public scope of the user module. Most important in this code snippet are lines from 4 to 12.</p><pre>// standard using of exported functions<br>const { createUser } = require(&#39;./user&#39;) <br>// using rewire to get into private <br>const userRewire = rewire(&#39;./user&#39;)<br>const hasProp = userRewire.__get__(&#39;hasProp&#39;)<br>const hasProps = userRewire.__get__(&#39;hasProps&#39;)<br>const isString = userRewire.__get__(&#39;isString&#39;)<br>const arePropsStrings = userRewire.__get__(&#39;arePropsStrings&#39;)</pre><p>In those lines the single public function is taken directly from module (createUser), but other functions are here thanks to <strong>rewire </strong>library. It gives direct access to private resources by <strong>__get__</strong> function.</p><p>All things considered, it looks like you can have a cake and eat it too, and it is clearly possible by using <strong>rewire</strong>. Rewire allows to test private scope without any code refactoring and most importantly without choosing the lesser of two evils.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fb8c1345b25f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Effective backup of your JavaScript projects with export-cli]]></title>
            <link>https://medium.com/@macsikora/effective-backup-of-your-javascript-projects-with-export-cli-6100de7e046?source=rss-ae51491fd44a------2</link>
            <guid isPermaLink="false">https://medium.com/p/6100de7e046</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Maciej Sikora]]></dc:creator>
            <pubDate>Fri, 20 Oct 2017 10:02:39 GMT</pubDate>
            <atom:updated>2017-10-20T10:21:36.760Z</atom:updated>
            <content:encoded><![CDATA[<p>Sometime a situation can happen, when you need to backup a local environment with all projects there. Projects can have in that time many small and bigger changes, configurations files related to local environment and other staff which should not be pushed into git, or you just don’t want to do that.</p><p>Someday it can happen that you need to move to a different machine and you want to take your local files with you.</p><p>One day you want to archive local projects and store this archive in some safe place.</p><p>Sooner or later you can need a reliable backup solution for backup automation of your project files.</p><p>Are you familiar with these needs? Did you ever have a need to export projects and put them into some safe place? If so, them let’s continue, if no … maybe this is not for you.</p><p><strong>Export-cli</strong> (<a href="https://www.npmjs.com/package/export-cli">https://www.npmjs.com/package/export-cli</a>) is the tool which give’s easy cli interface for doing a backup of single or many projects. It has few important attributes:</p><ul><li>it is searching for every JavaScript project inside chosen directory</li><li>it exports every found project into a flat structure</li><li>it exludes node_modules and .git directories</li><li>it can archive projects into a zip file</li></ul><p>Let’s imagine that you have more then ten projects inside some example “projects” directory. They are in random, nested structure. All have node_modules and .git directories inside. If you want to backup them, you will probably use some archive command or try to copy them… and in result, you will export 80% not needed files, use 80% additional disk space, and export time will be simply huge.</p><p>Solution for that is mentioned <strong>export-cli</strong>, by one simple command — <strong>export srcDirectory,</strong> all projects inside the directory will be exported, archived if you want, into flat structure and without not wanted files.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6100de7e046" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Universal JavaScript what the hack is that?]]></title>
            <link>https://medium.com/@macsikora/universal-javascript-what-the-hack-is-it-aefc522e6a4e?source=rss-ae51491fd44a------2</link>
            <guid isPermaLink="false">https://medium.com/p/aefc522e6a4e</guid>
            <category><![CDATA[universal-app]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[universal-javascript]]></category>
            <dc:creator><![CDATA[Maciej Sikora]]></dc:creator>
            <pubDate>Mon, 14 Aug 2017 20:20:38 GMT</pubDate>
            <atom:updated>2018-02-04T15:53:30.021Z</atom:updated>
            <content:encoded><![CDATA[<p>The answer is simple, Universal JavaScript is a JavaScript code which can be executed both on the server and the client side. But before I will go into the details I will show you what is the purpose of using it.</p><h4>Why do You need it?</h4><p>The current usage of JavaScript frameworks like React or Angular gives developers possibility to manage the view level fully in a browser. It means a front-end application gets data from a server and uses this data to fill html views. This front-end view rendering creates a problem with maintaining of the view rendering by the server side. The problem is caused by a different technology stack on both sides and the same rendering need. If something was done on the browser run-time why it should be implemented and have duplicated functionality on the server side? The workaround solution here is to resign from the server side rendering, but … This resign has many side effects, as the application without the server side rendering are:</p><ul><li>less accessible</li><li>less or just not SEO-friendly</li><li>not accessible by text readers</li><li>slower in performing first launch</li><li>problematic to execute for slower devices</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/615/1*WdupJe7pCGjW5FBjB3yu9Q.png" /><figcaption>Execution differences for app with and without rendering on the server side</figcaption></figure><p>Do You know why Facebook is so fast when you enter its url in to the browser? It’s because Facebook page is pre-rendered on the server side and doesn’t do any special additional work when page is loaded. It is worth to mention that Facebook is hosted by super fast and spread all over the world servers and this is not without a meaning here :)</p><p>If you want to create a fast loading and widely accessible application, then Universal JavaScript can help in that.</p><p>In the next chapters, when I mention the server side, it means that I refer to a Node.js application, when I mention the client side, it stands for any web browser.</p><h4>Let’s go into details</h4><p>The Universal JavaScript should be executed in unchanged state on both, the server and the client. Let’s try to write some universal code and find important attributes of such JavaScript program.</p><p>When I start thinking of what type of code can be executed on both run-times then first thought is the pure functional programming. The pure functional programming has no state, has no global dependencies, it is about input and output. Let’s try such example of a function:</p><pre>function pureAction(input) { <br>  return &#39;This is input: &#39; + input; <br>}</pre><p>And, yes, this kind of function which doesn’t use any dependencies, which doesn’t touch outside environment, which only depends on its arguments is pure and universal.</p><p>We can then set the statement that — <strong>Pure functions are universal.</strong></p><p>What else can be easily universal? Let’s imagine that you are using some data object structures, and those data structures can be reused. Example of such a structure is:</p><pre>const UserFactory = {   <br>   build(id, name): () =&gt; { <br>     return {<br>       id: id,<br>       name: name<br>     }<br>   }<br>};</pre><pre>const userA = UserFactory.build(1, &quot;John&quot;);<br>const userB = UserFactory.build(2, &quot;Mark&quot;);</pre><p>After this example, it is easy to think about sharing between the server and the client all models of our data. The same goes with every utility, for example validation or conversion utils can be reused and universal.</p><h4>Don’t be afraid, touch the environment</h4><p>In case of previous trivial examples being universal isn’t a problem, what if you need to create something more related to the application flow, something which uses DOM or window events, in other words has side effects. In such case, there are no such objects in the node.js, such code will throw an exception. Let’s see an example with a button and a tipical event listener.</p><pre>document.getElementById(&#39;button&#39;).addEventListener((e) =&gt; {<br>  console.log(&#39;button clicked&#39;);<br>});</pre><p>This code will just fail on the server side, no way that it will be executed there, because server has no document object.</p><p>To solve such issue you have (as always) many possibilities. One of them is to create a mock of the object, something like a dummy global document object with the same api, it would look in the following way:</p><pre>// dummy dom element<br>function DomElement(id) {<br>  this.id = id; <br>  this.addEventListener = function() {}<br>};</pre><pre>// dummy document<br>global.document = { <br>  getElementById: function(id) { <br>    return new DomElement(id);<br>  }<br>};</pre><p>Thanks to that part, the code can be used without any changes, but part of the program with mock objects is not universal. It is only the tool which enables a different part of the code to become universal. When you follow presented solutions with dummy objects only for one side, the app will have more non-universal code, and it is for sure unwanted.</p><p>However, instead of creating parts of code which are only applicable on the server side, you can also create objects which can be executed on both sides. Let’s try to implement the same example in a such way.</p><pre>// object creates gate to original document api<br>const documentModel = () =&gt; {<br>  <br>  const element = { <br>   // dummy object for the server side<br>   addEventListener: () =&gt; {}<br>  };</pre><pre>  if (typeof document === &#39;undefined&#39;) { <br>    // dummy object for the server side<br>    let document = { <br>      getElementById: () =&gt; element<br>    }<br>  }  </pre><pre>  return { <br>    findById: (id) =&gt; document.getElementById(id)<br>  }<br>}();</pre><pre>// usage<br>documentModel.findById(&#39;button&#39;).addEventListener(&#39;click&#39;, () =&gt; {<br>  console.log(&#39;button click&#39;);<br>});</pre><p>The code represented above, can be fully executed on both sides. In case of the client usage, it will call real document object methods, on the server side the same code will call dummy objects. No errors, no exceptions.</p><p>So, what is the difference? In the second example, dummy objects are also here. Yes, but the difference is in the fact, that those mocks are also in the code which is executed on the client side. In thr first example dummy objects can be only related to the server side, and need to be excluded from the client side build, in the second example is is a fully universal code without any special excluded parts.</p><p><strong>The clue of being universal is to encapsulate the environment specifics into own universal components.</strong></p><p>To sum up previous chapters I can say that in order to be universal, you need to create as many pure and unrelated to environment components as it is possible. This part of code can cover utils, models and everything which doesn’t touch the environment directly, no side effects part. The rest of the code, which is somehow related to the global instances, needs to be encapsulated in universal modules, which will be responsible for solving difference problem.</p><h3>Create Universal Applications</h3><p>So you know what can be Universal JavaScript, now it’s high time to do something with it. Universal JavaScript gives an opportunity to create Universal Applications.</p><p><strong>Universal Application is an application which uses Universal JavaScript to execute itself on both, the client and the server side.</strong></p><p>But, wait. A part of components can be universal but how is it possible to fully execute the same application (with the same source code) in two different environments? That is to say, that there exist user interface in the browser, as well as events, form filling, scrolling etc. In the server none of these things exist. However, the server deals with not one but many connections and needs to provide content for every connected client.</p><p>Those two environments have different run-times, different purposes of work, but they have one important thing in common, both use JavaScript.</p><p>First I need to put here the execution target for every of environments.</p><ul><li><strong>The Server </strong>provides the rendered html content and data</li><li><strong>The Browser </strong>provides rich user interface</li></ul><p>The very important thing is that a fully Universal Application should execute only that part which is also executed in the browser. It means that the server side execution should not contain any additional data layers like db connections, disk read or any typical server side staff. The server side code should behave in a similar way to the browser one, with the difference that the result of it is a html text instead of DOM. The conclusion is the fact that the server side part is just a front-end application which needs to connect with some API end points in the same way as the browser does.</p><p><strong>Universal Application is a front-end application with a possibility to pre-render on the server side.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/546/1*lCLDIT4kileYdb8p3mvm_A.png" /><figcaption>Execution and connection between API Server and Non-Universal and Universal App</figcaption></figure><p>The diagram shows the difference, let’s focus on the connection between an API Server and a Universal Application. For an API Server (typical back-end app created in any back-end technology) it is no difference from where the requests are coming from, it can be a browser or a server with Node.js.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/671/1*SRLkok0UKY-3daTuz-h41w.png" /><figcaption>Universal Application flow</figcaption></figure><p>I will now try to analyze the flow presented in the diagram.</p><ol><li>The browser is sending request for the url of the application</li><li>The server side starts to execute universal code</li><li>The universal part is connecting with the API server</li><li>The universal part is executing and rendering the view</li><li>The server side sends the rendered view with the data</li><li>The browser starts execution</li><li>The browser binds events</li><li>The browser is responding for user actions and connects to the API server in future requests</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/561/1*V4RDUvEoooSTYvkTrCID-Q.png" /><figcaption>The separation between Universal Application and API Server</figcaption></figure><p>To know more I encourage you to get acquainted with an example of a Universal Application created from the scratch without any framework.</p><p><a href="https://github.com/maciejsikora/universal-sample-app">maciejsikora/universal-sample-app</a></p><h3>Can it be easier? Yes, choose React!</h3><p>With the usage of current top frameworks like React, Angular or Vue it could be done in an easier way. React.js with its virtual DOM looks like the good tool for the purpose, it has even method <strong>renderToString</strong> which executes the application in such way that the component tree is converted into html string. The server side in a React base application needs to execute components rendering on the given state of the app which is connected with provided app path. To simplify managing the state in one place good idea is to use Redux. In below code example you can see server side rendering with usage of React, Redux and ReactRouter.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e5e39645680233906d123dcdfcf920aa/href">https://medium.com/media/e5e39645680233906d123dcdfcf920aa/href</a></iframe><p>In every request it’s needed to set the state in the store and render the components with usage of <strong>renderToString</strong>. Usage of StaticRouter component deserves for the attention — it is a part of ReactRouter library and this particular component enables to route the application for a given url. The last thing is to append the part of html rendered by React into a full html template and …wallah, user has ready to use pre-rendered app. Below you can see how looks like the browser part responsible for initialization.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ad8a808a09f35a97bcfde3bf4e5f570f/href">https://medium.com/media/ad8a808a09f35a97bcfde3bf4e5f570f/href</a></iframe><p>Not much code here. The first thing is to take the data provided by the server, next based on this data, Redux store is created. After the window is loaded, React renders the application using given initial store. The BrowserRouter component, which will automatically connect to the browser url and route to this point of the application state. So the server side shares with the browser the pre-rendered html and also the data presented in the <strong>window.__STATE__ </strong>object. Those two things enable React to fully connect with prepared data and rendered content.</p><p>I need to mention also component life-cycle, when a component is called by <strong>renderToString</strong> (in the server side) then it is not executing its life-cycle methods, so these functions are only applicable for the browser run-time. Rendering in the server only set the props by the Redux store and executes the render function of the component.</p><p>Want to know more? Check full example of Universal Application based on React:</p><p><a href="https://github.com/maciejsikora/universal-js-app-oauth-example">maciejsikora/universal-js-app-oauth-example</a></p><h3>What is the conclusion?</h3><p>I hope You know more and understand what the Univesal Javascript concept is about. Of course using it in the project has its price, it is always something additional, its needs to be double-checked, front-end developer needs to have it in the back of his mind. But for the cost of some additional work your app can be more accessible, faster, less dependent from the client device computation power. The effort helps any kind of readers and robots to properly analyze page content. Good luck in creating your first Universal Application!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aefc522e6a4e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[When the server side rendering started to be called Universal JavaScript]]></title>
            <link>https://medium.com/@macsikora/when-server-side-rendering-started-to-be-called-universal-javascript-de38803bf09f?source=rss-ae51491fd44a------2</link>
            <guid isPermaLink="false">https://medium.com/p/de38803bf09f</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[universal-javascript]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Maciej Sikora]]></dc:creator>
            <pubDate>Sat, 24 Jun 2017 21:22:43 GMT</pubDate>
            <atom:updated>2017-08-14T20:30:39.286Z</atom:updated>
            <content:encoded><![CDATA[<p>Universal Applications and Universal JavaScript started to be the “must have” for most of new rich front-end applications. Every important js framework ( React, Vue, Angular and others ) is trying to follow this new universal concept. But what is hidden inside the “universal” word?</p><p>Let’s start from simple logic, what can mean universal. First clue is that universal is something which can be re-used in many different projects, second that universal code should be independent from the environment, third idea is that universal JavaScript is an implementation of the concept -”write once, run anywhere”.</p><p>Is it right? Simple answer is just <strong>no</strong>. When you try to find any implementation or example of the Universal JavaScript concept, you will find only one topic related to pre-rendering in the server side… really nothing more.</p><p>Every Universal JavaScript project is deeply connected with the server side rendering, every one is focused on the possibility of pre-rendering application before it will start it’s execution on the client side. No other solutions, no other use, no other purpose of the universal code, just rendering.</p><p>If we take those information&#39;s into consideration it is easy to create some definitions.</p><p><strong>Universal JavaScript</strong> is a JavaScript code which can be executed in the client and the server side.</p><p><strong>Universal Application </strong>is an <strong>front-end </strong>application which is able to pre-render itself in the server side.</p><p>Ok, lets think for a while, if those definitions can be considered as right, then <strong>universal</strong> word looks strange here. Why we call something universal if it is just an implementation of one concept? Why we call something universal if it works only in two environments (the browser and Node.js).</p><p>When <a href="https://medium.com/u/7f9567e0d71c">Michael Jackson</a> proposed the <strong>Universal JavaScript</strong> name he wrote:</p><blockquote>Because <strong>good names are important</strong></blockquote><p>And yes I fully agree, but naming something universal which is used only for one purpose is just simply bad.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=de38803bf09f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>