<?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 Adam Brodziak on Medium]]></title>
        <description><![CDATA[Stories by Adam Brodziak on Medium]]></description>
        <link>https://medium.com/@adambrodziak?source=rss-5fe74050beb4------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*HdV-_9ULgFzVS0x4IJzyOA.jpeg</url>
            <title>Stories by Adam Brodziak on Medium</title>
            <link>https://medium.com/@adambrodziak?source=rss-5fe74050beb4------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 16 Nov 2026 10:14:36 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@adambrodziak/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[Dockerfile good practices for Node and NPM]]></title>
            <link>https://adambrodziak.medium.com/dockerfile-good-practices-for-node-and-npm-24a1d246c208?source=rss-5fe74050beb4------2</link>
            <guid isPermaLink="false">https://medium.com/p/24a1d246c208</guid>
            <category><![CDATA[npm]]></category>
            <category><![CDATA[docker-image]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[dockerfiles]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Adam Brodziak]]></dc:creator>
            <pubDate>Mon, 22 Mar 2021 08:25:45 GMT</pubDate>
            <atom:updated>2023-07-05T09:45:07.799Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Originally published at </em><a href="https://adambrodziak.pl/dockerfile-good-practices-for-node-and-npm"><em>https://adambrodziak.pl/dockerfile-good-practices-for-node-and-npm</em></a></p><p>The goal is to produce minimal image to keep the size low and reduce attack surface. Also we want to make the docker build process fast by removing unnecessary steps and using practices outlined below to leverage internal build cache.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*A8Nu3Jh6uGN7-BxS" /><figcaption>Layers of containers, that will make sense later.</figcaption></figure><p>Besides pure Docker I’ll present docker-compose tool, which is a tool to start many Docker containers that are required to run the application, i.e. frontend server, backend server, database.</p><h3>NodeJS and NPM examples</h3><p>Here I’ll be using NodeJS and NPM in examples, but most of those patterns can be applied to other runtimes as well.</p><h3>Laverage non-root user</h3><p>Default NodeJS images have node user, but it has to be enabled. The best option is to use it before any NPM dependencies or code are added.</p><pre># Copy files as a non-root user. The `node` user is built in the Node image.<br>WORKDIR /usr/src/app<br>RUN chown node:node ./<br>USER node</pre><p>Node process no longer runs with root privileges. By such simple change you&#39;ve increased security of the image a lot.</p><h3>Set NODE_ENV=production by default</h3><p>This is the most important one, as it affects NPM described below. In short NODE_ENV=production switch middlewares and dependencies to efficient code path and NPM installs only packages in dependencies. Packages in devDependencies and peerDependencies are ignored.</p><pre># Defaults to production, docker-compose overrides this to development on build and run.<br>ARG NODE_ENV=production<br>ENV NODE_ENV $NODE_ENV</pre><p>For local development we can override it’s value. Here’s an example docker-compose.yml file that builds and runs our Docker image in development mode:</p><pre>version: &#39;3&#39;<br>services:<br>  myapp:<br>    build:<br>      args:<br>        - NODE_ENV=development<br>      context: ./<br>    environment:<br>      - NODE_ENV=development</pre><p>To start the application just type docker-compose up and it will build an image on first start and then run the container(s) defined in YAML.</p><h3>Install NPM dependencies before adding code</h3><p>The reason is simple: dependencies change way less often than code, so we can leverage build cache. The biggest difference can be seen if you have any C++ modules that require compiling during install.</p><pre># Install dependencies first, as they change less often than code.<br>COPY package.json package-lock.json* ./<br>RUN npm ci &amp;&amp; npm cache clean --force<br>COPY ./src ./src</pre><p>The npm ci will install only packages from lock file for reproducible builds on CI server. I recommend using it by default. Have a read how it is different than npm install in the official docs.</p><p>The magic happens in &amp;&amp; which will execute two commands in one run producing one Docker image layer. This layer will be then cached, so subsequent run of the same command (with the same package*.json) will use the cache.</p><p>Since build uses Docker image cache the NPM cache is not needed, so we can clean downloaded packages cache. This way resulting image is smaller.</p><pre>$ docker build .<br>Sending build context to Docker daemon<br>Step 2/5 : COPY package.json package-lock.json* ./<br> ---&gt; Using cache<br> ---&gt; 6fb28308975d<br>Step 3/5 : RUN npm ci &amp;&amp; npm cache clean --force<br> ---&gt; Using cache<br> ---&gt; 0a6bd71d2c2d</pre><p>While we’re at this I recommend adding node_modules line to .dockerignore file in order to avoid adding local version of modules to the resulting image. While npm ci would remove any existing node_modules directory, there&#39;s no point to increase the size of image layer.</p><h3>Use node (not NPM) to start the server</h3><p>Last, but not least, is to avoid npm start as command to start application in container. Using NPM seems reasonable, because this is how you used to run the application locally. However with Docker and Kubernetes it&#39;s a bit more complicated.</p><p>The main problem with npm start is that NPM does not pass SIGTERM OS signal to Node process. Because of that Node is not able to do cleanup before exit. Docker and Kubernetes send SIGTERM to container process when they want to stop it.</p><p>This can lead to many issues from hanging database connections to open file descriptors. Notice that it’s not only your application code that might react to SIGTERM, but it might be the framework or some libraries.</p><p>The good practice is to simply call Node directly.</p><pre># Execute NodeJS (not NPM script) to handle SIGTERM and SIGINT signals.<br>CMD [&quot;node&quot;, &quot;./src/index.js&quot;]</pre><p>Notice that we’ve used square brackets to denote exec form of CMD command. If the string would have been used instead the container would start sh -c as main process and OS signals would have been lost again.</p><p>Having node as main PID 1 process is also not ideal, but at least SIGTERM and other signals could be handled in application code. You can test it yourself using the simplest NodeJS server code:</p><pre>const http = require(&#39;http&#39;);<br>const port = process.env.PORT || 8000;</pre><pre>http.createServer(function (req, res) {<br>    res.end(req.url);<br>}).listen(port);<br>console.log(`Server running at http://localhost:${port}/ ...`);</pre><pre>// Signal handling<br>process.on(&#39;SIGTERM&#39;, function() {<br>    console.log(&#39;SIGTERM: shutting down...&#39;);<br>});</pre><p>Now try to execute docker container stop against newly created one. The change CMD line to use NPM and see that SIGTERM was not caught.</p><p>Such even handler is the place where you want to cleanup all the resources created or opened by the application.</p><h3>Builder pattern</h3><p>Let’s say your use case is to turn SASS/SCSS into plain CSS using Ruby Compass compiler. It has different stack than the rest of Node app, so we will need separate Docker image. Here’s how to use such separate temporary image for compilation step.</p><p>Modern Docker versions allow to use <a href="https://docs.docker.com/develop/develop-images/multistage-build/">multi-stage builds</a>. Essentially it allows to have many FROM clauses in Dockerfile, but only the last one FROM will be used as a base for our image. It means that all the layers of other stages will be discarded, so the resulting image is going to be small.</p><pre>FROM rubygem/compass AS builder<br>COPY ./src/public /dist<br>WORKDIR /dist<br>RUN compass compile<br># Output: css/app.css</pre><p>Docker build engine will save resulting files in a temporary image that can be used in COPY expression for our final image:</p><pre># Copy compiled CSS styles from builder image.<br>COPY --from=builder /dist/css ./dist/css</pre><p>Such expression will copy files from /dist folder, in our case css.app.css only. All the other image layers will be discarded for the</p><p>The same pattern can be used for any other compilation or transpilation tool, like Babel, Webpack, TypeScript, etc. In fact it makes sense whenever we have to install any development tool that should not be part of production build. The same applies for installing git, C++ compiler, development version of packages (packages with -dev suffix).</p><p>For some JavaScript projects you might notice that npm install or npm ci is done twice: in the builder and final image. It could mean that you mix frontend (i.e. React.js) and backend (i.e. Express.js) libraries in single package.json file. My advice is to separate those frontend and backend dependencies, but getting through exact strategies deserve another blog post. Let me know if you&#39;re interested.</p><h3>Putting it all together</h3><p>Here’s an example Dockerfile for easy copy&amp;paste for your project. It covers all the good practices we’ve discussed earlier.</p><pre># Separate builder stage to compile SASS, so we can copy just the resulting CSS files.<br>FROM rubygem/compass AS builder<br>COPY ./src/public /dist<br>WORKDIR /dist<br>RUN compass compile<br># Output: css/app.css</pre><pre># Use NodeJS server for the app.<br>FROM node:12</pre><pre># Copy files as a non-root user. The `node` user is built in the Node image.<br>WORKDIR /usr/src/app<br>RUN chown node:node ./<br>USER node</pre><pre># Defaults to production, docker-compose overrides this to development on build and run.<br>ARG NODE_ENV=production<br>ENV NODE_ENV $NODE_ENV</pre><pre># Install dependencies first, as they change less often than code.<br>COPY package.json package-lock.json* ./<br>RUN npm ci &amp;&amp; npm cache clean --force<br>COPY ./src ./src</pre><pre># Copy compiled CSS styles from builder image.<br>COPY --from=builder /dist/css ./dist/css</pre><pre># Execute NodeJS (not NPM script) to handle SIGTERM and SIGINT signals.<br>CMD [&quot;node&quot;, &quot;./src/index.js&quot;]</pre><p>The Dockerfile above contains all the essential good practices for JavaScript project (either NodeJS server or some frontend). In case you&#39;re interested in more advanced optimizations check out the repository documenting more good defaults for Node on Docker: <a href="https://github.com/BretFisher/node-docker-good-defaults">github.com/BretFisher/node-docker-good-defa..</a></p><p>Spread the knowledge about good practices in Dockerfile creation.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=24a1d246c208" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kubernetes: basic resources and concepts]]></title>
            <link>https://adambrodziak.medium.com/kubernetes-basic-resources-and-concepts-a34da9f5f371?source=rss-5fe74050beb4------2</link>
            <guid isPermaLink="false">https://medium.com/p/a34da9f5f371</guid>
            <category><![CDATA[kubernetes-cluster]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[aws-eks]]></category>
            <dc:creator><![CDATA[Adam Brodziak]]></dc:creator>
            <pubDate>Wed, 18 Nov 2020 16:25:35 GMT</pubDate>
            <atom:updated>2020-11-18T16:25:35.164Z</atom:updated>
            <content:encoded><![CDATA[<p>Below are my notes while learning Kubernetes, but I thought those might be useful to other people that are just starting or just need a quick dictionary for K8s concepts and resources. Enjoy!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kuhCYjudrYOyz7NP3l0eMQ.jpeg" /><figcaption>Using K8s feels like being air traffic controller, sometimes.</figcaption></figure><h3>Master Server Components</h3><p>Those master components make so called control plane.</p><ul><li>etcd — config store accessible to all cluster nodes</li><li>kube-apiserver — config workloads and org unit; REST + kubectl client</li><li>kube-controller-manager manages controllers, state saved to etcd</li><li>kube-scheduler — assigns workloads to specific nodes</li><li>cloud-controller-manager — bridge to specific cloud provider</li></ul><h3>Node Server Components</h3><ul><li>Node is a server that preforms work.</li><li>Container Runtime is typically Docker, but can be rkt or runc too.</li><li>kubelet is a main contact point for each node with the cluster group. Work is received as manifest.</li><li>kube-proxy lets manage sub-netting and makes services available to other components. Can do primitive load-balancing.</li></ul><h3>Kubernetes Objects and Workloads</h3><p>Instead of managing containers directly, users define and interact with instances composed of various primitives provided by the Kubernetes object model.</p><h3>Pods</h3><p>A pod is the most basic unit. One or more tightly coupled containers are encapsulated into pod. Those share a lifecycle, should be on the same node. They share environment, volumes, IP space.</p><p>Each pod gets its own IP address, so it can interact with other pods in the cluster.</p><p>Horizontal scaling is discouraged, there are other options.</p><p>Users should not manage pods themselves. Rather work with higher level objects that use pods or pod templates as base component.</p><h3>Replication Controllers and Replication Sets</h3><p>You’ll manage groups of identical, replicated pods. There are created from pod templates.</p><p>Replication controller manages number of pods. If pod or underlying host fails, the controller will start new pod to compensate. Same if number of pods in config changes. Can do rolling updates.</p><p>Replication sets are beginning to replace replication controllers, but can’t do rolling updates.</p><p>Neither of both you should manage directly.</p><h3>Deployments</h3><p>Deployments are a high level object and the most common workloads to create and manage. Use replication sets and add lifecycle management. Modification is a config change. K8s deals with the rest.</p><p>A Deployment chooses which Pods to include by use of the selector field. In this example the selector mode is matchLabels, which instructs the Deployment t look for Pods defined with the app: web label.</p><pre>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: apache-deployment<br>  labels:<br>    app: web<br>spec:<br>  replicas: 5<br>  selector:<br>    matchLabels:<br>    app: web<br>template:<br>  metadata:<br>    labels:<br>      app: web<br>  spec:<br>    containers:<br>    - name: apache-container<br>      image: httpd:2.4.35</pre><h3>Stateful Sets</h3><p>Stateful sets are used in case of special requirements related to deployment ordering, persistent data, or stable networking. Meant for databases.</p><p>Provide a stable networking identifier by creating a unique, number-based name for each pod that will persist even if the pod needs to be moved to another node. Operations are performed according to the numbered ID.</p><h3>Daemon Sets</h3><p>Run a copy of a pod on each node in the cluster (or subnet). Used for pods doing maintenance or services for the nodes. Examples: collection and forwarding logs, aggregating metrics.</p><h3>Jobs and Cron Jobs</h3><p>Jobs are for task-based workflow, where it exists when done.</p><p>Cron jobs are jobs that are invoked by scheduler.</p><h3>Other Kubernetes Components</h3><h3>Services</h3><p>Service acts as a basic internal load balancer and ambassador of pods. Groups logical collection of pods that perform the same function to present them as a single entity.</p><p>Service IP address remains stable, so it can be used by internal consumers. Any time you need to provide access to one or more pods to another app you should config a service. For example a set of web servers, or database pods.</p><p>It can be made available outside of the cluster using NodePort config, that opens a static port on each node’s external net interface. Alternatively LoadBalancer can be used.</p><h3>Volumes and Persistent Volumes</h3><p>Kubernetes Volumes differ from Docker volumes because they exists inside the Pod rather than inside the container.</p><p>Volumes allow data to be shared by all containers within a pod and remain available until the pod is terminated. So pods can easily share files. Container failures do not affect files.</p><p>Persistent volumes are not tied to pod life cycle. Allow admins to config storage that users can request and claim for the pods they are running. If the pod is kept after pod is done depends on volume reclamation policy. Persistent data can be used to guard against node-based failures and to allocate more storage than available locally.</p><h3>Namespaces</h3><p>Namespaces are virtual clusters. Every cluster has at least 3 namespaces: default, kube-system, kube-public.</p><h3>Labels and Annotations</h3><p>Label is a semantic tag assigned ot object. These can be selected for when targeting different instances for management or routing.</p><p>Annotations are more free-form, less structured data. Not used for selection.</p><h3>Secrets</h3><p>Secrets hold sensitive information such as passwords, TLS certificates, OAuth tokens, and ssh keys.</p><h3>ConfigMap</h3><p>ConfigMaps are mechanisms used to inject containers with configuration data while keeping containers agnostic of Kubernetes.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a34da9f5f371" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[OOP best practices that are anti-patterns in (functional) JavaScript]]></title>
            <link>https://levelup.gitconnected.com/oop-best-practices-that-are-anti-patterns-in-functional-javascript-61ee1af35452?source=rss-5fe74050beb4------2</link>
            <guid isPermaLink="false">https://medium.com/p/61ee1af35452</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[antipattern]]></category>
            <category><![CDATA[object-oriented]]></category>
            <category><![CDATA[design-patterns]]></category>
            <dc:creator><![CDATA[Adam Brodziak]]></dc:creator>
            <pubDate>Mon, 04 May 2020 08:38:15 GMT</pubDate>
            <atom:updated>2020-06-02T11:58:57.712Z</atom:updated>
            <content:encoded><![CDATA[<p>What is considered a good practice in Object-Oriented Programming (OOP) and Design Patterns, but is considered an anti-pattern in JavaScript (the functional programming (FP) flavor of JS at least)?</p><p>Here are the main points:</p><ul><li>The good: factory pattern</li><li>The bad: constructor</li><li>The ugly: class Foo extends Bar</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RWwbii6ig3GQOfhW0nwAMA.jpeg" /><figcaption>Looking at this lake helps me clear my mind.</figcaption></figure><p>For classic OOP languages (Java, C#, PHP) things look pretty much the same. C# is probably better of, but I have very little experience with it, so I will be using Java as a reference point. The (anti)patterns are the same in all languages, though.</p><p>Disclaimer: The above does not mean that Object-Oriented Programming or languages that follow OOP paradigms and use classes are bad. It’s more that JavaScript uses a different paradigm and provides greater expressiveness, so it’s good to make use of it.</p><h3>The good: factory pattern</h3><p>In fact, you have 2 factory patterns in OOP:</p><ul><li><a href="https://en.wikipedia.org/wiki/Factory_method_pattern">Factory method pattern</a></li><li><a href="https://en.wikipedia.org/wiki/Abstract_factory_pattern">Abstract factory pattern</a></li></ul><p>Both make sense, as they are solving the problem with a particular language. The big one here is: you want to code the creation of objects, without knowning their class yet. Look at the provided code examples in Java, how complicated it is and how much boilerplate is necessary.</p><p>In JavaScript none of those limitations exist: there are no object classes (more on class keyword later), no need to check interfaces and such. Any function can return an object, so you can do:</p><pre>const createUser = ({ name }) =&gt; ({<br>  name,<br>  setName(name) {<br>    this.name = name;<br>    return this;<br>  }<br>});<br> <br>const joe = createUser({ name: &#39;Joe Doe&#39; });</pre><p>The code above is a factory function that simply returns an object. No classes, static methods, polymorphism are necessary. Have a read on <a href="https://medium.com/javascript-scene/javascript-factory-functions-with-es6-4d224591a8b1">factory functions with ES2015 syntax</a> to learn how to handle default parameters, type inference and others.</p><p>In other words: the wide use of factory patterns in OOP languages make sense, but in JavaScript it is just a function returning object literal. Too simple to be called a design pattern ;)</p><h3>The bad: constructor</h3><p>So JavaScript has got a constructor function that <em>should</em> be invoked using new operator:</p><pre>function User(name) {<br>  this.name = name;<br>}<br> <br>const joe = new User(&#39;Joe Doe&#39;);<br>console.log(joe instanceof User);</pre><p>Just like Java, well almost. If you forget to use new the constructor will be called a regular function, in such case this will be bound to the global object (i.e. window in the browser). Vars like names are added to the global scope and the whole construction falls apart (pun intended). It is a major gotcha and cause of many bugs.</p><p>You can explore more <a href="https://css-tricks.com/understanding-javascript-constructors/">traits of constructor functions</a>, but I agree with <a href="https://github.com/getify">Kyle Simpson</a> there are better solutions than constructor, prototypes hackery and classes, like <a href="https://stackoverflow.com/questions/29788181/kyle-simpsons-oloo-pattern-vs-prototype-design-pattern">OLOO pattern</a>. If you really need objects with methods, of course ;)</p><p>Long story short: avoid using new keyword and constructors. As a consequence instanceof might not be necessary as well. Use more powerful factory functions described above. Just as Douglas Crockford said:</p><h3>Adam Brodziak on Twitter</h3><p>If a feature is sometimes dangerous, and there is a better option, then always use the better option.&quot; ~ Douglas Crockford</p><blockquote><em>“If a feature is sometimes dangerous, and there is a better option, then always use the better option.”</em></blockquote><p>The use of the new operator in OOP languages is discouraged too, to avoid coupling with a specific class and its implementation. Factory patterns are preferred instead, which enable Dependency Injection, but it&#39;s a story for another post.</p><h3>The ugly: class Foo extends Bar</h3><p>ES2015 introduced class and extends keywords to JavaScript. No, it does not mean JavaScript has got classes - it&#39;s still using the prototype chain. Basically it&#39;s a syntax sugar over constructor pattern with some magic done behind the curtains.</p><p>In fact, the worst offender here is the extends keyword, because it <em>encourages</em> extending classes for code sharing. That is the wrong motivation. The extends should be used to express “<em>is a”</em> relationship in design, but such a case rarely happens in reality. This is the highest form of coupling in OOP.</p><p>Extensive use of extends leads to deeply nested class inheritance hierarchies. It does not seem bad at first, but believe me, I&#39;ve worked in a system with such hierarchy 7 levels deep and we constantly keep fixing code in this tree. Fix on one level caused regressions few levels upper or lower, leading to the downward spiral. That is simply the <a href="https://medium.com/javascript-scene/the-two-pillars-of-javascript-ee6f3281e7f3">Seventh Circle of Hell</a> kind of issue.</p><p>Other often used name for this anti-pattern is “The Gorilla / Banana problem” coined by Joe Armstrong:</p><h3>Adam Brodziak on Twitter</h3><p>&#39;The problem with object-oriented languages is they&#39;ve got all this implicit environment that they carry around with them. You wanted a banana but what you got was a gorilla holding the banana and the entire jungle.&#39; ~ Joe Armstrong&quot; - @_ericelliott https://t.co/xepD08GleG</p><p>On the other hand class can be useful. For a long time using classes was the recommendation for <a href="https://medium.com/@dan_abramov/how-to-use-classes-and-sleep-at-night-9af8de78ccb4">creating React components</a>. Notice that you always had extends React.Component - there was no deep inheritance hierarchy in the code, right? Right?! I don&#39;t think <a href="https://medium.com/javascript-scene/how-to-fix-the-es6-class-keyword-2d42bb3f4caf">class keyword in JS is broken</a>, but it comes with its own problems, just like the new keyword does. As an analogy suggests - better to avoid them both.</p><h3>Objects and classes are not the software</h3><p>OOP aficionados often tend to focus on classes, objects, UML, diagrams — all of that is great, but not the core. What is the most important thing is: what the software does. With that in mind objects without methods are pretty useless, even though Java (used to) force you to <a href="http://steve-yegge.blogspot.com/2006/03/execution-in-kingdom-of-nouns.html">creating classes to hold your functions</a> — an awful idea.</p><p>For your next JavaScript feature or project start to think about how you can solve the problem the simplest way. Try to avoid all the OOP ceremony and focus on function(s) of the software.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=61ee1af35452" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/oop-best-practices-that-are-anti-patterns-in-functional-javascript-61ee1af35452">OOP best practices that are anti-patterns in (functional) JavaScript</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Communication patterns for people of various knowledge and experience]]></title>
            <link>https://adambrodziak.medium.com/communication-patterns-for-people-of-various-knowledge-and-experience-95dde531ada9?source=rss-5fe74050beb4------2</link>
            <guid isPermaLink="false">https://medium.com/p/95dde531ada9</guid>
            <category><![CDATA[self-improvement]]></category>
            <category><![CDATA[learning]]></category>
            <category><![CDATA[skills-development]]></category>
            <category><![CDATA[career-development]]></category>
            <category><![CDATA[communication-skills]]></category>
            <dc:creator><![CDATA[Adam Brodziak]]></dc:creator>
            <pubDate>Tue, 17 Sep 2019 20:10:13 GMT</pubDate>
            <atom:updated>2019-09-17T20:10:13.361Z</atom:updated>
            <content:encoded><![CDATA[<h4>Dreyfus model of skill acquisition provides hints for building effective communication - no matter if you want to delegate a task, ask for help, or just convey an idea.</h4><p>Imagine that you’re an experienced software developer calling ISP technical support, because router is broken. How would you feel when they ask you if it’s plugged-in, if lights are blinking, or if you tried turning it off and on again? Let me explain why they do ask stupid questions and why you feel annoyed.</p><p>Imagine an opposite situation when you have no mechanical skills, nor experience. Your car broke down in the middle of nowhere. The car mechanic tells you that oil pump needs to be replaced. You hear it’s an easy job, so you can do it yourself. How useful is that for you? What if you would get step-by-step guide instead?</p><h3>You will learn</h3><ul><li>How skills are acquired and developed.</li><li>How to judge your (and your colleagues) skill level.</li><li>Am I Competent, yet?</li><li>The importance of growing beyond Beginner state.</li><li>How to communicate your needs.</li><li>How to delegate tasks effectively.</li></ul><h3>What is Dreyfus model of skill acquisition?</h3><figure><img alt="Brain as a PCB" src="https://cdn-images-1.medium.com/max/800/1*oOv3mwkV33pbGqADUYbTVw.jpeg" /><figcaption>Brain as a sophisticated computer was all the rage in the ‘80</figcaption></figure><p>Dreyfus brothers worked on Artificial Intelligence in the ’80 of XX century. Back then General AI seemed like a close target [sic!], but they’ve stumbled upon a problem. General AI was supposed to learn skills like humans do, but we (humans!) had very little clue how we learn. They’ve researched the subject and came up with a model.</p><p>Dreyfus model of skill acquisition defined 5 stages of learning:</p><ol><li><strong>Novice</strong></li><li><strong>Advanced Beginner</strong></li><li><strong>Competent</strong></li><li><strong>Proficient</strong></li><li><strong>Expert</strong></li></ol><p>I’ll dwell into properties of those stages in a second, but first let me tell you why it matters. The model has been used for US Army pilot training (original case of research), <a href="https://journals.sagepub.com/doi/abs/10.1177/0270467604265061">applied in nursing industry</a> and is a foundation of <a href="https://pragprog.com/book/ahptl/pragmatic-thinking-and-learning">Pragmatic Thinking and Learning</a> book by Andy Hunt. In other words: it has been battle tested in practice and proven to be useful.</p><h3>5 Stages of skill acquisition</h3><p>Bear in mind that those stages are for specific skill. You could be an Expert in one and Novice in another skill.</p><h4>1. Novice</h4><ul><li>Have little or no previous experience</li><li>Don’t want to learn, just accomplish a goal</li><li>Don’t know how to respond to mistakes</li><li>Are vulnerable to confusion</li><li>Rules-based, context free</li></ul><h4>2. Advanced Beginner</h4><ul><li>Starts trying tasks on their own</li><li>Have difficulty troubleshooting</li><li>Want information fast</li><li>Can place some advice in context required</li><li>Begin to formulate some principles, but without holistic understanding</li></ul><h4>3. Competent</h4><ul><li>Develop conceptual models</li><li>Troubleshoot problems on their own</li><li>Seek out expert user advice</li><li>Conscious, long-term plans and goals</li><li>Beyond stimulus-response</li></ul><h4>4. Proficient</h4><ul><li>Want to understand the larger conceptual framework</li><li>Are frustrated by oversimplified information</li><li>Will self-correct previous poor task performance</li><li>Learn from experience of others</li><li>Asks difficult questions. First one to be let go.</li></ul><h4>5. Expert</h4><ul><li>Are primary sources of knowledge and information</li><li>Continually look for better methods</li><li>Work primarily from intuition, not reason</li><li>Forcing to follow set rules degrades performance</li></ul><p>For the first 3 stages progress is natural and comes with time (usually). Reaching Proficient and Expert levels requires not only focused training (i.e. deliberate practice), but also broadening the horizons.</p><figure><img alt="Dreyfus model stages explained as expending brain meme." src="https://cdn-images-1.medium.com/max/598/1*sRZLGlzHvI8nXh0p2Sa6yw.png" /><figcaption><a href="https://twitter.com/AdamBrodziak/status/1100676793407885312">https://twitter.com/AdamBrodziak/status/1100676793407885312</a></figcaption></figure><p>There is a risk that Beginner will think he’s an Expert (fallacy named Dunning-Kruger Effect), which forms rather peculiar stage: Expert Beginner. The terms has been coined by Erik Dietrich, who devoted an ebook and <a href="https://daedtech.com/how-developers-stop-learning-rise-of-the-expert-beginner/">series of blog posts</a> to describe this topic. Fortunately Beginner is the last stage that is prone to such fallacy, as Competent and above have enough awareness.</p><h3>How to use Dreyfus stages to help my development?</h3><p>Honest self-evaluation is the 1st step to expertise. Do not jump straight to becoming Expert though, but rather focus on reaching Competent level for main skills. An Expert is someone who devoted the career, often a lifetime, to become one. Keep in mind that changing the way you think, probably even on a hardware level, takes years and tremendous effort.</p><h4>Am I Competent, yet?</h4><p>So why becoming Competent is so important? It’s the fist stage where you’re able to work independently: make plans and reach goals, deal with problems as they arise, know when to seek out for expert advice and apply it effectively. All that is possible due to conceptual models that are being developed in the mind, seeing more than just a task that is in front of you.</p><p>In order to evaluate yourself look for the traits describing Competent (or any other stage for that matter). The goals is to do honest evaluation and being aware of cognitive biases: Dunning-Kruger effect mentioned before and Impostor Syndrome that works the other way around (higher stages undervalue themselves, think they are on the lower stage).</p><p>Essentially you usually want to go through Novice and Advanced Beginner phase as fast as possible for skills that are important. That means taking on more and more complex tasks, reading on the good practices and standards, collaborating with others and asking for help (a lot!). The latter ones are probably the most important aspects.</p><h4>Use mentor help to become Competent</h4><p>So you’re Novice or Beginner but want to up your game. The single best advice I can give you is: find a mentor. Why it is so important? Let’s look at some of the traits:</p><ul><li>mentor will help avoid mistakes or deal with them (for Novice)</li><li>mentor will clear out the confusion (for Novice)</li><li>mentor can help troubleshoot problems (for Beginner)</li><li>mentor can explain the context and its importance (for Beginner)</li><li>you’ll learn how to get help from mentor (from Competent)</li><li>mentor can show you next subjects to improve or explore</li></ul><p>Becoming Competent makes yourself a valuable part of a team and organization. Plus it’s the stage past the biggest issues, including confusing yourself with an Expert. This is the stage you realise how little you know about the subject. Reaching Proficient requires deliberate practice and broadening horizons. To become Expert it is a career choice, or even a calling.</p><h4>Evaluate others</h4><p>Similar evaluation can be applied to people you interact with. Being aware of their stage of a particular skill is a great help to communicate effectively. It allows to tailor the message according to person needs, for example:</p><ul><li>step-by-step instructions for Novice or Beginner</li><li>a problem with its context for Proficient or Expert</li></ul><p>While evaluating others keep in mind that Dreyfus stages are for specific skill. Someone can be Expert in their field (i.e. brain surgery), but Novice in others (i.e. baking cookies).</p><h3>Communicate appropriately</h3><p>Here are the guidelines how to communicate with person that reached particular stage. Those are useful when you ask someone to do something, assign a task, delegate or ask for collaboration. You can use the same framework to ask for help, i.e. if you’re Novice ask for step-by-step directions.</p><h4>Novice needs context-free steps</h4><ul><li>Provide step-by-step instructions how to complete the task.</li><li>Be specific what needs to be done. Use precise values, i.e. bake cookies for 20 minutes in 200°C temperature.</li><li>Tell what is the expected outcome, as Novice is not able to judge if they done it right.</li><li>Make steps small, so it’s fast to see success. It boosts motivation.</li><li>Technical support rule books are good examples of context-free rules that can guide even complete Novice somewhere.</li></ul><h4>Advanced Beginner wants task with guidelines</h4><ul><li>Beginner is happy to tackle task, but might require some guidance where to start or which direction to take.</li><li>Provide all necessary information (if possible), so no need to consult other sources (motivation!).</li><li>Explain how to deal with problems (i.e. escalation path), as Beginner can’t troubleshoot yet.</li><li>If possible provide context, so Beginner can try to formulate mental models.</li></ul><h4>Competent wants goal to reach</h4><ul><li>Competent wants to receive goals, rather than specific tasks.</li><li>Is able to navigate at the crossroads (make informed decisions) and troubleshoot problems.</li><li>Providing context (not only task at hand) is necessary, so Competent can make decisions on their own.</li><li>Knows when to ask expert advice or escalate the issue.</li></ul><h4>Proficient will ask for problem and context</h4><ul><li>Proficient will be annoyed with oversimplified information.</li><li>Needs to be provided with context, because every problem is different.</li><li>Will ask a lot of (annoying) questions to understand the conceptual framework.</li><li>Is able to apply maxims. If you get a maxim (i.e. use TDD) in response, ask for specifics.</li></ul><h4>Expert will ask what is the pain</h4><ul><li>No need to provide much information upfront, just explain the pain.</li><li>Expert know the difference between irrelevant details and the very important details (but maybe not on the conscious level).</li><li>Expert works from intuition, so might not be able to explain their reasoning.</li><li>An example is Dr. House, who by looking at the patient can judge what tests need to be done.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*os7Ds0Ivco6toaV11u9caQ.jpeg" /><figcaption>Source: <a href="https://pixabay.com/illustrations/starry-sky-meditation-legged-2515489/">https://pixabay.com/illustrations/starry-sky-meditation-legged-2515489/</a></figcaption></figure><h3>Partying words</h3><p>Keep in mind Dreyfus model of skill acquisition is just a simplification of reality. In addition it’s one of many models of learning. What’s important to remember that it should not be confused with seniority or hierarchy in the organization, as it applies to specific skill, not to person.</p><p>There are <strong>3 basic things</strong> I’d like to ask you:</p><ul><li>Be aware of your stage, especially when asking for help or delegating.</li><li>Bear in mind people’s stage, or consider they might be a Novice.</li><li>Let others know about Dreyfus model and how to use it.</li></ul><p>My personal goal for this post was to organize my thoughts and become more proficient at using Dreyfus model in life. It was very useful for me over the years to guide my career, but more importantly, to communicate with others and help them develop. I hope you will make good use of it too. Please share, clap or send it to people you care about.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=95dde531ada9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Wasted 10 years with Bash]]></title>
            <link>https://adambrodziak.medium.com/wasted-10-years-with-bash-a7f6cb480419?source=rss-5fe74050beb4------2</link>
            <guid isPermaLink="false">https://medium.com/p/a7f6cb480419</guid>
            <category><![CDATA[shell]]></category>
            <category><![CDATA[bash]]></category>
            <category><![CDATA[shell-script]]></category>
            <category><![CDATA[terminal]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Adam Brodziak]]></dc:creator>
            <pubDate>Wed, 30 Jan 2019 16:18:59 GMT</pubDate>
            <atom:updated>2019-01-30T16:21:46.579Z</atom:updated>
            <content:encoded><![CDATA[<h4>Try Fish or ZSH — modern Bash alternatives that make shell more productive and cool. Do not waste time with Bash as I did.</h4><p>When you’re thinking of shell on any Linux system you probably think <a href="https://www.gnu.org/software/bash/">Bash</a> (Bourne Again Shell). On Windows too actually, as Git Bash is quite popular (despite it has got an ugly terminal emulator) and WSL (Windows Subsystem for Linux) uses Bash as well (by default). At least those have quite modern 4.x versions of Bash, while MacOS X ships an outdated 3.2 version and there are tutorials how to <a href="https://itnext.io/upgrading-bash-on-macos-7138bd1066ba">upgrade Bash on Mac to 5.0</a> which was released days ago.</p><p>The Bash 5.0 upgrade on Mac looks quite complicated and can yield unexpected errors, so that begs the question: why not use better shell instead?</p><h3>My history with Bash</h3><p>My story with Linux started in 2007 and for 10 years straight I’ve been using stock Bash, as it came with Ubuntu. It’s not <em>that bad</em>, as Ubuntu at least ships autocomplete configuration by default, so you can use Tab to complete command or its parameters. Just try to type apt ins&lt;Tab&gt; to see it in action. I&#39;ve learned that very quickly and blessed Ubuntu for <a href="https://www.tecmint.com/install-and-enable-bash-auto-completion-in-centos-rhel/">making it work for me</a>.</p><p>Over the years I’ve learned <a href="https://zwischenzugs.com/2018/01/06/ten-things-i-wish-id-known-about-bash/">some useful things</a>, like Ctrl+R to search history or Ctrl+K to clear line. I did not know any better (unconscious incompetence), because for me shell==Bash back then. Even after finding that there are other shells and relying on <a href="https://linux.die.net/man/1/checkbashisms">Bash quirks in scripts is bad practice</a> I haven’t looked for greener pastures. Somehow it did not even occur to me to alter Bash stupid defaults (case sensitive file completion — why?!), besides maybe increasing history buffer (huge productivity boost BTW).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Cnkyf62bqddhWlokAi28qg.jpeg" /><figcaption>This is how it feels to use Bash nowadays. Photo from <a href="https://www.flickr.com/photos/fhwrdh/5390966278">Flickr</a>.</figcaption></figure><p>BTW: There is <a href="https://github.com/mrzool/bash-sensible">sensible Bash config</a> that you should definitely check out!</p><h3>Fish — The user-friendly command line shell</h3><p>It was late 2017 when I stumbled upon <a href="https://fishshell.com/">Fish Shell</a>. The tipping point was aptly named <a href="https://jvns.ca/blog/2017/04/23/the-fish-shell-is-awesome/">The fish shell is awesome</a> post by Julia Evans. Then I’ve watched few <a href="https://www.youtube.com/watch?v=g_HoW4iek2Q">videos</a> and was totally hooked. Fish comes with all bells and whistles out of the box, setup for you. No need to configure anything, install plugins, etc.</p><p>As you can see Fish (on the right) has got <a href="https://www.youtube.com/watch?v=0NOAUogSSMo">the best tab-completion</a> compared to ZSH and Bash.</p><p>Of course Fish community created <a href="https://github.com/jorgebucaran/awesome-fish">plugins for more advanced features</a> — I can recommend the following:</p><ul><li><a href="https://github.com/rafaelrinaldi/pure">rafaelrinaldi/pure</a> — Pure-fish port of <a href="https://github.com/sindresorhus/pure">sindresorhus/pure</a> prompt</li><li><a href="https://github.com/franciscolourenco/done">franciscolourenco/done</a> — Automatically receive notifications when a long process finish</li><li><a href="https://github.com/jethrokuan/z">jethrokuan/z</a> — Pure-fish <a href="https://github.com/rupa/z">rupa/z</a>-like directory jumping</li></ul><p>Notice those plugins are <em>Pure-fish</em> implementations of 3rd party scripts. The reason is: Fish offers sane scripting (<a href="https://twitter.com/fishpkg/status/1087159872561414145">unlike other shells</a> some say), but it’s not POSIX compliant. This is probably the biggest drawback (or downside) of using Fish. Over the years I’ve accumulated one-liners, scripts and habits from Bash (i.e. using &amp;&amp; to join commands), but most were POSIX-compliant. Which led me to ZSH…</p><p>Note: <a href="https://github.com/fish-shell/fish-shell/releases/tag/3.0.0">Fish 3.0.0</a> released month ago have added &amp;&amp; support. I might give Fish another try. It is that important :)</p><h3>ZSH (Z shell) — designed for interactive use</h3><p>ZSH has been recommended to me by my colleagues at work as better Bash alternative, because it is POSIX-compliant. That means my Bash habits still work: &amp;&amp; to join commands, way of exporting ENV variables, storing command output in var using backticks, etc.</p><p>Since I’ve been using Fish before I’ve started to look for plugins that replicate features that Fish provides out of the box. To get some of the Fish coolness install the following:</p><ul><li><a href="https://github.com/zsh-users/zsh-autosuggestions">zsh-autosuggestions</a> — Fish-like fast/unobtrusive autosuggestions for zsh.</li><li><a href="https://github.com/zsh-users/zsh-syntax-highlighting">zsh-syntax-highlighting</a> — Fish shell-like syntax highlighting for Zsh.</li><li><a href="https://github.com/zsh-users/zsh-history-substring-search">zsh-history-substring-search</a> — This is a clean-room implementation of the Fish shell’s history search feature</li></ul><p>There’s plenty of <a href="https://github.com/unixorn/awesome-zsh-plugins">awesome ZSH plugins</a>, but I tend use only few, not to overload <a href="https://github.com/adambro/dotfiles/blob/master/home/.zshrc">my .zshrc</a> file. The reason: it is on me to make sure everything works well. I’m using <a href="http://antigen.sharats.me/">Antigen plugin manager</a> that is supposedly solving plugins installation issues (see motivation section), but problems still happen. To be honest I have never tried installing <a href="https://ohmyz.sh/">oh-my-zsh</a> directly, because it does not ship Fish-like plugins listed above and <a href="https://joshldavis.com/2014/07/26/oh-my-zsh-is-a-disease-antigen-is-the-vaccine/">configuring custom plugins in OMZ is awful</a>.</p><h3>Bash as a scripts runtime</h3><p>OK, so we’ve established that there are better interactive shells than Bash, but Bash is still useful for scripts. It’s because of it’s ubiquitousness obviously — it’s available on (almost) every Linux/Unix system those days. However Bash has it’s gotachas as scripting language, so beware. Here are few links to make your life easier with Bash scripts:</p><ul><li><a href="http://redsymbol.net/articles/unofficial-bash-strict-mode/">http://redsymbol.net/articles/unofficial-bash-strict-mode/</a></li><li><a href="https://zwischenzugs.com/2018/01/06/ten-things-i-wish-id-known-about-bash/">https://zwischenzugs.com/2018/01/06/ten-things-i-wish-id-known-about-bash/</a></li><li><a href="https://github.com/dylanaraps/pure-bash-bible">https://github.com/dylanaraps/pure-bash-bible</a></li></ul><h3>Partying words</h3><p>If you’re working with shell do yourself a favor and try something more modern than Bash. Do not waste a decade as I did. My suggestions are as follows:</p><ul><li>Try Fish as it’s awesome out of the box. Not only cooler, but much more productive. If you know something even better— let me know!</li><li>If you like to tinker or need POSIX shell give ZSH a go. No idea which plugin manager to recommend though ;)</li><li>Use <a href="https://github.com/mrzool/bash-sensible">Bash sensible config</a> if you really need to use Bash, i.e. on remote host you do not control.</li></ul><p>Let me know if I missed anything or there’s even better shell that I’m not aware of. Basically rising awareness of Bash alternatives is my point here, so I’m open to learn.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a7f6cb480419" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Singleton with async constructor in JavaScript]]></title>
            <link>https://adambrodziak.medium.com/singleton-with-async-constructor-in-javascript-32367f52540f?source=rss-5fe74050beb4------2</link>
            <guid isPermaLink="false">https://medium.com/p/32367f52540f</guid>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[software-design-patterns]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Adam Brodziak]]></dc:creator>
            <pubDate>Fri, 29 Jun 2018 09:37:18 GMT</pubDate>
            <atom:updated>2018-06-29T09:37:18.016Z</atom:updated>
            <content:encoded><![CDATA[<p>Singleton is really easy to write, but it’s not so simple, especially in multi-threading environments. Sure, JavaScript is single-threaded by design, but not all concurrency daemons are slayed.</p><p>Note: this is one of those posts leveraging <a href="https://meta.wikimedia.org/wiki/Cunningham%27s_Law">Cunningham’s Law</a>: the best way to get an answer is not to ask questions on the Internet, just post the wrong solution. To be honest I don’t know what’s the best way to handle Singleton with async constructor — I’m just trying to adjust best practices to JavaScript specific runtime.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nqystAGZ7ELqZBHJMwApCA.png" /><figcaption>There are different flavors of Singleton.</figcaption></figure><p>Starting with the basics here’s Singleton implementation with standard blocking (non-async) constructor:</p><pre>let instance;<br>const getInstance = () =&gt; {<br>    if (!instance) {<br>        instance = new Date();<br>    }<br>    return instance;<br>}</pre><p>Note: all code examples assume to be confined within CommonJS modules (Node runtime), where only relevant parts are exported. I’ve skipped exports, classes, constructors and all the unnecessary cruft for clarity.</p><p>The code above is all fine when object creation actually happens in the same event loop tick as the instance variable check. Problems start to happen when it’s not the case. For example instance in question is a network connection that needs to be opened first. Such operations in Node are done as async call not to block main thread.</p><h4>Async/Await</h4><p>For asynchronous instance creation we can use following code:</p><pre>const net = async () =&gt; await new Promise(resolve =&gt; setTimeout(resolve, 1000));</pre><pre>let instance;<br>const getInstance = async () =&gt; {<br>    if (!instance) {<br>        instance = await net();<br>    }<br>    return instance;<br>}</pre><p>Not much different than previous one — just an additional async/await pair. However, can you spot the problem already? At the “await net()” call there’s context switch, because promise is created, but it will be resolved (return value) only some time after it has been created. This is not happening all in one sequence on the main thread any more.</p><p>As a result we can have many calls of “net” instantiation potentially creating heavy objects in memory, where only one will be eventually used. Not only waste of CPU and RAM, but also using up the I/O resources. Amount of network sockets is limited! Not ideal, but eventually we’ll always have at least one usable instance to use.</p><h4>JavaScript is single-threaded, but beware of context switches</h4><p>The most reasonable solution is with simple async/await. It does not guarantee that constructor will be invoked only once, but at least once. Other requests will likely await Promise resolution — that’s the price to pay.</p><p>I’ve made an attempt to make sure only one call for constructor is invoked using Semapthore pattern, but there’s a risk of running into race condition when another request is made before await is done:</p><pre>let instance;<br>let semaphore = false;<br>const getInstance = async () =&gt; {<br>    if (!instance &amp;&amp; !semaphore) {<br>        semaphore = true; // mark awaited constructor<br>        instance = await net();<br>    }<br>    return instance;<br>}</pre><p>The code above will not work in all cases, because there’s a time window when semaphore===true but instance is not resolved yet. On other words: we risk that instance will be returned as undefined in some cases.</p><h4>Bonus: blocking constructor in Node.js runtime</h4><p>Bonus: in Node.js the heavy and blocking constructor can be invoked during server startup time. For that the code does not even have to be async, we can easily block the main thread loop. This way it can be initialized once and then instance can be exported via CommonJS module variable. That’s the simplest solution, but available only in Node.js runtime.</p><p>Node.js runtime is a bit more complicated than single-threaded JavaScript loop. I recommend watching the <a href="https://www.youtube.com/watch?v=8aGhZQkoFbQ">What the heck is the event loop anyway?</a> video by Philip Roberts.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=32367f52540f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Use JS object spread operator instead of Object.assign() pattern in Node 8]]></title>
            <link>https://adambrodziak.medium.com/use-js-object-spread-operator-instead-of-object-assign-pattern-in-node-8-125a4914f6dd?source=rss-5fe74050beb4------2</link>
            <guid isPermaLink="false">https://medium.com/p/125a4914f6dd</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[eslint]]></category>
            <category><![CDATA[node-for-begginners]]></category>
            <dc:creator><![CDATA[Adam Brodziak]]></dc:creator>
            <pubDate>Thu, 21 Dec 2017 20:56:43 GMT</pubDate>
            <atom:updated>2017-12-21T20:56:43.219Z</atom:updated>
            <content:encoded><![CDATA[<p>One of the best features of Node 8.6+ is the ability to use rest/spread operator for objects. It’s still an <a href="http://node.green/#ESNEXT-candidate--stage-3--object-rest-spread-properties">ESNEXT stage 3</a>, but it’s so useful already. Take a look at the snippet:</p><pre>const foo = { a:1, b:2, c: 3}<br>const bar = { d:4, b:9 }</pre><pre>const foobar1 = Object.assign({}, foo, bar)<br>const foobar2 = { ...foo, ...bar }</pre><pre>console.log(foobar1, foobar2)<br>console.log(JSON.stringify(foobar1) === JSON.stringify(foobar2))</pre><h4>Object.assign() issues</h4><p>The biggest problem with Object.assign() is that it modifies the first argument. If you omit the empty object literal {} it will modify the first parameter and return reference to it:</p><pre>const foo = { a:1, b:2, c: 3}<br>const bar = { d:4, b:9 }</pre><pre>const foobar3 = Object.assign(foo, bar)</pre><pre>console.log(foobar3, foo)<br>console.log(foobar3 === foo) // true</pre><p>Assign modified the first param and foobar3 is a reference to foo now.</p><p>I don’t know any solution, besides careful code review, to avoid this pitfall. Notice that using const foo did not prevented from modifying it. I haven’t found an ESLint rule that would prevent modification of first parameter in Object.assing() call.</p><h4>But the object spread syntax is …ugh</h4><p>Yeah, I’ve got the same feeling at the beginning, but quickly got used to it. For array rest/spread syntax is already part of ES2015 standard and becomes wildly used. That’s no a surprise, because in JavaScript there was no clean way to do head+tail list transformations prominent in Functional Programming.</p><p>As <a href="https://medium.com/u/1823d7a9f975">Corinne Kelly</a> <a href="https://medium.com/@corinnemariekelly/object-assign-vs-spread-operator-577c889dbadc">pointed out</a> even the MDN docs uses “spread syntax operator” to describe Object.assign() behavior. It’s that common in FP and math notations:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/307/1*E9Tm9FkC2qBFC9cVLAbh6g.png" /><figcaption>Object.assign() syntax from MSN docs.</figcaption></figure><p>Note that there’s an ESLint rule that allows enforcing using object spread syntax instead of Object.assign() for object cloning, which prevents unintentional modification:</p><p><a href="https://www.npmjs.com/package/eslint-plugin-prefer-object-spread">eslint-plugin-prefer-object-spread</a></p><h4>Object spread syntax benefits</h4><ul><li>Less cluttered code thanks to sparse syntax</li><li>Prevents accidental object modification</li><li>Can be enforced using <a href="https://www.npmjs.com/package/eslint-plugin-prefer-object-spread">ESlint rule</a></li><li>Douglas Crockford says so:</li></ul><h3>Adam Brodziak on Twitter</h3><p>If a feature is sometimes dangerous, and there is a better option, then always use the better option.&quot; ~ Douglas Crockford</p><p>If I’m mistaken and there are better options let me know in comments or on Twitter.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=125a4914f6dd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to involve a domain expert into modeling — visual and linguistic DDD techniques]]></title>
            <link>https://adambrodziak.medium.com/how-to-involve-a-domain-expert-into-modeling-visual-and-linguistic-ddd-techniques-2cf45f8941ad?source=rss-5fe74050beb4------2</link>
            <guid isPermaLink="false">https://medium.com/p/2cf45f8941ad</guid>
            <category><![CDATA[business-analytics]]></category>
            <category><![CDATA[domain-driven-design]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[domain-driven-development]]></category>
            <dc:creator><![CDATA[Adam Brodziak]]></dc:creator>
            <pubDate>Wed, 30 Nov 2016 11:12:05 GMT</pubDate>
            <atom:updated>2016-11-30T11:12:05.245Z</atom:updated>
            <content:encoded><![CDATA[<p><em>It is a review of JDD 2014 talk by Sławomir Sobótka originally published at </em><a href="https://www.future-processing.pl/blog/java-developers-day-2014/"><em>Future Processing technical blog</em></a><em> along with other talks reviews. The video recording (in Polish) is available on </em><a href="https://www.youtube.com/watch?v=z0y3IPJDyp0"><em>youtube</em></a><em>.</em></p><p>This talk was presented in Polish, its original title is „Jak wciągnąć eksperta domenowego w wir modelowania — wizualne i lingwistyczne techniki DDD”. It used linguistic techniques that are typical for Polish language. Nonetheless, I’ll try to get the gist out of it, because approach and way of thinking is applicable to any natural language.</p><p>The most important takeaway from this lecture for me was: naming is very powerful, because it affects our thinking. Also naming things is the most difficult thing in computer science, a <a href="http://martinfowler.com/bliki/TwoHardThings.html">famous quote by Phil Karlton</a>. In order to avoid running into rabbit hole with putting labels on objects we should avoid putting names on classes as long as we can. Sławek suggested to use <a href="http://en.wikipedia.org/wiki/Gibberish_%28language_game%29">gibberish game</a> for naming, or just put a „Blah” name first. From practical perspective it helps to avoid generic names like manager, resource and such.</p><p>Object Oriented Programming is about message passing, events and signals — not sticking together procedures and data structures. Hence Object Oriented Design should focus on mentioned behaviours and system events, which will operate on objects. After we’ve got actions and relevant objects it’s way easier to name classes. The proper order of Object Oriented Analysis is then as follows:</p><ul><li>Behaviour, action, operation (technically: method)</li><li>What does it do?</li><li>Behaviour rules (technically: method implementation)</li><li>How does it do it?</li><li>Data that is processed (technically: attributes)</li><li>What is the thing?</li><li>Name (technically: class name)</li><li>What it is?</li></ul><p>Above rules help to get a common ground with domain expert while designing domain model of the system. The goal is to have names in code that are understandable to business. It’s not only about class names, but also methods and even their implementation. Take a look at the <a href="https://github.com/BottegaIT/ddd-leaven-v2/blob/master/src/main/java/pl/com/bottega/ecommerce/sales/application/impl/OrderingServiceImpl.java#L153">following piece of cod</a>e — it reads almost like a prose:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/727/0*LncqISzYLhjY3uUu.png" /><figcaption>Code taken from example DDD project linked above.</figcaption></figure><p>Try a trick with that piece of code: strip all Java-specific language constructs from it and give it to a non-technical person to read. If they grasp it, then it’s good code. Such technique is called „<a href="http://mbartyzel.blogspot.com/2013/06/en-code-speaks-to-you.html">IVONA test</a>„, a term coined by Michał Bartyzel. You can even use „IVONA text-to-speech software to try it yourself.</p><p>Another protip for object analysis with domain expert is to note down everything expert says. Not only gives us the record, but also lets find out illogical statements and missing pieces of the puzzle — things software engineers are pretty good at. Furthermore, it’s a base for linguistic analysis, that translated to object analysis quite nice. Here’s how parts of sentence translate into programming language constructs:</p><ul><li>To reservation add product, given quantity</li><li>Subject.predicate(object)</li><li>Object.method(parameter)</li><li>reservation.add(product, quantity)</li></ul><p>During the talk the speaker touched on many other aspects of Domain Driven Design. Many of them deserve their own blog posts, so let me just list them:</p><ul><li>Whirlpool Model Exploration — knowledge flow between expert and modeler</li><li>how different people see system (and objects in it) differently</li><li>why estimations based on GUI mockups are bad idea</li><li>why process does not tell you everything</li><li>visualization techniques</li></ul><p>Overall the lecture was packed with knowledge from different domains (linguistics, visualization, knowledge exploration, cognitive science, object oriented design, DDD) with great jokes incorporated at the right moment. Even though talk was light in terms of perception and entertaining. It is definitely worth watching if you have got a chance. Thank you Sławek.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2cf45f8941ad" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[More #OpsEmpathy In Software Development]]></title>
            <link>https://adambrodziak.medium.com/more-opsempathy-in-software-development-ce2f8e8f4b89?source=rss-5fe74050beb4------2</link>
            <guid isPermaLink="false">https://medium.com/p/ce2f8e8f4b89</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[system-administration]]></category>
            <category><![CDATA[operations]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Adam Brodziak]]></dc:creator>
            <pubDate>Mon, 22 Aug 2016 16:16:17 GMT</pubDate>
            <atom:updated>2017-01-23T15:21:33.446Z</atom:updated>
            <content:encoded><![CDATA[<h4>After years of doing DevOps now I’m in situation where there are several operation teams to work with.</h4><p>System administrator job is hard. They have to make sure everything works smooth all the time. That includes the complex legacy system that nobody fully understands. Such work is often invisible and goes unappreciated.</p><h4>Do The Dirty Work Yourself First</h4><p>For the last few days I’ve put myself into shoes of such operation person trying to install and configure software developed by me. It was quite a painful and frustrating experience trying to debug why remote syslog does not receive messages over UDP. I can only imagine how much more difficult would be to make the same without inherent knowledge of the application and how all the things were wired together.</p><p><strong>Such experience led me to the insight: have more empathy for people who maintain your software.</strong> It does not matter if you have separate operation team or doing DevOps. The person taking care of your app will be grateful. Also keep in mind that person could be future you. The future you who did not slept well and has got huge hangover (been there, done that).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/897/1*QjOFLLeMK4uAiwH24e9OEQ.jpeg" /><figcaption>The success of your software is on the shoulders of giants!</figcaption></figure><h4>Try Docker To Make Yourself Uncomfortable</h4><p>Using tools like Docker makes the work much simpler. It is useful even if operations team is not using containers, like it is in my case. If the whole system works in such hostile environment like Docker it won’t have any problem being deployed to virtual machine or bare metal.</p><p>Using Docker you are able to simulate cluster on your laptop with all the warts and shortcomings of production environment: no easy access to files, limited way to peek how application is performing (trace, debug), network access restrictions from one container to another. The default Docker configuration is pretty restrictive — just how any reasonable system administrator would do it.</p><h4>Put Yourself In The Shoes Of The Maintainer</h4><p>Look at your logs as you’d have to do application support. How quickly you’re able to determine what the problem is looking only at log message or attached stack trace? Is is obvious what is wrong and what is the severity of the problem? From support person perspective: is it clear who to call for help to debug the issue further?</p><p>Rise-up and leave the comfort of IDE and try to pin down the root cause of a bug using toolset available for admins. Instead of interactive debugger try to process application logs with grep and awk. That might be quite a challenge, which means logs need improvement. Bear in mind: setting log level to DEBUG is cheating!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ce2f8e8f4b89" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Domain Driven Design makes you think about the business]]></title>
            <link>https://adambrodziak.medium.com/domain-driven-design-makes-you-think-about-the-business-7d3b9957efe4?source=rss-5fe74050beb4------2</link>
            <guid isPermaLink="false">https://medium.com/p/7d3b9957efe4</guid>
            <category><![CDATA[business-development]]></category>
            <category><![CDATA[software-architecture]]></category>
            <dc:creator><![CDATA[Adam Brodziak]]></dc:creator>
            <pubDate>Fri, 24 Jun 2016 21:00:34 GMT</pubDate>
            <atom:updated>2016-06-24T21:00:34.366Z</atom:updated>
            <content:encoded><![CDATA[<h4>How we discovered big shift an auction platform has made at the DDD training.</h4><p>At Domain Driven Design training we’ve been given an exercise to model domains of Allegro (more on what’s that later) and try to mark which ones belong to Core Domain. The modeling phase went quite smooth, but we’ve faced a problem when it came to choose Core Domain of the business. My colleagues and I argued and could not came to conclusion. In hindsight the reason is obvious, but first let me tell you a story.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*-YCVlcP3vsNBpHmuq7zmJA.jpeg" /><figcaption>This logo is a synonym for buy and sell online in Poland.</figcaption></figure><p><a href="http://allegro.pl/">Allegro</a> is an auction platform that was originally coded over the weekend and quickly became very popular in Poland. To give you an impression how much success they’ve got — the eBay.com tried to enter the Polish market, but failed miserably co compete against local player despite the brand and investments. Back then Allegro was much better in terms of user experience, but that’s different story. Right now the company is true eCommerce giant with several brands (including some abroad) and development offices in few cities.</p><p>The biggest alternative on the market is a spinoff made by the same company called <a href="http://olx.pl/">OLX</a> with slightly different target. Currently OLX is an actual auction platform where people put their no longer needed stuff for sale. On the other hand Allegro transitioned into a platform for shops and professional merchants and became more of a Internet price comparison engine. Which gets us to the point of Core Domain disagreement we’ve faced during the exercise.</p><p>My imagination of modern Allegro was the shopping mall, where convenience and variety of choice is the most important factor. In this case the easiness of finding the right goods, UX of checkout and payment are top priority and Core Domain. My colleagues thought of old school auction platform (that Allegro used to be) where user trust is top priority, so comments and ranks belong to core. The trainer said that we’ve spotted business shift , which results in Core Domain transition as well.</p><p>Understanding such business changes its very important, because it changes the system dynamics. In case os such big shift of Core Domain the whole company is affected actually. Personally I wonder how it is reflected in the development and system architecture. I can only guess that new Core Domain becomes the new shiny thing where best people work, starting from scratch and integration with legacy code is done using Anti Corruption Layer.</p><p>Overall the DDD training was a great experience. It was well prepared and held, modeling and coding exercises were cool too. The biggest benefit though was how Domain Driven Design approach enabled us, developers, to think in business terms, not technical. That seems to be the biggest advantage of DDD.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7d3b9957efe4" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>