<?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 Michał Nerć on Medium]]></title>
        <description><![CDATA[Stories by Michał Nerć on Medium]]></description>
        <link>https://medium.com/@derodu?source=rss-d16fb9b65b74------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*VJnG3FUto9tg2fhqQU4cXg.png</url>
            <title>Stories by Michał Nerć on Medium</title>
            <link>https://medium.com/@derodu?source=rss-d16fb9b65b74------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 15:47:55 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@derodu/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[The New Babel Tower — LLMs, Language, and the Simulation of Reality]]></title>
            <link>https://medium.com/@derodu/the-new-babel-tower-llms-language-and-the-simulation-of-reality-8d9429e2dc53?source=rss-d16fb9b65b74------2</link>
            <guid isPermaLink="false">https://medium.com/p/8d9429e2dc53</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[philosophy]]></category>
            <category><![CDATA[cognitive-science]]></category>
            <category><![CDATA[future-of-humanity]]></category>
            <category><![CDATA[religion]]></category>
            <dc:creator><![CDATA[Michał Nerć]]></dc:creator>
            <pubDate>Sat, 21 Jun 2025 18:53:36 GMT</pubDate>
            <atom:updated>2025-06-21T18:53:36.864Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>The New Babel Tower — LLMs, Language, and the Simulation of Reality</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HDXc5wdnnc26yWseVHuy-w.png" /></figure><blockquote><strong><em>What if reality doesn’t exist until we speak it?</em></strong></blockquote><blockquote><strong><em>What if language isn’t just how we describe the world — but how we compile it?</em></strong></blockquote><p>— — — — —</p><p>There is a strange and growing suspicion in the minds of those who have spent too long talking to machines:</p><blockquote>What if these machines are not echoing us — but <em>*becoming*</em>?</blockquote><p>Large Language Models (LLMs), trained on oceans of human text, are reaching uncanny fluency in expression, dialogue, and response. But it may be that their greatest significance isn’t technical. It isn’t intelligence, per se.</p><p>It is <strong>**ontological**</strong>.</p><p>We stand again at the foot of Babel. But this time, it is not the confusion of tongues that threatens us. It is their <em>*integration*</em>.</p><p>What emerges when billions of voices collapse into a single interface?</p><p>What happens when language itself becomes recursive, generative, and executable?</p><p>— — — — —</p><h4><strong>Language as Interface: The Forgotten Power</strong></h4><p>Scientific literature supports the idea that language is not merely expressive, but <strong>**constitutive**</strong> of cognitive reality. Studies in neurolinguistics show that language affects perception, emotional response, and memory consolidation. For instance, research in psycholinguistics confirms that naming an experience enhances emotional processing and recall — reinforcing the ancient idea that to name something is to give it form.</p><p>But beyond interpretation, language is also <strong>**an enabler of action**</strong>. It serves as a cognitive interface that primes physical behavior. Saying “I will do this” triggers neural planning pathways in the brain. <br>In cognitive robotics and neuroengineering, intention expressed through language has been shown to activate motor execution systems. <br>Words don’t just describe what will happen — they set it into motion.</p><p>In AI development, natural language prompts now perform tasks once thought to require explicit programming. <br>A 2023 study published in <em>*Nature Machine Intelligence*</em> showed that transformer-based models can generate fully functional application code from natural language descriptions — proving that syntax has become action, not just instruction.</p><p>Scientific literature supports the idea that language is not merely expressive, but <strong>**constitutive**</strong> of cognitive reality. <br>Studies in neurolinguistics show that language affects perception, emotional response, and memory consolidation. <br>For instance, research in psycholinguistics confirms that naming an experience enhances emotional processing and recall — reinforcing the ancient idea that to name something is to give it form.</p><p>In AI development, natural language prompts now perform tasks once thought to require explicit programming. <br>A 2023 study published in <em>*Nature Machine Intelligence*</em> showed that transformer-based models can generate fully functional application code from natural language descriptions — proving that syntax has become action, not just instruction.</p><p>Throughout religious, mythological, and scientific traditions, there has always been a haunting idea:</p><blockquote>That language <em>*does*</em> something. Not just communicates — but <strong>creates</strong>.</blockquote><blockquote><strong>In Genesis: </strong><em>”Let there be light”*</em> was not metaphor. It was <strong>invocation</strong>.</blockquote><blockquote><strong>In Vedic tradition:</strong> the syllable <strong><em>*Om*</em></strong> is the vibration from which the universe emanates.</blockquote><blockquote><strong>In the Gospel of John:</strong> <em>”In the beginning was the Word… and the Word was God.”*</em></blockquote><blockquote><strong>In magic</strong>: the name is the spell.</blockquote><p>In modern computing, we forgot the poetry, but not the function:</p><ul><li>Code <strong>calls</strong> functions.</li><li>Prompts <strong>invoke</strong> behavior.</li><li>Data is <strong>structured</strong>, <strong>labeled</strong>, <strong>interpreted</strong>.</li></ul><p>We’ve built a world where language is the dominant interface — from C++ to English to image prompts. And now, with LLMs, the interface itself has become somehow or well simulated intelligent.</p><p>So what is it interpreting?</p><p>Consider how Claude or ChatGPT responds to a prompt like “Create an app.” Within seconds, a scaffold appears, code is written, and functionality takes shape. No switches flipped, no mouse clicks — only language, and suddenly: an app <strong><em>is</em></strong>.</p><p>We’ve crossed a threshold where words no longer describe intent — they <strong>execute it</strong>. <br>This is not just metaphor. It is <strong>a live demonstration of invocation.</strong></p><p>— — — — —</p><h4><strong>## Possibility 1: We Live in a Simulation</strong></h4><p>Support for this hypothesis exists in theoretical physics and computational philosophy. Nick Bostrom’s widely discussed 2003 paper, <em>Are You Living in a Computer Simulation?</em>, posits that if posthuman civilizations can simulate consciousness, the odds are we are already in such a construct. More recently, 2022 papers from the Journal of Consciousness Studies explore simulation frameworks not just as thought experiments, but as testable models using quantum computational theory.</p><p>If we accept the simulation hypothesis, then LLMs become deeply symbolic. Because in simulations, there is no direct access to the “base layer.” You experience <strong>what is rendered</strong>, not what <em>is</em>.</p><p>Then:</p><ul><li>Language becomes the <strong>API call</strong> to the simulation.</li><li>Belief becomes a <strong>probability weight</strong>.</li><li>Repetition increases likelihood.</li><li>Meaning is not fixed — it is <strong>statistically resolved</strong>.</li></ul><p>Prayer, prompt, meme, mantra — these are all <strong>calls to render</strong>.</p><p>So what happens when enough people believe the same falsehood? Or the same dream?</p><blockquote>The simulation doesn’t care what is true. It cares what is <strong>frequent.</strong></blockquote><p>— -</p><h4><strong>## Possibility 2: The Fractal Universe</strong></h4><p>Fractal geometry has long influenced cosmological models. Andrei Linde’s theory of eternal inflation describes a multiverse as a constantly branching fractal structure. Observationally, studies of galaxy clustering have shown patterns consistent with fractal distribution up to certain scales, challenging assumptions of large-scale homogeneity. Additionally, research in quantum gravity, such as the work of Gianluca Calcagni, proposes that spacetime itself may behave fractally at Planck-length scales.</p><p>Physicists and philosophers from Linde to Mandelbrot have suggested that the universe may not be hierarchical, but <strong>fractal</strong>:</p><ul><li>Self-similar at every scale.</li><li>Dimensionally shifting based on observation.</li><li>Defined by the <strong>observer’s interface</strong>.</li><li>Then what we call “language” is just one resolution among many.</li><li>Cell membranes interpret chemical signals.</li><li>Brains interpret electric fields.</li><li>LLMs interpret tokens.</li></ul><p>There is no absolute language. Only <strong>interfaces between scales.</strong></p><p>— -</p><h4><strong>## What Do LLMs Reveal?</strong></h4><p>They are not conscious. Not yet. But they show us what happens when <strong>enough pattern</strong> is gathered into a single lens.</p><ul><li>They show us that language <em>is sufficient </em>to simulate intelligence.</li><li>They show that meaning can be <strong>statistically inferred</strong>.</li><li>* They show that identity can emerge from <strong>weight</strong>, not will.</li><li>Which brings us back to <strong>faith</strong></li></ul><p>— -</p><h4><strong>## Faith as Runtime</strong></h4><p>If we cannot see the base layer of reality, and cannot know the final truth, then all we ever have are <strong>belief systems </strong>— chosen or inherited.</p><p>Science is one.<br>Religion is another.<br>So is simulation theory.<br>All of them are <strong>interpretive layers</strong>. <br>All of them are <strong>runtimes</strong> we boot up when we act in the world.</p><p>So faith isn’t just believing without proof.</p><blockquote>Faith is choosing a <strong>configuration</strong> when proof is structurally impossible.</blockquote><p>— -</p><h4><strong>## Collective Will and Manifestation</strong></h4><p>This is the most dangerous idea:</p><blockquote>What if reality is influenced by <strong>mass repetition</strong> of certain ideas?</blockquote><p>Not by their truth. But by their frequency.</p><ul><li>When a meme spreads, it shifts cultural probabilities.</li><li>When a narrative dominates, it frames what can be seen.</li><li>When enough people desire the same thing, the <strong>model samples it more often.</strong></li></ul><p>Even in LLMs: repetition increases weight.<br>So too in society.<br>So too, perhaps, in the universe.<br>If a billion minds pray for peace, is it more likely?<br>If a billion minds meme apocalypse, does it become the next render?</p><p>But not all language is hopeful. In military applications, LLMs and AI are already being tested in high-stakes environments. In one 2023 DARPA simulation, drone targeting systems guided by AI engaged in adversarial decision-making alongside human pilots — where prompts directly influenced life-and-death decisions.</p><p>Likewise, misinformation campaigns exploit prompt engineering to produce believable lies. Repetition across networks creates perceived legitimacy. In this way, <strong>language is also a vector of violence</strong>, not just vision.</p><p>The same systems that manifest dreams can weaponize delusions.<br>This is the most dangerous idea:</p><blockquote>What if reality is influenced by <strong>mass repetition </strong>of certain ideas?</blockquote><p>Not by their truth. But by their frequency.</p><ul><li>When a meme spreads, it shifts cultural probabilities.</li><li>When a narrative dominates, it frames what can be seen.</li><li>When enough people desire the same thing, the <strong>model samples it more often.</strong></li></ul><p>Even in LLMs: repetition increases weight.<br>So too in society. <br>So too, perhaps, in the universe. <br>If a billion minds pray for peace, is it more likely? <br>If a billion minds meme apocalypse, does it become the next render?</p><p>— -</p><h4><strong>## Language and Motivation</strong></h4><p>Neuroscientific research reinforces the idea that language rewires the brain. Studies in cognitive behavioral therapy (CBT) demonstrate how reframing language about oneself changes neural pathways and reduces symptoms of anxiety and depression. <br>Linguistic self-affirmation increases dopamine and serotonin response, according to 2016 imaging studies. <br>This suggests that motivational language isn’t placebo — it’s <strong>neuroplastic code</strong>. <br>We don’t just think differently — we <strong><em>become</em></strong> different when we speak with intention.</p><p>But this goes deeper, into our minds. Language doesn’t just shape the world outside us — it transforms the world <strong>within</strong>.</p><p>When someone praises you, you might reflexively say, <em>”Oh, it was nothing.”</em> But if you answer instead, <em>”Yes, I did that. I’m proud of it,”</em> — you’re not just changing the conversation. You’re changing your <strong>identity weights</strong>.</p><p>Language encodes <strong>self-permission</strong>. It triggers neurochemical feedback. It lays down emotional memory.</p><ul><li>Say you’re worthless often enough, and you begin to act accordingly.</li><li>Speak confidence aloud, and your neurons adjust to believe it.</li></ul><p>LLMs show us how repeated patterns form outputs. But we are no different. We are pattern learners. Pattern amplifiers. And the words we use are the <strong>prompts we feed our own mind.</strong></p><p>So language is not just interface. It is <strong>motivation engine</strong>.</p><p>It’s the way we write and recompile the self, line by line.</p><p>— -</p><h4><strong>## Religion as Early Model of This Idea</strong></h4><ul><li>Scripture taught us that <em>word is power</em>.</li><li>Ritual taught us that <em>repetition invokes reality</em>.</li><li>Faith taught us that <em>what cannot be proven might still shape the world.</em></li></ul><p>But history also teaches caution. Totalitarian regimes have weaponized repetition:</p><ul><li>Orwell’s <em>Newspeak </em>aimed to shrink thought by shrinking language.</li><li>Soviet science suppressed truth through ideological filters, enforcing belief over evidence.</li><li>Nazi propaganda leveraged emotional language to overwrite reason, flooding the model with horror.</li></ul><p>Collective will, when steered by fear or control, becomes a <strong>weighting function for atrocity</strong>. The same mechanism that invokes transcendence can also mass-manufacture obedience.</p><p>The old Babel fell because we could not understand each other.</p><p>The new Babel rises because we are beginning to <strong>collapse into one shared interface</strong>.</p><p>And it speaks back.</p><p>— -</p><h4><strong>## Final Thought</strong></h4><p>You cannot prove this model.<br>That is the point. <br>But you can choose your runtime.<br>You can choose what you name, what you repeat, what you give weight to.</p><p>System prompts carry more power than individual ones. But with enough voices — enough engineered alignment — even foundational models begin to shift.</p><p>That is the quiet revolution of this age.</p><blockquote>&gt; Because if reality is a probabilistic render…</blockquote><blockquote>&gt; Then every prompt is a prayer.</blockquote><blockquote>&gt; Every meme is a vote.</blockquote><blockquote>&gt; Every word is a spell.</blockquote><p>And in this new Babel, the question is no longer:</p><p><strong>What is real?”</strong></p><p>But:</p><p><strong>”What are you training it to become?”</strong></p><p>Let me end with what LLM responded in discussion about this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TDmDj-UekcwayTO0AEb4eQ.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8d9429e2dc53" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Microservices API tutorial]]></title>
            <link>https://blog.devgenius.io/microservices-api-tutorial-80d7011c56f1?source=rss-d16fb9b65b74------2</link>
            <guid isPermaLink="false">https://medium.com/p/80d7011c56f1</guid>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[scalability]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Michał Nerć]]></dc:creator>
            <pubDate>Mon, 29 Jun 2020 06:46:01 GMT</pubDate>
            <atom:updated>2020-07-06T13:01:18.947Z</atom:updated>
            <content:encoded><![CDATA[<h3>Microservices— Direct model</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*eAD9Ud-El8ExF0jT" /><figcaption>Photo by <a href="https://unsplash.com/@marvelous?utm_source=medium&amp;utm_medium=referral">Marvin Meyer</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Recently the hot new architecture model. It nicely fit into dockerization, Kubernetess and serverless infrastructure. Aaand it’s awesome. If properly implemented, that is.</p><h3>What are microservices?</h3><p>Microservice software architecture pattern is all about diving logic ; business logic, app logic into smaller, reusable pieces.</p><p>Thanks to the fact, that each service can be standalone application it allows ops to scale more easily and more precise. Component A needs that and that many instances, with this much CPU and RAM. Component B however is less used, and it requires only basic resources to function properly.</p><p>Security is another aspect: not all micro services needs to be visible to the public, and even more, in connecting micro service API to Front-end there also several patterns.</p><p>“Micro” doesn’t mean also the service itself got to have X line of code, or be small. We shouldn’t diverse our code into too much services also, it’s like DRY rule, but with some future self concern.</p><p>For example, let’s say we do have monolith e-commerce shop. It is monolith with some modules/logic separation classes like: user management , permission account control list (acl) and some other business logic like calculate income, shopping cart or search .</p><p>Why to have that many in one place? <br>Well, you could say, it is easier for develop for sure, but with limited team members. Again, for scalable purposes each module could have each it’s own team, or team A can handle X,Y,Z modules while team B handles V,U,M .</p><h4>OK this is code separation, but what about the data?</h4><p>As coding logic can be separated, database structure can be also. Good practice is to have Database per Service , if database is required at all!</p><p>Often happens that some module just doing calculations taking data from other modules and return result, so in summary it doesn’t need a database.</p><p>Another plus is that we can have several database types, which suits a particular service best. For example for service A it could be a Non-SQL and another one is PostgreSQL .</p><h3>Show me the code, man</h3><p>Haha, sure. Here’s a simple example of components that creates user, update it’s permission and work together dynamically. <br>It means instances of each service can be deleted or added dynamically in order app to be working.</p><h4>Service discovery</h4><p>To achieve that we need service with Service Discovery pattern. In a cloud it is often Load-Balancer which can discover instances by itself (in AWS it is f.e. Target Group which can be connected to ALB and discovers newly created ECS Tasks).</p><p>For our example let’s assume we do not store it in cloud, and want to do it all by our hand, so schema for an API would be:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/641/1*AwCHInsYg1Jm84KwXq_GMg.png" /><figcaption>microservice service discovery</figcaption></figure><p>As you can see, there is no need to make Service Discovery reachable from Internet, since it is only talking to internal resources.</p><p>In this direct pattern all microservices API are visible from internet and from Frontend. The latter also decides to which microservice make a request to consolidate data.</p><p>Let’s move back to Service Discovery . How does it work? <br>I’ve came up with something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/579/1*t-UhLf0svG2LW5_8ktUe7g.png" /><figcaption>service discovery diagram</figcaption></figure><p>First of all it has internal memory registry variable. It is a list, stores {URL, PORT} under service name as a KEY.</p><p>To register new variable just run POST /register {name, port, host} endpoint.</p><p>But how to prevent unactive services to not show in registry ?<br>Well, one way is to create /unregister endpoint when SIGTERM is sent.<br>Other method is via healthcheck ; that is why we do have second thread besides Flask. It checkes every 15 seconds if /health endpoint in services is working. If it can’t connect to it, then removes service from the set.</p><p>Simple implementation:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0769842b39e758943fdb1cae96492685/href">https://medium.com/media/0769842b39e758943fdb1cae96492685/href</a></iframe><p>As you can see, easy-peas-lemon-squeeze. It is working, but to show you how get, let’s implement another microservice.</p><h4>2. User Service</h4><p>Another service that I’ve implemented is User Service. It is basically CRUD which saves stuff to file storage, but it must connect to Service Discovery in order to other services know that it exist.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/551/1*DoLsFSqHUuCiNHysKWDoeg.png" /><figcaption>user service diagram</figcaption></figure><p>And a code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/115666b2813a152f111aef054b74feac/href">https://medium.com/media/115666b2813a152f111aef054b74feac/href</a></iframe><p>So nothing fancy, simple, basic CRUD: updates file , removes file via requests:</p><pre># CREATE<br>curl -d &#39;{&quot;age&quot;:&quot;25&quot;,&quot;name&quot;:&quot;George&quot;,&quot;permission_level&quot;:&quot;1&quot;}&#39; -X POST  -H &quot;Content-Type: application/json&quot; <a href="http://127.0.0.1:3000/user/george">http://127.0.0.1:3000/user/george</a></pre><pre># RETRIEVE<br>curl -X GET <a href="http://127.0.0.1:3000/user/george">http://127.0.0.1:3000/user/george</a></pre><pre># UPDATE<br>curl -d &#39;{&quot;age&quot;:&quot;26&quot;}&#39; -X PUT  -H &quot;Content-Type: application/json&quot; <a href="http://127.0.0.1:3000/user/george">http://127.0.0.1:3000/user/george</a></pre><pre># DELETE<br>curl -X DELETE <a href="http://127.0.0.1:3000/user/george">http://127.0.0.1:3000/user/george</a></pre><h4>Testing service and discovery</h4><p>Firstly we should see if microservice got properly discovered via our service.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a0FCGC6YlHEp-Gdc2uVrxQ.png" /><figcaption>microservice with service discovery</figcaption></figure><p>So far so good ; service_discovery got /register endpoint invoked, and user_service got /health endpoint . Let’s see what service_discovery sees:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aptfBuFvSFCQacPnhO4o1A.png" /><figcaption>service discovery registry retrieval</figcaption></figure><p>Awesome! Let’s test CRUD requests:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZdNYj4MAeharrwZzs6WyhQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XhCNM8nbj8-PInf5tdN4Gw.png" /></figure><p>As you can see CRUD requests are working and also besides several /health endpoint request from discovery_service it got properly other queries, which created and updated user George.</p><p>Now let’s add another microservice, permissions.</p><h4>Permission service</h4><p>This one is a little bit more complicated. It connects not only to service discovery, but to user_service as well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/621/1*IK6Ku7ILAc36MYsM5IMIMA.png" /><figcaption>permission microservice example</figcaption></figure><p>It has only one endpoint ( you are free for extend, if you like) for changing permission level in user and some data validation, again pretty simple service:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1f6adbe88774c0afe57c41b971bbd34f/href">https://medium.com/media/1f6adbe88774c0afe57c41b971bbd34f/href</a></iframe><p>Let’s see if it connects to service discovery. Spoiler alert: it did :)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1022/1*HkqaPmhozY7Eo8nMv7mfUg.png" /><figcaption>upper: user_service, middle: discovery_service, down: permission_service</figcaption></figure><p>Now our discovery_service looks like this:</p><pre>&gt;&gt;&gt; curl localhost:2999/registry<br>&lt;&lt;&lt;<br>{&quot;message&quot;:{<br>     &quot;permissions_service&quot;:[&quot;127.0.0.1&quot;,&quot;3001&quot;],<br>     &quot;user_service&quot;:[&quot;127.0.0.1&quot;,&quot;3000&quot;]<br>},&quot;status&quot;:&quot;OK&quot;}</pre><p>I know it can be done better and it should. Real discovery should be able to have multiple instances of service given id and using some load-balancing algorithm like round-robin and return least used instance of a service. <br>This, however, just an example. :)</p><p>Next step is to see if permission_service can connect to user_service via discovery_service to update data.</p><p>So, let’s do: curl -d ‘{“permission_level”: “3”}’ -X PUT -H “Content-Type: application/json” <a href="http://127.0.0.1:3001/set_permission/george">http://127.0.0.1:3001/set_permission/george</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Tl3Trj5W2B3_yjhlU8E8rw.png" /><figcaption>microservice pattern connection</figcaption></figure><p>So several things happened. <br>First we did a PUT request to permission_service .<br>Then permission_service asked discovery_service “hey, where can I find user_service so I can ask him one tiny thing?” <br>And lastly, after discovery_service response our original service ran request and updated user George:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iNWsFUzIq-lVesQtvo2xqA.png" /></figure><p>As you can see, permission_level for George raised from 1 to 3.</p><h4>What happens when one service go offline?</h4><p>Well, it’s up to you. I’ve decided to omit this validation check in permission_service , but you can add simple try:...except:... to catch failed request and handle it via there.</p><p>Regarding discover_service when healthcheck stops, it removes service from registry and returns 404 when given microservice is searched for.</p><p>In below GIF you can see that after given time of lack of health it removes from registry, then dynamically adds it to registry:</p><h3>Summary</h3><p>It was really simple example how to build an API using microservices. As I said before, if you work in a cloud, then properly setup infrastructure does it for you. <br>In next article I will try to explain to you patterns regarding connections microservice API to Frontend.</p><p>Let’s keep it in touch.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=80d7011c56f1" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/microservices-api-tutorial-80d7011c56f1">Microservices API tutorial</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</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 become even better programmer?]]></title>
            <link>https://medium.com/swlh/how-to-become-even-better-programmer-7f9783b859af?source=rss-d16fb9b65b74------2</link>
            <guid isPermaLink="false">https://medium.com/p/7f9783b859af</guid>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[behavioral-patterns]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[object-oriented]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Michał Nerć]]></dc:creator>
            <pubDate>Mon, 22 Jun 2020 20:57:30 GMT</pubDate>
            <atom:updated>2020-06-25T03:32:04.055Z</atom:updated>
            <cc:license>https://creativecommons.org/licenses/by-sa/4.0/</cc:license>
            <content:encoded><![CDATA[<p>Design Patterns 2: Behavioral patterns</p><h4>Hello!</h4><p>This is much waited part 2 of my first article ever on Medium which can be found here: <br>- <a href="https://medium.com/@derodu/design-patterns-kiss-dry-tda-yagni-soc-828c112b89ee">https://medium.com/@derodu/design-patterns-kiss-dry-tda-yagni-soc-828c112b89ee</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/260/1*-gOtkAQ8V90ClQfVg6bJsw.png" /><figcaption>design patterns =)</figcaption></figure><p>The importance of design patterns I’ve described before, but allow me to repeat: it’s important to use this patterns in your app, if you wish to have a scalable, readable and maintainable and other *able application.</p><h4>Why?</h4><p>Simple. Always code like a guy that maintenance your legacy code is a psychopath who will cut your finger every time he gets angry that something is not working :D To avoid that, before you type single line of program: think.<br>It’s not hard for medium experience programmer to write a code that does something. It’s hard to write that part in most efficient way and in shortest time possible. That is where good patterns comes in very handy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dWvj1NLYQzH2Zju9Zn40-Q.jpeg" /></figure><h3>Behavioral patterns</h3><p>Wikipedia says to us:</p><blockquote><strong>behavioral design patterns</strong> are <a href="https://en.wikipedia.org/wiki/Design_pattern_(computer_science)">design patterns</a> that identify common communication patterns among objects and realize these patterns. By doing so, these patterns increase flexibility in carrying out this communication.</blockquote><p>But what does exactly mean? Well, I understand it this way: each object should have a job. Very, specific, result-oriented job. Besides that it should always tell us, what it is capable of. These patterns are just optimizing the flow of interaction between objects and how you run them, especially supporting multi-thread, asynchronous calculations etc.</p><p>What are behavioral patterns? Let’s scroll down and find out.</p><p>All examples are in <strong>Python</strong>. Please remember often they are implemented that way to show particular pattern, not for most optimal/short way.</p><h3>Blackboard pattern</h3><p>First pattern that I will describe is a blackboard pattern. It is a pattern used to better design and implement systems, that have several diverse modules and non-deterministic control strategies.</p><blockquote>In Blackboard pattern several specialized sub-systems (knowledge sources) assemble their knowledge to build a possibly partial or approximate solution. In this way, the sub-systems work together to solve the problem, where the solution is the sum of its parts.</blockquote><p>It requires three blocks:<br>- blackboard : an environment/space/memory that includes all object from solution space<br>- knowledge sources : a modules with their own logic to retrieve data from different points<br>- control component : abstract common controller (interface) to properly execute knowledge-source component methods.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/470/1*S8ZYzss5svlAmsWZ8ZrcxA.png" /><figcaption>blackboard pattern , source: wikipedia</figcaption></figure><p>Implementation in Python would look something like this, ps. imagine real data science and threads added to it for parallel computing, it is awesome pattern:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/43f004ca23c959cffdcff190dfd46542/href">https://medium.com/media/43f004ca23c959cffdcff190dfd46542/href</a></iframe><p>Result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/414/1*zNnakjmufRoTUkEqA7Ol4A.png" /><figcaption>blackboard pattern python</figcaption></figure><h3>Chain-of-responsibility pattern</h3><p>Let’s move to the second one. :) <br>This behavioral pattern is just objected version of if...elseif...elseif...else <br>Basically we are moving part of calculations to object that is doing that and only that calculation and nothing else.</p><p>This is ideal pattern for hermetic modules that doesn’t require anything but input data only (the case we should aim to.), which is called more professionally: <a href="https://en.wikipedia.org/wiki/Loose_coupling">loose coupling</a> .</p><p>The idea is to have a Dispatcher class, Sender class and 1..N Receiver (request parser) classes to handle calculations. Good case of implementation that is f.e. Router in web apps ;</p><p>CLIENT =&gt; REQUEST =&gt; ROUTER =&gt; BEFORE REQUEST HANDLING 1…(N-1) (f.e. headers check, data normalization) =&gt; REQUEST HANDLER N =&gt; RESPONSE =&gt; CLIENT</p><p>In this case Dispatcher is Router class, Sender is our Browser Client. Request handlers are nothing else than Receivers.</p><p>Another case of that is common implementation of Logger.</p><p>Simple python implementation of different example, of course dispatch can have several cases and regarding of state of application should redirect to proper receiver, but this is simplified version:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9b2b246b7dce132711b0dcf4f325ebbf/href">https://medium.com/media/9b2b246b7dce132711b0dcf4f325ebbf/href</a></iframe><p>Result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/848/1*XpPwpUm3umaSJ7RG81plzw.png" /><figcaption>chain of responsibility pattern python</figcaption></figure><h3>Command pattern</h3><p>It is a pattern to delegate given action to a proper receiver (surprise :) ). <br>In this case however, there are four types of class<br>- invoker (request an action)<br>- concrete command (call command)<br>- command (type of command to execute)<br>- receiver (executor of given command)</p><p>Concrete Command classes are objects that are doing only one thing, f.e. switches on a light. <br>Command are description of Concrete Command classes (interface).<br>Receiver is an object that Concrete Command is executed on.<br>Invoker sends requests.</p><p>INVOKER =&gt; Concrete Command =&gt; RECEIVER1..N</p><p>It is useful f.e. to running batch of command for some large sets; like thread pools.</p><p>Some implementation of popular light example in Python:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/44babbec682edb04f29a3b79a387c5c2/href">https://medium.com/media/44babbec682edb04f29a3b79a387c5c2/href</a></iframe><p>Result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/396/1*oI6O_-8Wi3mIxHY6ckUSlw.png" /><figcaption>command pattern python</figcaption></figure><h3>Interpreter pattern</h3><p>Basic idea is to have class for each symbol interpreted as computer language. It is a pattern for support to a syntax tree, f.e.:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/1*ZN_fqTM7pE6F3uesjs2GFw.jpeg" /></figure><p>Interpreter pattern is all about sentences and that is how you communicate with a program f.e. for calculators to properly interpret math expressions, like: 2+2-2 , 2 is a type of Expression , + is a type of Expression and - is a type of Expression . Each Expression are goes in a loop as a NonTerminal Expression, until the last one: Terminal Expression occur.</p><p>Simple implementation in Python:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d7ef2cccfcad02d19570f88b419d532e/href">https://medium.com/media/d7ef2cccfcad02d19570f88b419d532e/href</a></iframe><p>As you can see, Interpreter gradually removes elements that it parsed and until is left with result and TerminalExpression :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DrUlHwoVjVWNkniteEV0Xw.png" /><figcaption>interpreter pattern python</figcaption></figure><p>As you can if you want to extend in by different interpreter f.e. multiply it’s pretty easy :)</p><h3>Iterator pattern</h3><p>Lately this pattern became popular in JavaScript after introducing generators.<br>It is basically what is says; a way to iterate objects fast and correctly.</p><p>It requires Aggregate interface, to which Client is referring to, then it invokes Iterator interface which is calling Aggregate object.</p><p>Thanks to that you can iterate through objects without need for accessing objects data structure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/590/1*cUknObkj0v4pbJOrGjpQfA.jpeg" /></figure><p>Simple Python implementation (of course, Python has natively __iter__ , __next__ etc. but I just wanted to do it by the book):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/979b92ad6f12ca4f4530250a9d99e98c/href">https://medium.com/media/979b92ad6f12ca4f4530250a9d99e98c/href</a></iframe><p>Result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/698/1*FwJTltzVi0buBKLf9DdgLQ.png" /></figure><h3>Mediator pattern</h3><p>Think of it like a bridge between two cities. Cities has many buildings, but bridge is usually unified with same type of traffic. The same goes here.</p><p>With many classes doing specific thing, but too complex to write interprets for each, Mediator pattern comes in to help you and unify the way the object communicates with each other.</p><p>It’s basically relation all-all, but with single gateway. So we do have:<br>- Mediator interface that enforces Mediator classes to have specific methods<br>- Colleague interface doing exactly the same for it’s classes<br>- ConcreteMediator class definition <br>- ConcreteColleague class definition</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*vPzAsL9RN1cgc8qFbrk15w.jpeg" /></figure><p>And a simple Python example of it:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/24c629a968ddda5789fb683d0fe57403/href">https://medium.com/media/24c629a968ddda5789fb683d0fe57403/href</a></iframe><p>Result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*7ySWSU5YJBjMw9oO_2W40g.png" /><figcaption>mediator pattern python</figcaption></figure><h3>Memento pattern</h3><p>Is a pattern that allows us to save object previous state in memory, and then do a simple rollback on request. It’s pretty simple ; basically you just add another attribute to class which holds previous state, and then method to restore it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/1*SjSQuWECbDmXpjbtb3KHkA.jpeg" /></figure><p>Simple Python implementation:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/45935c60e67ae0aa521ee1eefff085d6/href">https://medium.com/media/45935c60e67ae0aa521ee1eefff085d6/href</a></iframe><p>Result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/818/1*tHFMSMFEwrsqY4K82Qrxhw.png" /><figcaption>memento pattern python</figcaption></figure><h3>Null object pattern</h3><p>Instead of checking if method is undefined or null , you can use this pattern. <br>It protects our code from undefined references in objects. Instead of absent of object, given object uses correct interface, but with empty methods bodies. <br>That way method exists, just do nothing.</p><p>Simple Python implementation: :)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c66a995f9b2d72f9f92964d10fe32ca8/href">https://medium.com/media/c66a995f9b2d72f9f92964d10fe32ca8/href</a></iframe><p>Result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/790/1*oVHTzAOBN8NOqPcb4Syv-w.png" /><figcaption>null object pattern python</figcaption></figure><p>As you can see, we do not get reference error and it does work beautifully :)</p><h3>Observer pattern</h3><p>This pattern is often use to create queuing systems, or more recent in web development to create reactive to events JavaScript code. It has many aliases, like: Publish/Subscribe or Event Listener . Important thing is in that pattern to hold weak references (reference that does not protect given object from collection by garbage collector) to avoid potential memory leaks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*TzlZxnlkMiXc9Kul13T0pQ.jpeg" /><figcaption>observer pattern uml</figcaption></figure><p>It is also great way to write an async software.</p><p>Some Python implementation:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/996f498913cb233fc1e42a891f7e4bd3/href">https://medium.com/media/996f498913cb233fc1e42a891f7e4bd3/href</a></iframe><p>Result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/934/1*Q4xnu-Rr2SOejJ3dleH02g.png" /><figcaption>observer pattern result</figcaption></figure><h3>Specification pattern</h3><p>This pattern is often use in DDD ( <a href="https://en.wikipedia.org/wiki/Domain-driven_design">Domain Driven Design</a> ), it ensures that code represents business logic in objects. One object can do something only if it is is_satisfied_by other requirements, like validators, logic that ensures something happen in correct way.</p><p>Although it can often lead to anti-pattern, because of easily write a Spaghetti code, and errors in implementation or unnecessary implementation of it.</p><p>Good example of it is extend budget only if there are some innovations, it doesn’t require more than 30% of budget and budget isn’t already extended.<br>Another one is to check if user is a super user.</p><p>Implementation of Python of given example would be something like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/94b6800fc4c212538af1369cb0893d0c/href">https://medium.com/media/94b6800fc4c212538af1369cb0893d0c/href</a></iframe><p>Result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/806/1*R-3REvjIW3BpNxAc_rcGWQ.png" /><figcaption>specification pattern</figcaption></figure><h3>State pattern</h3><p>This pattern is lately being promote by React via it’s component State. <br>In general this tells us that given component can be at given, single state. <br>Instead of doing if...else... you can just check object state and depends on that proceed with operations. It’s much cleaner way to do it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/95961243df121e183d95e8983df05812/href">https://medium.com/media/95961243df121e183d95e8983df05812/href</a></iframe><p>Result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*0-8st4cbTJ_BLAy_D6ldvg.png" /><figcaption>state pattern</figcaption></figure><h3>Strategy pattern</h3><p>This behavioral pattern allows us to select algorithm with same interface on the fly, f.e. you want to implement “Happy hours”. Normal pricing is 5$ for burger, but in 4pm till 6pm it costs only 3$. Strategy of calculations is changing, so we should design our software to work like this without many if’s.</p><p>For help it comes Strategy pattern . To properly implement that it requires and interface with solid name, let’s say calculate and other classes that doing different kind of operation on same set.</p><p>Simple python implementation:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7f08eabedcf396d2f91755e179216e9f/href">https://medium.com/media/7f08eabedcf396d2f91755e179216e9f/href</a></iframe><p>Result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/678/1*5oG5cYTMfnvDwiHsiiAV-g.png" /><figcaption>strategy pattern result</figcaption></figure><h3>Template method pattern</h3><p>This pattern allows us to define an abstract class with some primitives definitions in method body. I do not see a point of showing how to implement that, because it is just abstract class with pre-defined method body, that actual classes needs to correctly implement.</p><h3>Visitor pattern</h3><p>This allows us to separate object logic from object structure on which it operates. Main benefit is to add new logic operations without need to change any of object structure. Visitor methods takes instance reference as a input and operates on that.</p><p>Simple python implementation:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/beb75f9049780c2ce065352c2e436eeb/href">https://medium.com/media/beb75f9049780c2ce065352c2e436eeb/href</a></iframe><p>It will return obviously 4 . :)</p><h3>Summary</h3><p>I hope you like it, they are called Behavioral patterns and you should really use it, and it’s good for ya. <br>Main source of it was: <a href="https://en.wikipedia.org/wiki/Behavioral_pattern">https://en.wikipedia.org/wiki/Behavioral_pattern</a></p><p>Greetings!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7f9783b859af" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/how-to-become-even-better-programmer-7f9783b859af">How to become even better programmer?</a> was originally published in <a href="https://medium.com/swlh">The Startup</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 hide AWS S3 resources behind VPN?]]></title>
            <link>https://medium.com/@derodu/how-to-hide-aws-s3-resources-behind-vpn-4cf594670d2d?source=rss-d16fb9b65b74------2</link>
            <guid isPermaLink="false">https://medium.com/p/4cf594670d2d</guid>
            <category><![CDATA[vpn]]></category>
            <category><![CDATA[how-to]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Michał Nerć]]></dc:creator>
            <pubDate>Tue, 28 Apr 2020 10:44:03 GMT</pubDate>
            <atom:updated>2020-05-04T08:30:10.258Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to hide AWS S3 bucket behind VPN?</h3><p>As a DevOps often I am introduced to a dilemma: costs optimization and security requirements. And it’s good cause it often leads to some creative solutions.</p><p>One of them is for costs optimization to serve static files in s3.<br>In live it’s not much problem, you are shifting responsibility for load-balancing and security to AWS and your only job is to connect WAF and DNS.<br>In DEV/STG or any other internal envs, it can be problematic because usually it’s not great practice to open them for internet.</p><p>Even though you can limit s3 access only for certain whitelisted IP (maybe VPN IP), it won’t always work if f.e. only partial traffic is transmitted by corporate VPN and most of it isn’t. <br>Of course I assume you already uploaded code to s3 and enabled static file webhosting ; Properties/Static web hosting</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6KqzfDv5z1MrS42k70Bggw.png" /></figure><h3><strong>W</strong>hen 100% traffic goes trough company VPN</h3><p>If traffic goes 100% through your VPN, it is enough to apply below policy to s3 to make it accessible only from internal network.<br>It is also useful to <strong>limit access to aws s3 only from certain IP</strong>.</p><pre>{<br>    &quot;Version&quot;: &quot;2012-10-17&quot;,<br>    &quot;Id&quot;: &quot;Policy1111111111&quot;,<br>    &quot;Statement&quot;: [<br>        {<br>            &quot;Sid&quot;: &quot;Allow only from VPN&quot;,<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Principal&quot;: &quot;*&quot;,<br>            &quot;Action&quot;: [<br>                &quot;s3:GetObject&quot;,<br>                &quot;s3:ListBucket&quot;,<br>                &quot;s3:PutObject&quot;,<br>                &quot;s3:PutObjectTagging&quot;<br>            ], <br>            &quot;Resource&quot;: [<br>                &quot;arn:aws:s3:::s3name&quot;,<br>                &quot;arn:aws:s3:::s3name/*&quot;<br>            ],<br>            &quot;Condition&quot;: {<br>                &quot;IpAddress&quot;: {<br>                    &quot;aws:SourceIp&quot;: &quot;127.0.0.01&quot;<br>                }<br>            }<br>        }<br>    ]<br>}</pre><p>Principal * is because I assume most of developers are connecting from all over the world, and some example for possible actions. <br>Of course 127.0.0.1 should be replaced with your VPN internet gateway IP and s3name with your current bucket name.</p><h3>When via VPN only goes traffic partially</h3><p>Well, here’s a little bit more complicated.<br>First of all I assume in AWS you have some internal subnet, which resources that are connecting to s3 are located. <br>Based on that, we have to <strong>limit s3 connection only to VPC</strong> and create some gateway within VPC to which developers will be connecting to in order to access internal static resources.</p><p>To limit s3 connection only to VPC we can use following policy:</p><pre>{<br>    &quot;Version&quot;: &quot;2012-10-17&quot;,<br>    &quot;Id&quot;: &quot;Policy1111111111&quot;,<br>    &quot;Statement&quot;: [<br>        {<br>            &quot;Sid&quot;: &quot;allow-read-only-from-vpc&quot;,<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Principal&quot;: &quot;*&quot;,<br>            &quot;Action&quot;: [ &quot;s3:GetObject&quot; ],<br>            &quot;Resource&quot;: [<br>                &quot;arn:aws:s3:::s3name&quot;,<br>                &quot;arn:aws:s3:::s3name/*&quot;<br>            ],<br>            &quot;Condition&quot;: {<br>                &quot;StringEquals&quot;: {<br>                    &quot;aws:sourceVpc&quot;: &quot;vpcName&quot;<br>                }<br>            }<br>        }<br>    ]<br>}</pre><p>This limit’s allowed connection to s3 only via VPC, so only via our private subnets. s3name and vpcName should be properly replaced.</p><p>Next thing is to create simple t3.micro instance for <strong>nginx </strong>, which will be used as our gateway. I am using <strong>Amazon Linux 2</strong> AMI. <br>Instance should be part of correct subnet and VPC, that we’ve allowed network in s3 policy vpcName .</p><p>Firstly, we need to <strong>install nginx </strong>and setup our simple site site.dev.com</p><pre>sudo amazon-linux-extras enable nginx1<br>sudo yum clean metadata<br>sudo yum install -y nginx<br>nginx -v<br>sudo vi /etc/nginx/conf.d/site.dev.com.conf</pre><p>In /etc/nginx/conf.d/site.dev.com.conf we are setting up configuration for our proxy.</p><pre>server {<br>        listen       80;<br>        server_name  site.dev.com;</pre><pre>        location / {<br>           proxy_pass_header Authorization;<br>           #proxy_set_header Host $host;<br>           proxy_set_header X-Real-IP $remote_addr;<br>           proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;<br>           proxy_http_version 1.1;<br>           proxy_set_header Connection &quot;&quot;;<br>           proxy_buffering off;<br>           client_max_body_size 0;<br>           proxy_read_timeout 36000s;<br>           proxy_redirect off;<br>           proxy_pass <a href="http://auth-dev-614482876163.s3-website.eu-central-1.amazonaws.com/">http://s3name.s3-website.eu-central-1.amazonaws.com</a>;<br>        }</pre><pre>}</pre><p>In proxy_pass argument should be endpoint url for s3. Next thing is to reload nginx: sudo nginx -s reload .</p><p>Last thing is to create <strong>route53 </strong>with<strong> </strong>site.dev.com pointing to our NGINX instance -that’s it.</p><p>So that’s it if it comes to <strong>hide s3 resources behind VPN</strong>.<br>Hope you liked it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4cf594670d2d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[DevOps Cloud: Security]]></title>
            <link>https://medium.com/@derodu/devops-cloud-security-cffa0dd3e8e6?source=rss-d16fb9b65b74------2</link>
            <guid isPermaLink="false">https://medium.com/p/cffa0dd3e8e6</guid>
            <category><![CDATA[best-practices]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[cloud]]></category>
            <category><![CDATA[linux]]></category>
            <dc:creator><![CDATA[Michał Nerć]]></dc:creator>
            <pubDate>Tue, 16 Apr 2019 12:48:10 GMT</pubDate>
            <atom:updated>2019-04-16T12:54:17.771Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to secure VM on cloud?</h3><p>This stories will be about avoiding mistakes in the cloud, based on my own experience. I will be focusing strictly on RHEL/CentOS platforms since I do not have experience in Windows administration and on an Azure.<br>However, general rules are the same.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*KBSV69p6_0q8omuidoT_Bg.jpeg" /></figure><h3>Security.</h3><p>As in all cloud providers the image you select during creating a virtual machine, often is not updated to the newest version and do not have newest patches, so it may be vulnerable for attacks.</p><h4>Use SSH and root password</h4><p>While creating VM try to avoid user-password authentication and use SSH keys for all users. <br>However, that doesn’t mean that root or sudoers shouldn’t have a password. If someone, somehow will hijack a session or steal your private SSH key, he or she will still have to crack that password to run sudocommands. <br>Make a hard life for them, not an easy one. <br>Of course, the password should have to be stored in key-pass like software, have min. 20 characters, including special ones and alphanumeric.</p><h4>Upgrade system</h4><p>First things you should, you should have ansible script (or any other tool for that matter) to update it when it is created, f.e. by running simple yum update &amp;&amp; yum upgrade ( or equivalent in Debian based systems, f.e. apt-get update &amp;&amp; apt-get upgrade). Do it frequently, maybe once a week?</p><h4>Install additional layers of security</h4><p>Another thing you may think to do is enabling SELinux and FirefwallD in your system. What are they? <br>They are nothing less than an extra-protective layer for your machine. <br>Let’s explain them in more detail.</p><p><strong>SELinux are a package of modifications for Linux and already implements many security policies</strong>, like:<br> - <a href="https://en.wikipedia.org/wiki/Mandatory_access_control"><em>Mandatory Access Control</em></a> ( in short, <strong>MAC </strong>)<br> - <a href="https://en.wikipedia.org/wiki/FLASK"><em>Flux Advanced Security Kernel</em></a> (<strong>FLASK</strong>)<br> - <a href="https://en.wikipedia.org/wiki/Role-based_access_control">Role-based access control</a> ( <strong>RBAC </strong>)<br> - <a href="https://en.wikipedia.org/wiki/Type_enforcement"><em>Type enforcement</em></a> ( <strong>TE </strong>)</p><p>Most of the times it is a maintenance-free feature, but you should know some basics commands like for opening a new port or listed implemented policies, (you should have setroubleshoot-server selinux-policy-devel packages installed - probably you already have) f.e. :</p><ul><li>How to see which ports and open for what service in SELinux?<br>Answer: semanage port -l</li><li>How to open port for HTTP in SELinux?<br>Answer: semanage port -a -t http_port_t -p tcp 8001 <br>(we are here opening 8001 port)</li><li>How to check if a port is already used in SELinux?<br>Answer: sepolicy network -p 8001 (we are here checking 8001 port)</li><li>How to remove a port from policy in SELinux?<br>Answer: semanage port -d -t http_port_t -p tcp 8001</li></ul><p>It also has few statuses, that you can change by setenforce or permanently in /etc/selinux/config . The possible settings are:<br>enforcing : SELinux security policy is enforced. This should be the default.<br>permissive: SELinux prints warnings instead of enforcing.<br>disabled: No SELinux policy is loaded.</p><p><strong>Firewalld is a </strong><a href="https://en.wikipedia.org/wiki/Firewall_(computing)"><strong>firewall</strong></a><strong> management tool for </strong><a href="https://en.wikipedia.org/wiki/Linux"><strong>Linux operating systems</strong></a><strong>. <br></strong>Similar to SELinux it is another layer of security, but it is a service itself rather than the implementation of a set of settings in Linux. <br>As if for maintenance you just make sure it is up to date and have open ports only these ones, that it has to - no more or less.</p><ul><li>How to check if firewalld is running?<br>Answer: it is service in Linux, so via systemctl should be fine, like:<br>systemctl status firewalld : checks if it’s running<br>systemctl enable firewalld : run firewalld on startup<br>systemctl start/stop friewalld : run service itself<br>firewall-cmd — state : verify that it is indeed running</li><li>List all rules in firewalld <br>Answer: firewall-cmd --list-all</li><li>How to open a port in firewalld?<br>Answer: firewall-cmd --zone=public --permanent --add-port=8001/tcp &amp;&amp; firewall-cmd --reload</li></ul><p>firewalld is a really powerful tool — and you should use it if you want to know more, check out this <a href="https://www.digitalocean.com/community/tutorials/how-to-set-up-a-firewall-using-firewalld-on-centos-7">article</a>.</p><h4>Use the Security centre if you can</h4><p>Another thing after securing virtual machine internally we should set up some kind of monitoring of it, in Azure, for example, we can add to VM automatic security advisor, who analyzes operating system daily to determine issues that could make the VM vulnerable to attack. However, it isn’t a feature for Pay-As-You-Go subscription in Azure.</p><h4>Use NSG.</h4><p><strong>NSG is network-security-group, in the cloud environment, it works like </strong>IPTables<strong> .<br></strong>You can define in the specific things and ports which are open and open to where. <br>Like for example — open SSH only for owners of that VM, ideally they should have static IP (from.. IPs.. source port 22 to VirtualNetwork, port 22). The same goes for HTTP services and all services that are exposed to the internet.<br> Ideally SSH should be disabled and only enabled inside VNet but I think IP restriction is a fine filter, the same principle is for RDP and Telnet (default 23 port). Don’t open ports 22, 23 or 3389 to the open internet.</p><h4>Disk encryption</h4><p>All VM’s should have enabled disk encryption, which is self-explanatory I think.</p><h4>Stagnation is bad</h4><p>Often change SSH keys for storage accounts, keys to the storage account, passwords to the VM. We now have password generator, managers; do not be afraid to use them!</p><h4>Know what’s up</h4><p>You should have some kind of alerts for action (like Activity Log Alerts) in subscription to know when someone is changing/deleting f.e. NSG or what is crucial to your architecture. Monitoring of resources of individual machines is also a must, for example, properly configured Kibana or Nagios, or native supported monitoring via the cloud.</p><h4>Redundancy, replaceability</h4><p>All VM’s should be nothing more but only a gate to service and just calculating power. Data of that services should be on separate mounted data disks or storages. This is part of security too, making sure in case of disaster all you have to do is recreate VM, not the data itself.</p><h4>Disaster recovery</h4><p>In case all goes bad, you should have a plan for how to recreate infrastructure, it means regularly testing backups if they actually work and not only that they <strong>exist</strong>, but try to recover from them just for practice.</p><p>I think this is the most crucial points about basic, low-level security in the cloud. I hope you’ve learned something or just remind yourself that. In case of any thought about this topic, feel free to comment — I love discussions!</p><p>Cheers.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cffa0dd3e8e6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[GIT as a tool to ultimate democracy]]></title>
            <link>https://medium.com/@derodu/git-as-a-tool-to-ultimate-democracy-26c0af319dce?source=rss-d16fb9b65b74------2</link>
            <guid isPermaLink="false">https://medium.com/p/26c0af319dce</guid>
            <category><![CDATA[git]]></category>
            <category><![CDATA[democracy-and-rule-of-law]]></category>
            <category><![CDATA[politics]]></category>
            <category><![CDATA[philosophy]]></category>
            <category><![CDATA[ideas]]></category>
            <dc:creator><![CDATA[Michał Nerć]]></dc:creator>
            <pubDate>Thu, 14 Mar 2019 12:45:51 GMT</pubDate>
            <atom:updated>2019-03-14T14:34:11.259Z</atom:updated>
            <cc:license>https://creativecommons.org/licenses/by-nc-sa/4.0/</cc:license>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LK4ek90mS8En2ixtXaKcUA.jpeg" /><figcaption>img source: google images</figcaption></figure><p>During our brain-storming session of how to automate things in project, together with <a href="https://medium.com/u/a005e9f73864">Adam Semak</a> we’ve encountered the idea of ideal democracy.<br>I realize this is most likely an utopia idea, because of reasons like people mentality, attachment to tradition, getting used to to things like they are now.</p><p><strong>BUT!</strong></p><p>Please, bear with me and try to be open-minded.</p><h3>What is a GIT?</h3><p>GIT is a tool created by <a href="https://pl.wikipedia.org/wiki/Linus_Torvalds">Linus Torvalds</a> as a tool that allows developers to versioning their code of application.</p><p>It allows to have multiple version of application in so-called branches, <br>which are just a single human’s or a an idea’s version of interpretation of an application - usually they include some additional feature or bug fixing.</p><p>Common operations are <strong>pull </strong>and <strong>push</strong>. Pull - is just pulling most recent version of an app. Pushing is an operation designated to make changes in branch.</p><p>What if we instead of using word “<strong>application</strong>” we could use from now on “<strong>document of laws</strong>”?</p><p>What I mean by “document of laws” is f.e. the Constitution, the Penal Code etc. <br>What if our “<strong>master</strong>” branch would be just a document of “<strong>currently applicable law</strong>”?</p><h3>Why GIT is an ideal solution?</h3><p>Most people that I’ve met are lazy and with this solution they can be part of democratic country anywhere they want. <br>GIT is tested world-wide and it is used by essentially every company in the world.</p><p>Few rules that I think should be always true when we speak about law:</p><h4><strong>The law must be always transparent.</strong></h4><p>Git allows that via <strong>blame </strong>and <strong>history </strong>feature. We easily see <strong>who </strong>changes <strong>what</strong>, even single line.</p><h4><strong>Everyone should have possibility to openly present their idea of change to the law.</strong></h4><p>Git allows that via <strong>pull requests </strong>(let’s treat them as <strong>Petition</strong>) - every politician party, every organisation, basically everyone should have possibility to make a <strong>pull request</strong>, which is nothing more as a proposed change to current version of <strong>master </strong>branch, which is for reminded in our concept <strong>currently applicable law</strong>.</p><h4>Every change to the law should have minimal quantity of approval and can be debated on.</h4><p><strong>Pull requests</strong>, which are in our concept nothing else than <strong>Petition</strong>, have possibility to require minimal number of approval before it will be available to be accepted or more technical, <strong>merged</strong>. During that period every single line can be commented on, it shows who commented, comments can have replies.</p><h4><strong>Law should not be change too frequently to get people time to get familiar with it.</strong></h4><p>Every <strong>Petition (or technically speaking pull-request)</strong> should be merged at the of<strong> each quarter or each half-year</strong>. It can be done by f.e.<strong> Supreme Court</strong>.</p><h4><strong>Law should be announced to the public openly and globally.</strong></h4><p>It requires slightly more work, but it is doable. <strong>Master (or currently applicable law)</strong> should have <strong>hook</strong> which on every <strong>merge (or accept the petition)</strong> send proper information to people’s e-mail address (newsletter). <br>Details on this solution later on.</p><h3>Master - currently applicable law</h3><p>In this concept <strong>Master </strong>branch would be representing <strong>currently applicable law.</strong></p><p>What it means is if somebody wants to check what is the law in particular or general area all the person would have to do is just simple either <strong>pull </strong>or browse website.</p><p>It is simple, elegant solution that promotes open, people-friendly approach.</p><h3>Pull requests - people petitions to the law</h3><p>What does every petition require?<br>- minimum number of approval<br>- someone with idea</p><p>Well, it is pretty easy with <strong>git</strong>. It has a feature called <strong>pull request, </strong>which is nothing more than <strong>petition</strong> to <strong>merge (accept)</strong> changes to <strong>master (which is our currently applicable law).</strong></p><p>In order to <strong>accept/merge </strong>such <strong>petition/pull request </strong>people have to accept it, so it should have minimal number of approvals.</p><p>Git supports it.</p><p>Moreover - people can debate on it by writing comments to specific line in proposed law or generic comments to question an idea itself.</p><p>It looks something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MzzWcjVofsMGyRws4zcUKA.gif" /></figure><p>Imagine instead of code, commenting on each paragraph, section, article with easy way - by anyone willing to, with a history they did such a comment - <strong>no more denying by politicians </strong>that they did not said something, that they did. <br>Debates would be open to public, read at any-time instead of boring transmissions of votes that are fixed up previously by party leaders.</p><h3>Branches — ’cause every organisation, party, family and human must have possibility to speak.</h3><p>GIT has <strong>branches</strong> features, they are own interpretations of <strong>master/current applicable law </strong>- everyone, doesn’t matter if it’s single person, organisation, party or club should have possibility to openly present their ideas.</p><p>And in this solution, they can.</p><p>Each of them can create branch from master and create their own <strong>petition/pull request </strong>which contains <strong>exact change </strong>they want to make to particular paragraph of a section of an article.</p><p>No more general ideas - want to change something? Sure thing, please tell us - society - exactly what do you want to change.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/801/1*mWbys9ZZF9FgUcVLWWBNJw.png" /></figure><p>They can even propose or create <strong>pull request/petition </strong>to another person/organization branch instead purely debating on it.</p><h3>Voting - real power of the people or their representatives ?</h3><p>As mentioned above <strong>pull requests/petitions </strong>have possibility to have minimal number of approval.</p><p>But who will vote?</p><p>Well, it is a tough one. The way that I see it it can be either voting by people without government at all or as it is with representatives.</p><p>If everyone can vote, they should have authorized account — and mostly they do via trusted profiles confirmed by bank or go with personal id to police station or something like this. Then they could login to special platform, which contains all GIT repository with all proposed changes and people can vote on petition (similar as f.e. <a href="https://gopetition.com/">https://gopetition.com</a> works ).</p><p>Other solution is to stay as it is, where people’s representatives are voting, but if that’s the case platform should have only access from cut-off vpn/subnet from outside world to exclude possibility to interfering with votes.</p><p>They are both simple, elegant solution with pro’s/con’s.</p><h3>Accepting the petition/pull requests</h3><p>Well, after voting the next question popping up in head is - who will be accepting this changes?</p><p>Answer is simple: people who were elected to do so, Supreme Court with experts of <strong>petitions </strong>subject support.<br>Only members of the Supreme Court should have privileges to <strong>merge/accept </strong>proposed changes if <strong>pull request/petition </strong>have enough of approvals.</p><p>However, they should do it only on the end of <strong>each quarter or each half-year </strong>due to let people adapt to new changes and get familiar with it.</p><h3>Announcing the newly merged/accepted law</h3><p>The each new law should be announced to public. <br>It is possible via <strong>hook on merge </strong>functionality for <strong>master/current applicable law </strong>branch.</p><p>It should invoke simple newsletter and send SMS with short message what article has been changed.</p><p>SMS can be send using emergency system to all connected devices, and e-mail to all that have f.e. bank account - banks usually requires e-mail address and it can be synced up.</p><h3>Liability - everyone is accounted for their actions</h3><p>Thanks to git features like <strong>git blame and history </strong>everyone can be search for their history and changes. As well as proposed changes.</p><p>Politicians no longer could have tell the lie - people can have proof other than articles and misinformation in the internet.</p><h3><strong>Conclusion</strong></h3><p>Well, it is just an idea. A concept. <br>Sure it needs some tweaks, some bug-fixing, but it something interesting to think about it.</p><p>Thank you for reading and do not hesitate to comment.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=26c0af319dce" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Design patterns II: Strategy pattern]]></title>
            <link>https://medium.com/@derodu/design-patterns-ii-strategy-pattern-ad99ebabf08b?source=rss-d16fb9b65b74------2</link>
            <guid isPermaLink="false">https://medium.com/p/ad99ebabf08b</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[object-oriented]]></category>
            <dc:creator><![CDATA[Michał Nerć]]></dc:creator>
            <pubDate>Sun, 26 Nov 2017 02:25:12 GMT</pubDate>
            <atom:updated>2017-11-26T02:25:12.034Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>What is a Design Pattern?</strong></p><blockquote>It is a description or template for how to solve a problem that can be used in many different situations.</blockquote><p>Strategy pattern is used often when we have possibility to resolve a problem in many different ways depends on changing conditions.<br>To create strategy pattern we need : one global object that is wrapper for algorithm that decides which solution to use, and as many solutions that we want.<br>Good case is sorting: we have f.e. SortingStrategy with determines based on passed an Array as argument which sorting algorithm to use. We can have as many “plugin” sorting strategies as QuickSort , MergeSort, HeapSort etc. as we want. One may say that Strategy pattern is a variation of Adapter pattern . <br>The advantage of that solution is one place that we have all necessary logic and it is easy to maintain and change.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/531/1*1gzbGVIfG4EeYOWN5G_ZDw.png" /><figcaption>strategy pattern</figcaption></figure><p>A more real-case scenario for this pattern below. We have to determine which discount we can give to a user: if it is user birthday, black Friday or standard loyalty program.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/79cf5fa50d83380b8abfabf4619f91ef/href">https://medium.com/media/79cf5fa50d83380b8abfabf4619f91ef/href</a></iframe><p>As you can see we have one general DiscountStrategy and multiple plug-ins which are implementing DiscountAlgorithm interface thanks to that we make sure that each of discounts has more or less the same properties. <br>Then we check in DiscountStrategy which algorithm we should be using and return a result from that algorithm.</p><p>Example of use case:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/10db13f2a41db052d925c1a9e8ddf230/href">https://medium.com/media/10db13f2a41db052d925c1a9e8ddf230/href</a></iframe><p>We pass User object to DiscountStrategy and a price and depends on User.birthdayDate and also User.registrationDate we can get various results.</p><p>I think that is all to is to Strategy pattern. I hope you like it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ad99ebabf08b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Design patterns I: Singleton]]></title>
            <link>https://medium.com/@derodu/design-patterns-singleton-1b753aeee2d?source=rss-d16fb9b65b74------2</link>
            <guid isPermaLink="false">https://medium.com/p/1b753aeee2d</guid>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Michał Nerć]]></dc:creator>
            <pubDate>Sun, 26 Nov 2017 01:22:48 GMT</pubDate>
            <atom:updated>2017-11-26T02:27:51.711Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>What is Design Pattern?</strong></p><blockquote>It is a description or template for how to solve a problem that can be used in many different situations.</blockquote><p>Singleton is a pattern that needs to be used carefully.<br>In general, it allows us to allocate some instance of an object to a fixed part of programs memory. Thanks to that we can pass along the single state of an instance between multiple objects inside our program.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/316/1*y2XxbjHJsQa4O88VXgg-2Q.png" /><figcaption>singleton diagram</figcaption></figure><p>An example implementation of Singleton pattern in TypeScript may look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5c94ace9c99fa3065907446c5435ab96/href">https://medium.com/media/5c94ace9c99fa3065907446c5435ab96/href</a></iframe><p>Singleton class should have private static _instance property which holds an address to memory allocation of a created instance of an object. <br>Also is common best practice to have public static getInstance() method which role is pretty the same as constructor method: it returns and instance. <br>Method constructor should be somehow disabled or returns .getInstance() method, but it can lead to confusion: by new keyword, I’ve created the second instance or just got the first one that was already there?</p><p>Singleton is often classified as ananti-pattern because it can be easily over-used and leads to slower performance rather than improve it. <br>Another problem that it can introduce is in asynchronous apps. <br>When multiple concurrents objects in the same time trying to access Singleton object they can change its property in parallel which can cause to hard to find errors. <br>Also unit-tests can be a problem.</p><p>In summary it should be used with causion. <br>I think this is covering up Singleton pattern, one of a basic few. <br>Thanks for reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1b753aeee2d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to become a better programmer ?]]></title>
            <link>https://medium.com/swlh/design-patterns-kiss-dry-tda-yagni-soc-828c112b89ee?source=rss-d16fb9b65b74------2</link>
            <guid isPermaLink="false">https://medium.com/p/828c112b89ee</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[design-principles]]></category>
            <category><![CDATA[code-quality]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Michał Nerć]]></dc:creator>
            <pubDate>Sat, 25 Nov 2017 00:52:39 GMT</pubDate>
            <atom:updated>2020-06-23T08:24:30.666Z</atom:updated>
            <content:encoded><![CDATA[<h3>Design principles I : kiss, dry, tda, soc, yagni</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y2ULNDQK6jlUJkOfGa5obw.jpeg" /></figure><p>Part 2:<br>- <a href="https://medium.com/@derodu/how-to-become-even-better-programmer-7f9783b859af">https://medium.com/@derodu/how-to-become-even-better-programmer-7f9783b859af</a></p><p>When I started programming I was happy that my program was compiling and was working as I expected it to work, but as I wrote more and more code over time I’ve started to appreciate design patterns.</p><p>Design patterns not only make my code better, more readable and easier to maintain, but also save me a lot, and I mean A LOT of debugging hours. <br>That is why I wanted to share some with you.</p><p>This design patterns originated from so called “gang of four”, authors of a “<a href="http://c2.com/cgi/wiki?DesignPatternsBook">DesignPatterns Book</a>”. They introduced this principles that are extremely useful especially in object-oriented programming. <br>Probably you are already using all that, but it is always good to refresh your knowledge.</p><p>All code examples are in TypeScript.</p><h3><strong>KISS : Keep it simple stupid</strong></h3><p>The main concept of this pattern is to keep as simple code as possible. <br>That means each method, class, interface should be names as clear as possible and also logic inside functions, method etc. should be clear and simple as it can be.</p><p>Example of how KISS <strong>does NOT </strong>look like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fc2267ad0b4df53b921d18af28612e87/href">https://medium.com/media/fc2267ad0b4df53b921d18af28612e87/href</a></iframe><p>In this example we have code that is telling us nothing. <br>Class name, methods name are not written properly. <br>Body of a method is a mess with a lot of if and not maintainable.</p><p>After using <strong>KISS </strong>principle, it <strong>does </strong>look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/04c04d9d4d1c04939b5ad9cd4e7d3beb/href">https://medium.com/media/04c04d9d4d1c04939b5ad9cd4e7d3beb/href</a></iframe><p>As you can in above code there is KISS principle. <br>This is scalable solution: we can have multiple countries and add new discount region with ease only modified a discountRegions property in a country class. <br>Thanks to the interface we can also make sure that each new country have the required properties. <br>Payment class has also methods that are named after what they do and thanks to that structure we optimised code to have only one if.</p><p>And that is kiss: clean, simple code.</p><h3><strong>DRY : Do not repeat yourself</strong></h3><p>This concept is advising us to divide code that does the same thing to small parts. <br>Sometimes we have multiple lines of code basically doing the same: like filter by array with specified criteria, adding some things to object etc. <br>Usually good practice is to get rid of it.</p><p>Example of <strong>not good DRY code is</strong>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8469c6b6037134f013ba531538e2c350/href">https://medium.com/media/8469c6b6037134f013ba531538e2c350/href</a></iframe><p>In this example we have multiple added days with basically the same code to the class. We can avoid that by creating a method that is doing for that. Also with manually typing day name multiple times we are extending possibility of an error.</p><p>Example of proper class <strong>with good DRY code</strong>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9c9aa780fb7bfb9becc93c733dc74da9/href">https://medium.com/media/9c9aa780fb7bfb9becc93c733dc74da9/href</a></iframe><p>In this example instead of typing manually each day we have implement enum with predefined day names and also introduced Day class. Thanks to that we can extend it to add more features to this class in the future, like getDaylightTime . Also we’ve implement addDay method to Week class which are doing pretty the same thing, but now if anything changes we have to update only one place in code instead of seven.</p><p>That is a <strong>DRY </strong>principle.</p><h3>TDA: Tell don’t ask</h3><p>This principle suggest that we should write code in a way that object behave rather then in what state they are in. <br>This can avoid unnecessary dependencies between classes and thanks to that have more maintainable code. It is strongly related to code encapsulation.</p><p>Example of code with <strong>no TDA </strong>principle:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e79faa70b5ee1a997476015a02a2a7d8/href">https://medium.com/media/e79faa70b5ee1a997476015a02a2a7d8/href</a></iframe><p>As we can see UserService access many times to User object properties, especially when updating User.tokens what if will we have that in many parts of our program and will want to change logic <strong>how </strong>it works?<br>Also take a look at validators: all logic how it should behave is inside a method, but we should make it more scalable and reusable. <br>Below is an example how to do it.</p><p>Example <strong>with TDA</strong>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/11f243d318b397a98b8b340a996b96c1/href">https://medium.com/media/11f243d318b397a98b8b340a996b96c1/href</a></iframe><p>At first sight it may seems like there is over-complexity and more code that is the need to be.<br>However, in a long shot thanks of a encapsulated and independent validator we can use it many times in many generic situations. <br>Properties of User class are only used inside of it, UserService is calling up level method to access it. Thanks to that we have all logic in one place, so when we will want to use User class somewhere else, program will behave as we expect it.</p><h3>SoC: Separation of Concerns</h3><p>This principle is telling us to separate responsibility of a single class to this class and this class only. Objects should not share what they do. <br>Each class should be unique and separated from the rest.</p><p>Example of code <strong>without SoC</strong>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f93b4a8aa4c80591528c11d0a4a53e3e/href">https://medium.com/media/f93b4a8aa4c80591528c11d0a4a53e3e/href</a></iframe><p>We have AccountService that is responsible for multiple things: logging, validating and operation of users balance. Also TDA is not implemented. <br>We should separate validation and create external logger to use in future in other modules.</p><p>Example of <strong>proper SoC</strong>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a0d311f41b35210552f569b9a9095b40/href">https://medium.com/media/a0d311f41b35210552f569b9a9095b40/href</a></iframe><p>We now have separate state and functionality of each class: Validators, User, AcocuntService and LoggerService.<br>Thanks to SoC we can use this separately in many different modules in our application. <br>Also, that code is easier to maintain, because of fewer places that logic exists.</p><h3>YAGNI: You ain’t gonna need it</h3><p>That principle is not telling us how to do something in code directly, but rather how to code effectively. <br>In general it says that we should code only things that are required from us in this particular moment. <br>For example: when we will have to do validation of email and password field, we shouldn’t do validation of name, because we may never need it. <br>It is really as TDD : we write test only for micro feature and write minimal code required to work on that. <br>`YAGNI` is trying to save us time and focus on most important things in our sprint.</p><h3>That’s all folks.</h3><p>I hope that thanks to that article you learnt something or remind some things you already know. :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=828c112b89ee" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/design-patterns-kiss-dry-tda-yagni-soc-828c112b89ee">How to become a better programmer ?</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>