<?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 Talysson de Oliveira on Medium]]></title>
        <description><![CDATA[Stories by Talysson de Oliveira on Medium]]></description>
        <link>https://medium.com/@talyssonoc?source=rss-b65d1410fd8b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*C9uBT9_kl7kpSOzU.jpg</url>
            <title>Stories by Talysson de Oliveira on Medium</title>
            <link>https://medium.com/@talyssonoc?source=rss-b65d1410fd8b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 08:54:13 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@talyssonoc/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[Scalable Frontend #2 — Common Patterns]]></title>
            <link>https://medium.com/codeminer-42/scalable-frontend-2-common-patterns-d2f28aef0714?source=rss-b65d1410fd8b------2</link>
            <guid isPermaLink="false">https://medium.com/p/d2f28aef0714</guid>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[clean-architecture]]></category>
            <category><![CDATA[software-architecture]]></category>
            <dc:creator><![CDATA[Talysson de Oliveira]]></dc:creator>
            <pubDate>Thu, 22 Nov 2018 13:48:44 GMT</pubDate>
            <atom:updated>2019-05-21T18:17:15.613Z</atom:updated>
            <content:encoded><![CDATA[<h3>Scalable Frontend #2 — Common Patterns</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XuTr3RoTWHcQH9AdqDycXQ.jpeg" /><figcaption>Patterns should fit nicely, like playing blocks</figcaption></figure><blockquote><em>This post is part of the Scalable Frontend series, you can see the other parts here: “</em><a href="https://blog.codeminer42.com/scalable-frontend-1-architecture-9b80a16b8ec7"><em>#1 — Architecture</em></a><em>” and “</em><a href="https://blog.codeminer42.com/scalable-frontend-3-the-state-layer-b23ed69ca57c"><em>#3 — The State Layer</em></a><em>”.</em></blockquote><p>Let’s continue our conversation about frontend scalability! In the last post, we discussed architecture fundamentals in frontend applications, but only conceptually. Now we’re going to get our hands dirty with actual code.</p><h3>Common patterns</h3><p>How do we implement architecture as mentioned in the first post? What’s different compared to what we’re used to do? How can we combine all of that with dependency injection?</p><p>There are recurring patterns in frontend applications, no matter what library you’re using to abstract the view or to manage the state. Here we’re going to talk about some of them, so buckle up your seatbelt!</p><h3>Use cases</h3><p>We chose <em>use cases </em>as the first pattern because architecture-wise they are the means by which we interact with our software. Use cases tell what our application does at a high-level; they are the recipes for our features; the main units of the application layer. They define the application itself.</p><p>Also often called <em>interactors</em>, the use cases hold the responsibility of performing the interaction between the other layers. They:</p><ul><li>Are called by the input layer,</li><li>Apply their algorithm,</li><li>Make the domain and infrastructure layers interact without caring about how they work internally, and,</li><li>Hand the result status back to the input layer. The result status indicates whether the use case was successful or failed because of an internal error, a failed validation, a pre-condition, etc.</li></ul><p>Knowing the result status is useful because it helps to determine what action to emit for an outcome, thus allowing for richer messages in the UI, so that the user knows what went wrong in a failure situation. But there’s an important detail: the logic for the result status should be inside the use case, not the input layer — since it’s not the input layer’s responsibility to know that. It means the input layer should <em>not</em> receive a generic error object from the use case and resort to if statements to find out the reason of the failure — like checking an error.message attribute or instanceof to query the class of the error.</p><p>Which takes us to the tricky fact: returning promises from use cases might not be the best design decision because promises only have two possible outcomes: success and failure, requiring us to resort to conditionals to discover the reason of the failures inside catch() statements. Does it mean we should skip promises in our software? No! It is totally OK to return promises from other parts of our code, like actions, repositories, and services, as long as the input layer remains ignorant about that. A simple way to overcome this limitation is to have a callback for each possible result status of the use case.</p><p>Another important characteristic of use cases is that they should respect the boundaries between layers by not knowing what entry point is calling them, even in the frontend where there’s a single entry point. It means that we should not touch browser globals, DOM-specific values, or any other low-level object inside the use cases. For example: we should not receive an instance of an &lt;input /&gt; element as a parameter and then read its value; the input layer should be the one responsible for extracting out this value and passing it to the use case.</p><p>Nothing better to make a concept explicit than an example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3a92b30b2b00453d90f37e06996513c2/href">https://medium.com/media/3a92b30b2b00453d90f37e06996513c2/href</a></iframe><p>Notice that in userAction, we don’t make any assertion over the response of the createUser use case; we trust that the use case will call the correct callback for each result. Also, even though the values inside the userData object come from HTML inputs, the use case doesn’t know anything about that. It just receives the extracted data and passes it forward.</p><p>That’s it! The use cases shouldn’t do more than that. Can you see how easy it is to test them now? We can simply inject mock dependencies that behave as we want, and test if our use cases call the correct callback for each situation.</p><h3>Entities, value objects, and aggregates</h3><p>Entities are the core of our domain layer: they represent the concepts that our software deals with. Say we’re building a blog engine application; in that case, we’ll probably have a User entity, an Article entity, and even a Comment entity if our engine allows so. Entities are therefore simply objects that hold the data and the behavior of these concepts, without taking the technology into consideration. Entities shouldn’t be seen as models or implementations of the Active Record design pattern; they don’t know anything about databases, AJAX, or persistence at all. They just represent the concept and the business rules around that concept.</p><p>So, for example, if a user of our blog engine has age restrictions when commenting on an article about violence, we would have a user.isMajor() method that would be called inside article.canBeCommentedBy(user), in such a way as to keep the rule for age classification inside the user object and the rule for age restriction inside the article object. The AddCommentToArticle use case would be the one to pass the user instance to article.canBeCommentedBy, and the use case would be the one to perform the <em>interaction</em> between them.</p><p>There’s a way to identify if something is an entity in your codebase: if an object represents a domain concept and it has an <em>identifier</em> attribute (an id, a slug or a document number, for example,) it <em>is</em> an entity. The existence of this identifier is important because it is what differentiates an entity from a value object.</p><p>While the entities have an identifier attribute, the value objects have their identities defined by the value of all its attributes combined. Confusing? Think about a color object. When representing a color with an object, we usually don’t give this object an id; we give it values of red, green and blue, and it’s these three attributes combined that identify this object. If we change the value of the red attribute, we can now say that it represents another color, but the same doesn’t happen with a user identified by an id. If we change the value of the name attribute of a user but keep the same id, we say it’s still the same user, right?</p><p>At the beginning of this section, we said that it’s common to have methods within the entities with the business rules and behaviors for that given entity. But in the frontend, it’s not always possible or good to have business rules as methods of entity objects. Think about functional programming: we don’t have instance methods, or this, or mutability — and it&#39;s a paradigm that plays very well with the one-way data-flow using plain JavaScript objects instead of instances of custom classes. Does it make sense to have methods in the entities when using functional programming then? Certainly no. So how do we create entities with such limitations? We go by the functional way!</p><p>Instead of having a User class with a user.isMajor() instance method, we’ll have a User <em>module </em>with a named export called isMajor(user), which takes an object with user attributes and treats it as if it was the this from a User class. The argument doesn’t need to be an instance of a specific class, provided that it has the same attributes a user would have. This is important: the attributes (which are the expected arguments for the User entity) should be formalized somehow. You can do it in pure JavaScript with factory functions or more explicitly using <a href="https://flow.org/">Flow</a> or <a href="https://www.typescriptlang.org/">TypeScript</a>.</p><p>Shall we see a <em>before</em> and <em>after</em> to make it easier to understand?</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/88d14af57b56a40222bbc13eb0616d0a/href">https://medium.com/media/88d14af57b56a40222bbc13eb0616d0a/href</a></iframe><p>When dealing with state managers like Redux, the easier you can make to favor immutability the better, so not being able to <em>spread</em> objects to create shallow copies is not a good thing. Using the functional approach will enforce decoupling and we’ll still be able to spread objects.</p><p>All these rules apply to value objects, but they also have another importance: they help make our entities less bloated. It’s common to have a lot of attributes not directly related to each other in entities, which may be a sign that we can extract some of them to value objects. For example, let’s say we have a Chair entity with id, cushionType, cushionColor, legsCount, legsColor, and legsMaterial. Notice that cushionType and cushionColor are not related to legsCount, legsColor, or legsMaterial, so after extracting some value objects, our chair would be reduced to three attributes: id, cushion and legs. Now we can continue adding attributes to cushion and legs without making the chair even more bloated.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/213/1*2VikCQmpB6mHcP-NTinb-Q.png" /><figcaption>Before extracting value objects</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9lNN8CTLqz_mrvLO1-ivnA.png" /><figcaption>After extracting value objects</figcaption></figure><p>But just extracting value objects from an entity won’t always be enough. You’ll notice that, more often than not, there will be entities associated with secondary entities where the main concept is represented by the first entity, which depend on these secondary entities to be a <em>whole</em>, and that the existence of these secondary entities alone doesn’t make sense. There’s certainly some confusion in your head right now, so let’s clear it out.</p><p>Think about a shopping cart. A shopping cart can be represented by a Cart entity, which will be composed of line items, which in turn are also entities, since they have their own ids. Line items should only be interacted with through the main entity, the cart object. Want to know if a given product is inside the cart? Call the cart.hasProduct(product) method instead of reaching out to the lineItems attribute directly like cart.lineItems.find(...). This kind of relationship between objects is called an <em>aggregate</em>, and the main entity of the given aggregate (in this case, the cart object) is called the <em>aggregate root. </em>The entity that represents the concept of the aggregate and all of its components can only be accessed through the cart, but it&#39;s OK for the entities inside the aggregate to reference objects from the outside. We can even say that, in cases where a single entity alone is able to represent a whole concept, that entity is also an aggregate composed of a single entity and its value objects, if any. So when we say “aggregate”, from now on you must interpret it as proper aggregates and single-entity aggregates as well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/973/1*mi2o5vB42A1kV3YmbkRAAQ.png" /><figcaption>There’s no access from the outside to the internal entities of the aggregate, but the secondary entities can access things from outside of the aggregate, like the products</figcaption></figure><p>Having entities, aggregates, and value objects well-defined in our codebase and named after how the domain experts refer to them can be very valuable (no pun intended). So always pay attention to whether something can be abstracted with them before throwing the code somewhere else. Also, be sure to understand entities and aggregates because it’s going to be useful for the next pattern!</p><h3>Repositories</h3><p>Did you notice we didn’t talk about persistence yet? It’s important to think about it because it enforces something that we spoke since the beginning: persistence is an implementation detail, a secondary concern. It doesn’t matter where you persist stuff in your software, as long as the part responsible for handling it is reasonably encapsulated and doesn’t affect the rest of your code. In most layer-based architectures, this is the responsibility of the <a href="https://martinfowler.com/eaaCatalog/repository.html"><em>repository</em></a>, which lives inside the infrastructure layer.</p><p>Repositories are objects used to persist and read entities, so they should implement methods that make them <em>feel</em> like collections. If you have an article object and you want to persist it, you’ll probably have an ArticleRepository with an add(article) method which takes the article as a parameter, persists it <em>somewhere</em>, and then returns an article copy with additional persisted-only attributes like the <em>id</em>.</p><p>I said that we would have an ArticleRepository, but how do we persist other objects? Should we have a different repository to persist users? How many repositories should we have, and how granular should they be? Calm down there, the rule is not hard to grasp. Do you recall aggregates? That’s where we cut off the line. The rule of thumb is having a repository for each <em>aggregate</em> of your codebase. We can also create repositories for secondary entities, but only if needed.</p><p>Ok, ok, it sounds a lot like backend talk. What do repositories do in the frontend then? We don’t have databases in there! And here’s the catch: stop associating repositories with databases. Repositories are about <em>persistence</em> as a whole, and not only about databases. In the frontend, repositories deal with data sources such as HTTP APIs, LocalStorage, IndexedDB and so on. In the previous example, our ArticleRepository#add method takes an Article entity as input, converts it to the JSON format the API expects, makes an AJAX call to the API, and then maps the JSON response back to an instance of the Article entity.</p><p>It’s nice to notice that, for example, if the API is still in development, we can emulate it by implementing an ArticleRepository called LocalStorageArticleRepository, which interacts with the LocalStorage instead of the API. When the API is ready, we then create another implementation called AjaxArticleRepository, thus replacing the LocalStorage implementation — so long as both of them share the same <em>interface</em> and are injected with a generic name that doesn&#39;t reveal the underlying technology, like articleRepository.</p><p>We use the term <a href="https://en.wikipedia.org/wiki/Protocol_(object-oriented_programming)"><em>interface</em></a> here as to represent the set of methods and attributes that an object should implement, so don’t confuse it with graphic user interfaces (a.k.a. GUIs). If you’re using pure JavaScript, the interfaces will be only conceptual; they’ll be imaginary, since the language doesn’t support explicit declaration of interfaces, but they can be explicit if you’re using <a href="https://www.typescriptlang.org/docs/handbook/interfaces.html">TypeScript</a> or <a href="https://flow.org/en/docs/types/interfaces/">Flow</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/1*YLxmpXnoHy3RKMMWgssZUQ.png" /></figure><h3>Services</h3><p>This one is not the last pattern just for a coincidence. It is here precisely because it should be seen as the “last resource”. When you can’t fit a concept in any of the previous patterns, only then should you consider creating a service. It is very common to see codebases where any piece of reusable code is thrown in a so-called “service object”, which is nothing but a bucket of reusable logic with no encapsulated concept. Always be aware of that and don’t let this happen in your codebase, and resist the urge to create services instead of use cases because they are not the same thing.</p><p>In short: services are objects that implement procedures which don’t fit in your domain objects. For example, payment gateways.</p><p>Let’s imagine for a second that we’re building an e-commerce and we need to interact with an external API of the payment gateway to fetch the authorization token of a purchase. The payment gateway isn’t a domain concept, so it’s a perfect fit for a PaymentService. Add methods to it that won’t reveal technology details such as the format of the API response, and then you have a generic object to perform the interaction between your software and the payment gateway, nicely encapsulated.</p><p>And that’s it, no secret here. Try to fit your domain concepts in the aforementioned patterns, and if they don’t work, only then consider a service. It counts for all the layers of your codebase!</p><h3>File organization</h3><p>Many developers misunderstand the difference between architecture and file organization, thinking that the latter defines the architecture of an application. Or even that with good organization, the application will scale well, which is totally misleading. Even with the most perfect file organization, you can still have performance and maintainability issues through your code base, so there’s the last topic of this post. Let’s demystify what organization really is, and how we can use it in conjunction with architecture to achieve a readable and maintainable project structure.</p><p>Basically, organization is how you visually separate the parts of your app, while architecture is how you separate it <em>conceptually</em>. You can perfectly well keep the same architecture and still have multiple options to choose from when picking an organization scheme. It’s a good idea, however, to organize your files as to reflect the layers of your architecture and favor the readers of your codebase, so that they understand what happens just by looking at the file tree.</p><p>There is no perfect file organization, so choose wisely according to your taste and needs. There are two approaches, however, particularly useful to highlight the layers discussed in this article. Let’s see each of them.</p><p>The first one is the most simple and consists in dividing the root of the src folder in layers, and then in the concepts of your architecture. For example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a8ddcdb177b45528f4ee4ffa7a94557e/href">https://medium.com/media/a8ddcdb177b45528f4ee4ffa7a94557e/href</a></iframe><p>It’s very common to see folders like components, containers, reducers, actions, and so on, when working with React and Redux using this kind of organization. We preferred to go one step further and group similar responsibilities within the same folder. For example, our components and containers will all be inside the view folder, and the actions and reducers will be inside the store folder because they follow the rule of gathering together the things that change for the same reason. The following are the standing points of this organization:</p><ul><li>You should <em>not</em> have folders to reflect technical roles like “controllers”, “components”, “helpers” and so on;</li><li>Entities live inside the domain/&lt;concept&gt;folder, where “concept” is the name of the aggregate in which the entity lives, and is exported through the domain/&lt;concept&gt;/index.js file;</li><li>When a unit may fit in two different concepts, choose the one where the given unit wouldn’t exist if the concept didn’t exist;</li><li>It’s OK to import files between concepts of the same layer, as long as it doesn’t cause coupling.</li></ul><p>Our second option consists in separating the root of the src folder by <em>features</em>. Let’s say we are dealing with articles and users; in that case, we will have two feature folders to organize them, and then a third folder for common things like a generic Button component, or even a feature folder only for UI components:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ee87f6e1198ddd5c2137b939a4131cbd/href">https://medium.com/media/ee87f6e1198ddd5c2137b939a4131cbd/href</a></iframe><p>The standing points of this organization are basically the same as the first one. For both, you should keep the dependencies container in the root of the src folder.</p><p>Again, these options may not fit your needs, and therefore might not be the perfect organization for you. So take the time to play and move files and folders around until you achieve a result that makes it easier to find the artifacts you need. This is the best way to find out what works better for your team. And be aware that just separating code into folders won’t make your application easier to maintain! You got to keep the same mindset while separating the responsibilities within your code.</p><h3>Coming next</h3><p>Wow! Quite a few content, right? It’s OK, we spoke about a lot of patterns here, so don’t push yourself to understand all of this in a single read. Feel free to re-read and check the first post of the series and our examples until you feel more comfortable with the outline of the architecture and its implementation.</p><p>In the next post, we’ll also talk about practical examples, but focusing totally in state management.</p><p>In case you want to see a real implementation of this architecture, check out the code for this <a href="https://github.com/talyssonoc/react-redux-ddd">example blog engine application</a>. Remember that nothing is written in stone, and that there will be patterns we’re still to talk about in the upcoming posts.</p><h3>Recommended links</h3><ul><li><a href="https://www.youtube.com/watch?v=US8QG9I1XW0&amp;feature=youtu.be">Mark Seemann — Functional architecture — The pits of success</a></li><li><a href="https://www.youtube.com/watch?v=srQt1NAHYC0">Scott Wlaschin — Functional Design Patterns</a></li></ul><p>Written by <a href="https://medium.com/u/b65d1410fd8b">Talysson de Oliveira</a> and <a href="https://medium.com/u/56076e80e075">Iago Dahlem Lorensini</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d2f28aef0714" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codeminer-42/scalable-frontend-2-common-patterns-d2f28aef0714">Scalable Frontend #2 — Common Patterns</a> was originally published in <a href="https://medium.com/codeminer-42">The Miners</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Scalable Frontend #1 — Architecture Fundamentals]]></title>
            <link>https://medium.com/codeminer-42/scalable-frontend-1-architecture-9b80a16b8ec7?source=rss-b65d1410fd8b------2</link>
            <guid isPermaLink="false">https://medium.com/p/9b80a16b8ec7</guid>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Talysson de Oliveira]]></dc:creator>
            <pubDate>Mon, 22 Oct 2018 13:16:14 GMT</pubDate>
            <atom:updated>2019-05-21T18:15:51.610Z</atom:updated>
            <content:encoded><![CDATA[<h3>Scalable Frontend #1 — Architecture Fundamentals</h3><h4>How can your frontend benefit from software architecture?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aqmGPSkQtyFUd-c3vUF_AQ.jpeg" /></figure><blockquote><em>This post is part of the Scalable Frontend series, you can see the other parts here: “</em><a href="https://blog.codeminer42.com/scalable-frontend-2-common-patterns-d2f28aef0714"><em>#2 — Common Patterns</em></a><em>” and “</em><a href="https://blog.codeminer42.com/scalable-frontend-3-the-state-layer-b23ed69ca57c"><em>#3 — The State Layer</em></a><em>”.</em></blockquote><p>The two most common meanings of the word scalability regarding software development are related to the performance and the maintainability of the codebase over time. You can have both of them, but focusing on good maintainability will make it easier to tweak the performance without affecting the rest of the application. Even more<strong> </strong>so on the frontend, where we have an important difference from the backend: the local state.</p><p>In this series of posts, we’re going to talk about how to develop and maintain a scalable frontend application with real-life tested approaches. Most of our examples will use React and Redux, but we’ll compare it often with other tech stacks to show how you can achieve the same results. Let’s begin the series talking about architecture, the most important part of your software.</p><h3>What is software architecture?</h3><p>What is architecture anyway? It seems pretentious to say that architecture is the most important part of your software, but bear with me.</p><p>Architecture is how you make the units of your software interact with each other to highlight the most important decisions you have to make and postpone the secondary decisions and implementation details. Designing the architecture of a software means separating the actual application from its supporting technologies. Your <em>actual</em> application doesn’t know about databases, AJAX requests, or the GUI; instead, it’s composed of use cases and domain units representing the concepts covered by your software, regardless of the actors that execute the use cases or where the data is persisted.</p><p>There’s also something important to talk about regarding architecture: it doesn’t mean file organization, and it’s not how you name files and folders.</p><h3>Layers in frontend development</h3><p>One way to separate what is important from what is secondary is by using layers, each with a different and specific set of responsibilities. A common approach in a layer-based architecture is to separate it into four layers: application, domain, infrastructure, and input. These four layers are better explained in another post, <a href="https://blog.codeminer42.com/nodejs-and-good-practices-354e7d763626">NodeJS and Good Practices</a>. We recommend you read the first part of the post about them before continuing. You don’t have to read the second part since it’s specific to NodeJS.</p><p>The domain and application layers aren’t that different between the frontend and the backend since they’re technology agnostic, but we can’t say the same about the input and the infrastructure layers. In a web browser, it’s common to have a single actor in the input layer, the view, so we can even call it <em>the view layer</em>. Also, the frontend doesn’t have access to a database or a queue engine, so we won’t find these in our frontend infrastructure layer. What we will find, instead, are abstractions that encapsulate AJAX requests, browser cookies, the LocalStorage, or even units that interact with WebSocket servers. The main difference is only what is being <em>abstracted</em>, so you can even have frontend and backend <a href="https://martinfowler.com/eaaCatalog/repository.html">repositories</a> with exactly the same interface but a different technology underneath. Can you see how awesome a good abstraction can be?</p><p>It doesn’t matter if you’re using React, Vue, Angular or any other tool to create your view. It’s important to follow the input layer rule of not having any logic, therefore delegating the input parameters to the next layer. With regards to a frontend layer-based architecture, there’s another important rule: to keep the input/view layer always in sync with the local state, you should follow the one-way data-flow. Does this term sound familiar? We can do it by adding a fifth layer specifically for that: the state, also known as <em>the store</em>.</p><h3>The State layer</h3><p>When following the one-way data-flow, we never change nor mutate the data received by a view directly inside the view. Instead, we dispatch what we call “actions” from the views. It goes like this: an action sends a message to the source of the data, the source updates itself, and then re-renders the view with the new data. Notice that there’s never a direct channel from the view to the store, so if two sub-views use the same data, you can dispatch the action from any of them and this will cause both to be re-rendered with the new data. It may seem that I’m talking specifically about React and Redux, but it’s not the case; you can achieve the same results with almost every modern frontend framework or library, like React + <a href="https://reactjs.org/docs/context.html">context API</a>, Vue + <a href="https://vuex.vuejs.org/">Vuex</a>, Angular + <a href="https://ngxs.gitbook.io/">NGXS</a>, or even Ember using the data-down action-up approach (a.k.a. DDAU). You can even do it with jQuery using its event system to send actions up!</p><p>This layer is responsible for managing the local and constantly-changing state of your frontend, like the data that’s been fetched from the backend, temporary data created in the frontend and not yet persisted, or transient info like the status of a request. In case you’re wondering, that’s the layer where the actions and their handlers responsible for updating the state live.</p><p>Even though it’s common to see codebases with business rules and use case definitions directly inside actions, if you read carefully the description of the other layers, you’ll see that we already have a place to put our use cases and business rules, and it’s <em>not</em> the state layer. Does it mean that our actions are use cases now? No! So how should we treat them?</p><p>Let’s think for a moment… we said that actions are not use cases and that we already have a layer to put our use cases. The views should dispatch actions, which take the info coming from the view, hand it to the use cases, dispatch new actions based on the response, and finally update the state — which updates the view and closes the one-way data-flow. Don’t the actions sound like controllers now? Aren’t they a place to take params from the view, delegate away to the use case, and respond based on the result of the use case? That’s <em>exactly</em> how you should treat them. No complex logic or direct AJAX calls should go in there, for these are the responsibilities of another layer. The state layer should know only how to manage the local storage, and that’s all.</p><p>There’s another important factor in play. Since the state layer manages the local storage consumed by the view layer, you’ll notice that these two are coupled in some way. There will be some data in the state layer only for the view, like a boolean flag that says if a request is still pending so that the view can display a spinner, and that’s totally OK. Don’t beat yourself up over that, you don’t need to overgeneralize the state layer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Oxg6DPhED09WGfWa8lcx3Q.png" /></figure><h3>Dependency injection</h3><p>OK, layers are cool, but how do they talk to each other? How do we make a layer rely on another without coupling them? Is it possible to test all the possible outputs of an action without executing the use case it delegates to? Is it possible to test a use case without triggering an AJAX call? For sure it is, and we can do this with dependency injection.</p><p>Dependency injection is a technique which consists in receiving the coupling dependencies of a unity as a parameter during the creation of that unity. For example, receiving the dependencies of a class in its constructor, or using React/Redux to connect a component to the store and inject the required data and actions as props. The theory isn’t complicated, right? The practice shouldn’t be as well, so let’s use a React/Redux application as an example.</p><p>We just said that using React/Redux’s connect is a way to achieve dependency injection between the view and the state layer and that&#39;s as straightforward as it gets. But we also said before that the actions delegate the business logic to the use cases, so how do we inject the use cases (application layer) into the actions (state layer)?</p><p>Let’s imagine for a second that you have an object that contains a method for each use case of your application. This object is commonly known as <em>dependency container</em>. Yeah, it seems weird and that it won’t scale well, but it doesn’t mean the implementation of the use cases are inside this object. These are just methods that delegate to the use cases, which are defined somewhere else. It’s way better to have a single object with all the use cases of your application than having them spread throughout your codebase, making them really difficult to find. With this object at hand, all we need to do is inject it into the actions and let each of them decide what use case will be be triggered, right?</p><p>If you’re using redux-thunk, it’s really simple to achieve it with the <a href="https://github.com/reduxjs/redux-thunk/#injecting-a-custom-argument">withExtraArgument</a> method, which allows you to inject the container in every thunk action as the third parameter after getState. The approach should be as easy if you’re using redux-saga, where we pass the container as the second parameter of the run method. If you’re using <a href="https://guides.emberjs.com/v3.3.0/applications/dependency-injection/">Ember</a> or <a href="https://ngxs.gitbook.io/ngxs/getting-started/why#dependency-injection-di">Angular</a> , the built-in dependency injection machinery should suffice.</p><p>Doing that will decouple the actions from the use cases because you won’t need to import the use cases manually in each file where you define an action. Moreover, testing the action separately from the use case is now pretty simple: simply inject a fake use case implementation which behaves exactly the way you want. Do you want to test what action will be dispatched if the use case fails? Inject a mock use case that always fails, then test how the action responds to that. No need to think about how the actual use case works.</p><p>Great, we have the state layer injected into the view layer, and the application layer injected into the state layer. What about the rest? How do we inject dependencies into the use cases to build the <em>dependency container</em>? That’s an important question and there are a lot of ways to do it. First of all, don’t forget to check if the framework you’re using has dependency injection built-in, like Angular or Ember. If it does, you shouldn’t build your own. If it doesn’t, you can do it in two ways: either manually or with a little help from a package.</p><p>Doing it manually should be straightforward:</p><ul><li>Define your units as classes or closures,</li><li>Instantiate the ones that have no dependencies first,</li><li>Instantiate the ones that depend on them, passing them as parameters,</li><li>Repeat until you have all the use cases instantiated,</li><li>Export them.</li></ul><p>Too abstract? Take a look at a few code examples:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0320d3933d2215ec2fd9df05156b29b7/href">https://medium.com/media/0320d3933d2215ec2fd9df05156b29b7/href</a></iframe><p>You’ll notice that the important part, the use cases, are instantiated at the end of the file and are the only objects being exported because they will be injected into the actions. The rest of your code doesn’t need to know about how the repository is created and how it works. It’s not important and it’s just a technical detail. For the use case, it doesn’t matter if the repository sends an AJAX request or persists something in the LocalStorage; it’s not the use case’s responsibility to know it. If you want to use the LocalStorage while your API is still in development, and then switch to use calls over the wire to an API, you won’t need to change the use case as long as the code that interacts with the API follows the same <em>interface</em> as the one that interacts with the LocalStorage.</p><p>You can get pretty far doing the injection manually as described above, even if you have dozens of use cases, repositories, services, and so on. If it gets too messy to build all your dependencies though, you can always use a dependency injection package, as long as it doesn’t increase the coupling.</p><p>A rule of thumb to test if your DI package is good enough is to check if moving from the manual approach to using the library doesn’t require touching more than the container code. If it does, the package is too intrusive and you should choose a different one. If you really want to use a package, we recommend <a href="https://www.npmjs.com/package/awilix">Awilix</a>. It’s pretty simple to use, and moving off the manual approach will only require touching the container file. There’s <a href="https://medium.com/@Jeffijoe/dependency-injection-in-node-js-2016-edition-f2a88efdd427">a very good series</a> about how and why to use it, written by the author of the package.</p><h3>Coming next</h3><p>OK, we already talked about architecture and how to connect the layers in a nice way! In the next post, we&#39;re going to show some real code and common patterns for the layers we just spoke about, with the exception of the state layer — which will be handled in a separate post. Take some time to absorb these concepts; they’re going to be useful when we enter into detail about these patterns, and everything will make more sense. See you there!</p><h3>Recommended links</h3><ul><li><a href="https://blog.codeminer42.com/nodejs-and-good-practices-354e7d763626">NodeJS and Good Practices</a></li><li><a href="https://www.youtube.com/watch?v=WpkDN78P884">Bob Martin — Architecture the Lost Years</a></li><li><a href="https://www.youtube.com/watch?v=Oyt4Ru7Xzq0&amp;feature=youtu.be">Rebecca Wirfs-Brock — Why We Need Architects (and Architecture) on Agile Projects</a></li><li><a href="http://dddcommunity.org/books/">Domain-Driven Design</a></li></ul><p>Written by <a href="https://medium.com/u/b65d1410fd8b">Talysson de Oliveira</a> and <a href="https://medium.com/u/56076e80e075">Iago Dahlem Lorensini</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9b80a16b8ec7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codeminer-42/scalable-frontend-1-architecture-9b80a16b8ec7">Scalable Frontend #1 — Architecture Fundamentals</a> was originally published in <a href="https://medium.com/codeminer-42">The Miners</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[NodeJS and Good Practices]]></title>
            <link>https://medium.com/codeminer-42/nodejs-and-good-practices-354e7d763626?source=rss-b65d1410fd8b------2</link>
            <guid isPermaLink="false">https://medium.com/p/354e7d763626</guid>
            <category><![CDATA[domain-driven-design]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[clean-architecture]]></category>
            <dc:creator><![CDATA[Talysson de Oliveira]]></dc:creator>
            <pubDate>Wed, 12 Apr 2017 15:15:07 GMT</pubDate>
            <atom:updated>2017-04-13T13:47:07.458Z</atom:updated>
            <content:encoded><![CDATA[<h4>Separation of concerns doesn’t need to be boring</h4><p>Softwares are subject to change all the time, and one aspect that contributes to defining the quality of a code is precisely how easy it is to be altered. But what makes it be like so?</p><blockquote>…if you’re afraid to change something it is clearly poorly designed.</blockquote><blockquote>— Martin Fowler</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/250/1*9ppH_8U3MPiTUD_wNs3hgg.gif" /><figcaption>Don&#39;t make your code a swiss army knife</figcaption></figure><h3>Separation of concerns and responsibilities</h3><p>“Gather together the things that change for the same reasons. Separate those things that change for different reasons.”</p><p>Be those <em>things</em> functions, classes, or modules, they can apply to <a href="https://8thlight.com/blog/uncle-bob/2014/05/08/SingleReponsibilityPrinciple.html">the single responsibility principle and the separation of concerns</a>. Designing software based on these principles starts out with the architecture.</p><h3>Architecture</h3><p>In software development, a <em>responsibility</em> is a task that a unity is committed to achieving, for example: represent the concept of a product in an application, handle network requests, persist a user in the database, and so on and so forth.</p><p>Did you notice that these three responsibilities aren’t in the same category? It’s due to the fact that they belong to <em>different</em> layers, which in turn can be divided into <em>concepts</em>. As per the above example, “persist a user in the database”<em> </em>relates to the “user” concept and also to the layer that talks to the database.</p><p>In general, architectures correlated to the above concepts tend to be split off into four layers: domain, application, infrastructure, and input interfaces.</p><h3>Domain layer</h3><p>In this layer, we may define units which play the role of entities and business rules and have a direct relationship to our domain. For example, in an application of users and teams, we would probably have a User entity, a Team entity, and a JoinTeamPolicy to answer whether a user is able to join a given team or not.</p><p>This is the most isolated and important layer of our software, and it may be used by the application layer to define <em>use cases</em>.</p><h3>Application layer</h3><p>The application layer defines the actual behavior of our application, thus being responsible for performing interactions among units of the domain layer. For example, we can have a JoinTeam <em>use case</em> which receives instances of User and Team and passes them on to JoinTeamPolicy; if the user can join in, it delegates the persistence responsibility to the infrastructure layer.</p><p>The application layer can also be used as an <em>adapter</em> to the infrastructure layer. Let’s say our application can send emails; the class responsible for talking directly to the email server (let’s call it MailChimpService) belongs to the <em>infrastructure layer</em>, but the one that actually sends the emails (EmailService) belongs to the <em>application layer </em>and uses MailChimpService internally. Therefore, the rest of our application does not know details about specific implementations— it only knows that EmailService is able to send emails.</p><h3>Infrastructure layer</h3><p>This is the lowest layer of all, and it’s the boundary to whatever is external to our application: the database, email services, queue engines, etc.</p><p>A common feature of <em>multilayer</em> applications is the use of the <a href="https://martinfowler.com/eaaCatalog/repository.html"><em>repository pattern</em></a> to communicate with the database or some other external persistence service (like an API). Repository objects are essentially treated as collections, and the layers using them (<em>domain</em> and <em>application</em>) don&#39;t need to know which persistence technology lies underneath (similarly to our email service example).</p><p>The idea here is that the repository <a href="https://en.wikipedia.org/wiki/Interface_(computing)#Software_interfaces_in_object-oriented_languages">interface</a> belongs to the domain layer, and the implementation, in turn, belongs to the infrastructure layer — <em>i.e.</em> the domain only knows about methods and parameters accepted by the repository. That makes both layers more flexible, even with regards to testing! Since JavaScript doesn’t implement the concept of interfaces, we can imagine our own, and based on that create a concrete implementation on the infrastructure layer.</p><h3>Input interfaces layer</h3><p>This layer holds all the entry points of our application, such as controllers, the CLI, websockets, graphic user interfaces (in case of desktop applications), and so on.</p><p>It should not have any knowledge about business rules, use cases, persistence technologies, and not even about other kinds of logic! It should only receive user input (like URL parameters), pass it on to the <em>use case</em> and finally return a response to the user.</p><h3>NodeJS and the separation of concerns</h3><p>OK, after all of this theory, how does it work on a Node application? Truth to be said, some patterns used in multilayer architectures fit in very well with the JavaScript world!</p><h3>NodeJS and the domain layer</h3><p>The domain layer on Node can be composed of simple <a href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Classes">ES6 classes</a>. There are lots of ES5 and ES6+ modules to aid in creating domain entities, for example: <a href="http://github.com/talyssonoc/structure/">Structure</a>, <a href="https://github.com/AmpersandJS/ampersand-state">Ampersand State</a>, <a href="https://www.npmjs.com/package/tcomb">tcomb</a> and <a href="https://github.com/sylvainpolletvillard/ObjectModel">ObjectModel</a>.</p><p>Let’s see a simple example using <em>Structure</em>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a4cd75fbc61795451f8197cf5e1fe05b/href">https://medium.com/media/a4cd75fbc61795451f8197cf5e1fe05b/href</a></iframe><p>Notice that our list doesn’t contain <em>Backbone.Model</em> or modules like <em>Sequelize</em> and <em>Mongoose</em>, because these are meant to be used in the infrastructure layer to communicate with the external world. Therefore, the rest of our codebase doesn’t even need to know about their existence.</p><h3>NodeJS and the application layer</h3><p><em>Use cases</em> belong to the application layer, and differently from promises they may have results beyond <em>success</em> and <em>failure</em>. A good Node pattern for such cases is the <a href="https://nodejs.org/api/events.html">event emitter</a>. To use it, we have to extend the EventEmitter class and emit an event for each possible outcome, thus hiding the fact that our repository uses a promise internally:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/76a94fb682196b609315fbf6eb089113/href">https://medium.com/media/76a94fb682196b609315fbf6eb089113/href</a></iframe><p>That way our entry point can execute the <em>use case</em> and add a listener for each outcome, just like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5903902870c9aab19da87302d1d6aa6a/href">https://medium.com/media/5903902870c9aab19da87302d1d6aa6a/href</a></iframe><h3>NodeJS and the infrastructure layer</h3><p>The implementation of the infrastructure layer should not present difficulties, but be careful for its logic to not leak out to above layers!</p><p>For example, we may use <a href="https://www.npmjs.com/package/sequelize"><em>Sequelize</em></a> models to implement a repository that talks to a SQL database, and give it method names which <em>don’t</em> suggest the existence of a SQL layer underneath — such as the generic add method of our last example.</p><p>We can instantiate a SequelizeUsersRepository and pass it up to its dependents as a usersRepository variable, and the dependents may just interact with its interface.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7818f45d247e37df1f638ef7b4effbb5/href">https://medium.com/media/7818f45d247e37df1f638ef7b4effbb5/href</a></iframe><p>The same reasoning goes for NoSQL databases, email services, queue engines, external APIs and so on.</p><h3>NodeJS and the input interfaces layer</h3><p>There are lots of possibilities for implementing this layer on Node apps. For HTTP requests, the <a href="https://npmjs.com/package/express">Express</a> module is the most used one but you can also use <a href="https://www.npmjs.com/package/hapi"><em>Hapi</em></a> or <a href="https://www.npmjs.com/package/restify"><em>Restify</em></a>. The final choice comes down to implementation details, though changes to this layer should not affect other ones. If migrating from <em>Express</em> to <em>Hapi</em> somehow implies in performing thereof changes, it’s a sign of coupling and you should pay close attention to fix it.</p><h3>Connecting the layers</h3><p>Having a layer talk <em>directly </em>to another can be a bad decision and cause coupling between them. In object-oriented programming, a common solution to this problem is <em>dependency injection </em>(DI). This technique consists in making dependencies of a class be received as arguments in its constructor, instead of requiring the dependencies and instantiating them inside of the class itself — hence creating the so-called <em>inversion of control</em>.</p><p>Using this technique enables us to isolate dependencies of a class in a very concise way, making it more flexible and easy to be tested because stubbing out dependencies becomes a trivial task.</p><p>For Node applications there’s a good DI module called <a href="https://www.npmjs.com/package/awilix"><em>Awilix</em></a>, which allows us to leverage DI without coupling our code to the DI module itself — so we don’t feel like using that <em>weird</em> dependency injection machinery from Angular 1. The author of <em>Awilix</em> has a <a href="https://medium.com/@Jeffijoe/dependency-injection-in-node-js-2016-edition-f2a88efdd427">series of posts</a> explaining dependency injection with Node which are worth reading, and also an introduction about how to use <em>Awilix</em>. By the way, if you plan on using <em>Express</em> or <em>Koa</em>, you should also take a look at <a href="https://www.npmjs.com/package/awilix-express"><em>Awilix-Express</em></a> or <a href="https://www.npmjs.com/package/awilix-koa"><em>Awilix-Koa</em></a>.</p><h3>A practical example</h3><p>Even with all those examples and explanations about layers and concepts, I believe there’s nothing better than a practical example of an application following a <em>multilayer</em> architecture to convince you that indeed, it can be simple to use!</p><p>You can check out this production-ready <a href="https://github.com/talyssonoc/node-api-boilerplate">boilerplate for web APIs with Node</a>. It applies the <em>multilayer</em> architecture and has the basics already set up (including <a href="https://github.com/talyssonoc/node-api-boilerplate/wiki">documentation</a>) for you, so that you can practice and even use it as a kickstarter for your Node apps.</p><h3>Additional information</h3><p>If you want to learn more about multilayer architectures and how to separate concerns, take a look at the following links:</p><ul><li><a href="http://wiki.c2.com/?FourLayerArchitecture">FourLayerArchitecture</a></li><li><a href="https://www.youtube.com/watch?v=WpkDN78P884">Architecture — The Lost Years</a></li><li><a href="https://8thlight.com/blog/uncle-bob/2012/08/13/the-clean-architecture.html">The Clean Architecture</a></li><li><a href="http://wiki.c2.com/?HexagonalArchitecture">Hexagonal Architecture</a></li><li><a href="http://dddcommunity.org/">Domain-driven design</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=354e7d763626" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codeminer-42/nodejs-and-good-practices-354e7d763626">NodeJS and Good Practices</a> was originally published in <a href="https://medium.com/codeminer-42">The Miners</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>