<?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 Dominik Szczepaniak on Medium]]></title>
        <description><![CDATA[Stories by Dominik Szczepaniak on Medium]]></description>
        <link>https://medium.com/@dominikszczepaniak?source=rss-a7a40f499568------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*2AiXDEZa-XdTWcu5H-lteA.jpeg</url>
            <title>Stories by Dominik Szczepaniak on Medium</title>
            <link>https://medium.com/@dominikszczepaniak?source=rss-a7a40f499568------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 11:21:56 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@dominikszczepaniak/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 first application in Express.js]]></title>
            <link>https://dominikszczepaniak.medium.com/the-first-application-in-express-js-b2bd22857e51?source=rss-a7a40f499568------2</link>
            <guid isPermaLink="false">https://medium.com/p/b2bd22857e51</guid>
            <category><![CDATA[expressjs]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Dominik Szczepaniak]]></dc:creator>
            <pubDate>Fri, 16 Jun 2023 20:33:20 GMT</pubDate>
            <atom:updated>2023-06-16T20:40:48.238Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*paSvn-4APpeR2HNeQRGibw.jpeg" /></figure><p>Despite its long-standing presence on the market, Express.js is still one of the most popular frameworks for Node.js. All signs in heaven and earth indicate that this is unlikely to change in the near future. In this article, I will show you a template that allows creating your first application in Express.js. You can use it for learning, prototyping, or even as a foundation for a business application.</p><p>I decided to bet on Express for several reasons. First, <strong>Express.js is now a dozen years old</strong>. During that time, the technology matured, resulting in a huge number of products and tools being built around it. The demand for familiarity with Express will be high for a long time, and this article will help you learn a little more about it.</p><p>Secondly, <strong>the overhead while learning Express is, in my opinion, very low.</strong> The Express documentation is easy to understand, simple, and concise. The docs even allow you to copy code snippets that, with a little customization, can be run as full-fledged applications.</p><p>Third, the low entry level, lifespan, and ubiquity of Express usage mean <strong>there is quite a large community built around Express.</strong> The large community and abundance of Express-related content mean if you run into a problem, there is a low chance that no one before you has stepped into it. The <em>express</em> tag on <a href="https://stackoverflow.com/questions/tagged/express">Stack Overflow</a> is alive and well. In the popularity rankings of frameworks for Node.js, Express is still present. On the other hand, is the statement <em>“millions of flies can’t be wrong”</em> true in this case? I leave the topic for discussion in the comments 😉</p><h3>Components of the application</h3><p>The application template I’ve prepared allows you to quickly launch your project in Express.js. I decided to use TypeScript because of the typing capability and convenience of my work and yours. If for some reason you prefer to write in pure JavaScript, removing types, additional dependencies, and TypeScript configuration should not be a problem. You can find all the code described in this article in the <a href="https://github.com/elszczepano/expressjs-boilerplate">repository on GitHub</a> that I prepared for this post. To download the application, all you need to do is run git clone git@github.com:elszczepano/expressjs-boilerplate.git &amp;&amp; cd expressjs-boilerplate</p><p>After downloading the project, you can run the application by calling docker-compose up --build</p><p>The command builds an image with the application and starts the container with the database and the application. Additionally, it configures the network on which the containers will run.</p><p>When you see confirmation in the command line that the application is running, you can visit <a href="http://localhost:8000/hello/:name">http://localhost:8000/hello/:name</a>or send an HTTP request to the specified address using any HTTP client such as cURL, Postman, or Insomnia. In place of the :name parameter, you can enter your name. As a result, a JSON will be returned with a list of users who have queried the indicated address and the value passed.</p><h3>Application infrastructure</h3><p>In addition to the Express app itself, I used several additional components.</p><p>The first is the MySQL database. It will literally take you a while to replace MySQL with any other database solution, so you don’t have to get too attached to it. To keep the template simple, I also decided not to use ORMs. Instead of an ORM, I decided to use the <a href="https://www.npmjs.com/package/mysql">node driver for MySQL</a> directly. Of course, nothing prevents you from adding any ORM to the project.</p><p>The prepared application was adjusted to run in containers. For this purpose, I have prepared a Dockerfile and a docker-compose.yml file. With this, it is possible to run the prepared application using Docker. Before you run the application, make sure that Docker and Docker Compose are installed on your machine. The Dockerfile for prepared application looks as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/da56cb954b5817baeb6a6bcbc0c8658f/href">https://medium.com/media/da56cb954b5817baeb6a6bcbc0c8658f/href</a></iframe><p>I used the <a href="https://hub.docker.com/_/node">Alpine Linux image</a> for the Node.js environment as the base image. Feel free to swap it for any other, depending on your preferences. The advantage of the Alpine Linux-based image is its small size. The docker-compose.yml file, in addition to the definition of the application container, additionally contains the definition of the container for the MySQL database, and the configuration of the network in which the containers will run:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cb34481f6feac5270852013cd0da5268/href">https://medium.com/media/cb34481f6feac5270852013cd0da5268/href</a></iframe><p>From the most interesting configuration options, I decided to implement a health check for the database. The application container in Express.js will only start when the health check for the database returns a healthy status. In addition, all environment variables come from the .env file, which contains the values of the environment variables. The use of environment variables avoids keeping secrets in the repository and allows dynamic injection of variable values. The structure of the .env file is based on the structure from the .env.example file:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d3bbc096d5370aa9556d50ae6deffa4c/href">https://medium.com/media/d3bbc096d5370aa9556d50ae6deffa4c/href</a></iframe><h3>Components of the application</h3><p>The prepared application was prepared in the <a href="https://dominikszczepaniak.medium.com/what-minimum-viable-product-is-f52552d3c78e">Minimum Viable Product</a> approach. I was keen to deliver a working boilerplate in a short time. The application boilerplate is supposed to allow rapid prototyping of the application, skipping the overhead of preparing the application structure and low-level components. If the MVP approach is unfamiliar to you, you can learn more about it in my article about <a href="https://dominikszczepaniak.medium.com/what-minimum-viable-product-is-f52552d3c78e">Minimum Viable Product</a>. Using the MVP approach means that the application framework is far from perfect. Some changes and improvements will need to be implemented before the production launch of the application.</p><h4>Service</h4><p>The main component of the application is the Service class. The file contains the initialization of Express and the inclusion of the HTTP server. In addition, extra middleware code can be included in this file. For now, I have only added the body-parser. The Service class itself looks as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3a7769035c1a7facf6ee66c9f87a2a2f/href">https://medium.com/media/3a7769035c1a7facf6ee66c9f87a2a2f/href</a></iframe><h4>Router</h4><p><strong>The concept of a router is necessary to understand in order to develop applications in Express.js</strong>. I decided to prepare an abstraction that allows you to conveniently define paths by defining the IRouteDefiniton interface. In addition, the custom abstraction allows for potential expansion with additional mechanisms as needed. For now, the main value of the router is the automatic handling of query body processing in PUT and POST requests. The code of the Router presents as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/294e2c137b4c9b5ddd0af13e4c383963/href">https://medium.com/media/294e2c137b4c9b5ddd0af13e4c383963/href</a></iframe><p>Adding a Router to an application is handled in the Service class in the addRouter() method. The method allows you to define a path parameter, in case all of the paths should contain a specific prefix.</p><p>The initialization and addition of the router look as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5650b4635dafe956ed293962258b5fbf/href">https://medium.com/media/5650b4635dafe956ed293962258b5fbf/href</a></iframe><p>Of course, nothing prevents you from defining more than one router.</p><h4>Handler</h4><p>In the Handler class, the Request and Response objects known from Express, as well as the work with the HTTP protocol in Node.js itself, are available for use. The responsibility the Handler is to prepare the data received in the request into the expected format. The Handler is also responsible for returning the response to the client in the appropriate format. Each Handler implements the IHandler interface:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c6b7b0fcfeb853c79a1b79ea5026749c/href">https://medium.com/media/c6b7b0fcfeb853c79a1b79ea5026749c/href</a></iframe><p>In the application, I prepared a sample implementation of the IHandler interface. HelloHandler can serve you as an example for further handlers:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/be1a600c5148941674188c16236b1fb3/href">https://medium.com/media/be1a600c5148941674188c16236b1fb3/href</a></iframe><h4>Controller</h4><p>In the Handler constructor, I passed a Controller instance, on which the execute() method is then called. Controllers contain the business logic of the application. The controller is defined by the IController interface:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/85534e58c9e0f082c0f9f00c47f2d2ce/href">https://medium.com/media/85534e58c9e0f082c0f9f00c47f2d2ce/href</a></iframe><p>The interface uses two generic types — TParams to type the object with parameters and TResult to type the response. The implementation of the example controller is shown in the following code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a993a30f48c276c1883abffc45f06104/href">https://medium.com/media/a993a30f48c276c1883abffc45f06104/href</a></iframe><p>The example controller uses the repository injected in the constructor to store the passed name. Then it retrieves the guest list from the repository and returns the result.</p><h4>Repository</h4><p><strong>The repository classes will serve as components of the data access layer.</strong> By using repositories, the logic related to data access is isolated from the business logic contained in the controller. The controller receives a ready-made class that allows it to perform specific operations on the data, such as reading, writing, or updating. What’s more, the controller doesn’t even know what data source it is using or the structure of the stored data. Thanks to this, the MySQL database can be replaced by another solution, without the necessity of modifying the business logic code. An example repository is shown in the following code snippet:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7023eed38d82a40b6db52b1b6c4f807c/href">https://medium.com/media/7023eed38d82a40b6db52b1b6c4f807c/href</a></iframe><p>In the case of repositories, there is no need to define an underlying interface common to all repositories. Methods defined in the repository will strictly depend on the data structure and business requirements.</p><h3>Driver</h3><p>The Driver class is an additional abstraction into which I have wrapped the driver for MySQL. <strong>With this, repositories using MySQL can ignore the implementation details of the external component.</strong> A developer gets a class with a convenient query method, which expects only a database query. A meticulous eye could see that the presented solution is vulnerable to SQL Injection attacks. In order to simplify the example, I decided to omit this aspect, but it is one of the necessary improvements that would need to be added to the framework before using it in production. In case you want to use ORM, Driver could be replaced with another solution. The MySQLDriver class looks as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1fbeae840823972f4353ea911d4ebff3/href">https://medium.com/media/1fbeae840823972f4353ea911d4ebff3/href</a></iframe><p>In addition to the query method for performing queries, the Driver also implements methods for establishing and terminating connections to the database. Based on the IDriver interface, other drivers could be prepared for different database solutions. However, this would require handling database queries in various dialects. It could be dynamically injected queries or generating queries depending on the dialect chosen.</p><h4>Migrator</h4><p>In order to use a database, it would be good to initialize its structure beforehand. ORMs take care of this automatically, but since I decided to abandon ORMs, it was necessary to prepare my own migrator. The migrator is a relatively simple class and uses the driver described earlier. The migrator’s only responsibility is to perform the migration:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5d56187e2647c6313bcb9a2639681768/href">https://medium.com/media/5d56187e2647c6313bcb9a2639681768/href</a></iframe><p>The migrate method in a loop executes all migrations. The migrations are defined in .sql files in the queries directory. A field for improvement in the migrator is saving the state of migrations. Currently, running the application on an already migrated database can result in errors or inconsistent data. A separate table can be used for this purpose.</p><h3>Tests</h3><p>In order to make the boilerplate as complete as possible, I prepared a configuration to write tests. I used <a href="https://github.com/avajs/ava">AVA</a> as the test runner. The chosen test runner allows for easier writing of FIRST-compliant tests, especially <em>Fast</em> and <em>Isolated</em> rules due to the parallel running of tests. For preparing stubs, I used the Sinon library. I prepared some sample tests to demonstrate how tests can be written using AVA and Sinon. I used the <a href="https://www.npmjs.com/package/node-mocks-http">node-mocks-http</a> library to prepare mocks of the Request and Response classes. The unit tests for the HelloController class look as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/db64ab0ebe292457fc88507296ec50e2/href">https://medium.com/media/db64ab0ebe292457fc88507296ec50e2/href</a></iframe><p>Integration and E2E tests can be prepared using AVA too.</p><h3>Summary</h3><p>I have already mentioned several times that the prepared framework needs a few improvements to be a base for production applications. Nevertheless, it provides a solid foundation on which you can build your first application in Express.js. In addition to the aforementioned improvements, an element worth adding is the input validation mechanism. When you launch the application, check what happens when you enter a name longer than 30 characters. It is worthwhile to protect the application from such situations.</p><p>Another useful component is a logger. You can use one of the ready-made solutions, such as <a href="https://github.com/pinojs/pino">Pino.js</a>.</p><p>I strongly encourage you to check out the <a href="https://github.com/elszczepano/expressjs-boilerplate">repository on GitHub</a>, to clone and run the project. Remember that this template is meant to serve you first and foremost, so don’t be afraid to add, change or remove something.</p><p>I also encourage you to participate in the discussion about the solution and performed decisions in the comments. In particular, I encourage you to suggest changes and improvements. You can also do this directly on GitHub in the form of an issue or pull request 😁.</p><p>The original article has been posted on my Polish programming blog — <a href="https://devszczepaniak.pl/pierwsza-aplikacja-w-express-js/">Devszczepaniak.pl</a>.</p><h4>Sources and extra links</h4><ul><li><a href="https://stackdiary.com/node-js-frameworks">The Most Popular Node.js Frameworks in 2023</a></li><li><a href="https://www.npmjs.com/package/mysql">MySQL driver npm package</a></li><li><a href="https://hub.docker.com/_/node">node — Official Docker Image</a></li><li><a href="https://snyk.io/blog/choosing-the-best-node-js-docker-image/">Choosing the best Node.js Docker image</a></li><li><a href="https://blog.devgenius.io/reduce-the-size-of-your-node-js-docker-image-by-up-to-90-53aad23890e2">Reduce the size of your Node.js docker image by up to 90%</a></li><li><a href="https://expressjs.com/en/guide/routing.html">Express routing</a></li><li><a href="https://github.com/avajs/ava">GitHub — AVA</a></li><li><a href="https://sinonjs.org/">Sinon.js</a></li><li><a href="https://github.com/pinojs/pino">Pino.js</a></li><li><a href="https://www.npmjs.com/package/node-mocks-http">node-mocks-http</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b2bd22857e51" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Relational databases normal forms explained]]></title>
            <link>https://dominikszczepaniak.medium.com/relational-databases-normal-forms-explained-513cf13b0151?source=rss-a7a40f499568------2</link>
            <guid isPermaLink="false">https://medium.com/p/513cf13b0151</guid>
            <category><![CDATA[database]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[normalization]]></category>
            <dc:creator><![CDATA[Dominik Szczepaniak]]></dc:creator>
            <pubDate>Sat, 08 Oct 2022 15:23:13 GMT</pubDate>
            <atom:updated>2023-01-05T13:17:53.286Z</atom:updated>
            <content:encoded><![CDATA[<h3>Relational databases Normal Forms explained</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P-jpwyR1q67M8QEPf-a0oA.jpeg" /></figure><p>The article has been originally posted on my Polish blog — <a href="https://devszczepaniak.pl/postaci-normalne">devszczepaniak.pl</a>.</p><p>This article covers the topic of normal forms in relational databases. The article includes practical examples of normalized tables for each normal form.</p><p>First, let’s explain what normalization is. Usually, normalization is understood as <strong>activities aimed at achieving the optimum level of order in a particular area under given circumstances</strong>. In the context of computer sciences and work with data normalization is focused on ordering datasets to process them easier and/or optimize their size. In our case normalization affects data stored in relational databases. Normalizing databases brings a bunch of benefits:</p><ul><li>Decreases the risk of data inconsistency.</li><li>Simplifies operations performed on a database (adding, reading, updating, deleting).</li><li>Allows grouping data easier, for example by extracting some data to separate tables.</li><li>Decreases the eventual data size by removing duplicated data.</li></ul><p>Normalizing databases also have some cons. Strictly obeying normalization rules may cause that data in particular tables will be <strong>tightly coupled</strong> with each other that should be represented via relationships. A simple <em>SELECT</em> query may be transferred into a query with multiple <em>JOIN</em> clauses and with intermediate tables. <strong>It may decrease the performance of the query as well as its readability and maintainability.</strong> Degraded performance equals longer execution time. Depending on application type and business requirements, data duplication or inconsistency may be a better trade-off than e.g. a significantly higher query execution time. For this reason, it is crucial to normalize databases consciously and when the benefits outweigh the costs.</p><p>Also, in the context of data normalization, it is worth recalling the words of Donald Knuth:</p><blockquote>Premature optimization is the root of all evil.</blockquote><p>Nevertheless, there are cases when normalizing data is necessary or at least highly recommended. For example, almost always it makes sense to split contact details into separate columns such as street, city, postal code, and so on.</p><h3>Normal forms in relational databases</h3><p>Normalizing relational databases involves changing the structure of tables in a database into such a form that they meet the rules described by normal forms. The most commonly used and known normal forms are:</p><ul><li>The 1st Normal Form (1NF).</li><li>The 2nd Normal Form (2NF).</li><li>The 3rd Normal Form. (3NF).</li></ul><p>In addition, in the literature, you can find a few less-known normal forms:</p><ul><li>Boyce Codd’s Normal Form.</li><li>The 4th Normal Form (4NF).</li><li>The 5th Normal Form (5NF).</li></ul><p>In this article, I’m going to focus on the first three normal forms, as they are common, and using them will bring you the most benefits.</p><h3>The 1st Normal Form</h3><p>To demonstrate the 1st Normal Form let’s first take a look at an example. The example table is a menu from an example restaurant:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/627/1*UsrgUrb-KJ7T0PzHf9LaPw.png" /></figure><p>The 1st Normal Form says that <strong>each value in the database should be atomic</strong>. In other words, the value should be <strong>indivisible</strong>. The presented example does not meet this rule. First of all, each row in the table shows a list of ingredients. Moreover, some of the ingredients are repeated in several rows. If you‘d like to modify the menu, for example, replace the cheese with Mozarella di Buffala, you will need to modify all the rows in the table. Searching for a table with such a structure for the ingredients also can be cumbersome.</p><p>In the presented case, the solution is to use a <em>many-to-many</em> relationship and divide the presented table into two separate tables. The first table should contain the menu, and the second table should be a table with ingredients. Thus, the ingredient becomes a separate entity in the database, it has a primary key that allows to identify of each ingredient. There’s also a need to add an additional, table that will keep relations between menu positions and ingredients. The presented example normalized to the 1st Normal Form looks as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/627/1*bv50Sff-OzLPkjZqGaej9w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/618/1*HnGDXEW118aOB37i7JAPxA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/632/1*MdPmyF1qq65EWCWVeRjTcA.png" /></figure><p>Other examples, where it is useful to use the 1st Normal Form are separating the first and last name fields into two separate ones or the aforementioned division of the address into street and city.</p><h3>The 2nd Normal Form</h3><p>The first mandatory condition to meet the 2nd Normal Form <strong>is satisfying the 1st Normal Form</strong>. The second condition is that all columns in a table <strong>must depend on the primary key</strong>. The example presented below presents a table that does not meet the 2nd Normal Form requirements:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/615/1*nl8omef0Eh0AvKce9Lm5XQ.png" /></figure><p>The presented table contains orders from an online store. The 1st Normal Form is satisfied as each column is <strong>atomic</strong>. Nevertheless, the presented table contains far too much-unrelated data. First of all, the customer data i.e. first name, last name, address, and city should be moved to a separate table. For simplicity, let’s assume that there can be only one product per order. In this case, instead of the product name and its price, the table should contain a foreign key referring to a record in the table with products. The table with orders after normalization looks as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/622/1*rq7JhnSKU2vNH4qPV5M0jw.png" /></figure><p>All data not related to a primary key has been moved to other tables, while only foreign keys are stored in the order table.</p><h3>The 3rd Normal Form</h3><p>The first mandatory condition to satisfy the 3rd Normal Form <strong>is satisfying the 2nd Normal Form</strong>. The second obligatory condition to meet is that <strong>a non-key column must not depend on another non-key column</strong>. Below is an example of a table that will undergo normalization:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/622/1*EhrSpEQAiJi5a3tbT5EMiQ.png" /></figure><p>The presented table contains a list of contractors with values such as company name, address, city, phone, and dial code. The column is the one with the dialing code. <strong>The dialing code does not depend on the primary key, but on the city column, which is not a primary key</strong>. In this situation, the city and dial code should be extracted into a separate table, and in the presented table, add a foreign key pointing to the table containing the matching city and dial code.</p><h3><strong>Summary</strong></h3><p>I hope you learned something interesting through this article, and normalizing relational databases will no longer be a mystery to you. I encourage you to read the sources and additional materials and leave a like and comment.</p><h4>Sources and extra links</h4><ul><li><a href="https://learn.microsoft.com/en-us/office/troubleshoot/access/database-normalization-description">https://learn.microsoft.com/en-us/office/troubleshoot/access/database-normalization-description</a></li><li><a href="https://www.mikealche.com/software-development/a-humble-guide-to-database-schema-design">https://www.mikealche.com/software-development/a-humble-guide-to-database-schema-design</a></li><li><a href="https://www.linkedin.com/pulse/premature-optimization-root-all-evil-clark-dever/">https://www.linkedin.com/pulse/premature-optimization-root-all-evil-clark-dever</a></li><li><a href="https://towardsai.net/p/data-science/how-when-and-why-should-you-normalize-standardize-rescale-your-data-3f083def38ff">https://towardsai.net/p/data-science/how-when-and-why-should-you-normalize-standardize-rescale-your-data-3f083def38ff</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=513cf13b0151" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Factory design pattern]]></title>
            <link>https://dominikszczepaniak.medium.com/factory-design-pattern-bf683514a92a?source=rss-a7a40f499568------2</link>
            <guid isPermaLink="false">https://medium.com/p/bf683514a92a</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[gang-of-four]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[factory-pattern]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Dominik Szczepaniak]]></dc:creator>
            <pubDate>Sun, 10 Jul 2022 12:46:48 GMT</pubDate>
            <atom:updated>2022-07-10T12:46:48.149Z</atom:updated>
            <content:encoded><![CDATA[<p>This article was originally written in Polish and published on <a href="https://devszczepaniak.pl/wzorzec-projektowy-factory-fabryka">my blog</a>.</p><p>The <strong>Factory</strong> is a pretty popular and simple to use design pattern. The literature distinguishes 4 types of factories:</p><ul><li><strong>Factory</strong></li><li><strong>Factory Method</strong></li><li><strong>Static Factory</strong></li><li><strong>Abstract Factory</strong></li></ul><p>The Factory belongs to the creational design patterns family.</p><p>In this article, I’m going to cover and illustrate all the mentioned Factory types. <strong>The main idea of the Factory, as in the case of a real factory, is to create objects.</strong> Using Factories allows for hiding implementation details of creating objects and separating them from the business logic layer. In the article, all variations of the Factory design pattern will be explained via short code snippets in TypeScript. Fortunately, to understand the prepared snippets being familiar with only the basics of object-oriented concepts is required. Okay, so let’s get crackin’!</p><h3>Factory</h3><p>The best way to show the practical use case and benefits of using the Factory design pattern is by showing it in the example. The system you maintain includes a sales system and needs to generate invoices for customers. As your customers are from various countries, the invoices have to be suited for their needs. The examples of adjustments are:</p><ul><li>the date format e.g. <em>dd/mm/yyyy</em>, <em>mm/dd/yyyy</em>;</li><li>the text direction — left-to-right or right-to-left;</li><li>the currency.</li></ul><p>Potentially it creates a large number of combinations and possibilities and handling it inside the <strong>business logic would cause the business code unreadable and hard to maintain</strong>. It would also make the business code error-prone and harder to extend. The step forward in the design of the solution is to create a simple Factory where all types of invoices could be wrapped into a separate private method. The created factory would expose only one public method with a param object as an expected input. Based on parameter values a ready-to-print invoice will be produced. The business logic code knows nothing about the details of creating invoices for specific countries. The Factory is treated as a black box that creates an invoice based on the provided parameters. The most trivial implementation of the Factory may look as follows (I intentionally skipped parts of code that are not required to illustrate the Factory pattern):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/337d04d485e229ef78759425e8ee1122/href">https://medium.com/media/337d04d485e229ef78759425e8ee1122/href</a></iframe><p>When the Factory implementation is ready, all you have to do is to create an InvoiceFactory instance and call the createInvoice method. The result of calling the mentioned method is a ready-to-print invoice that can be returned to the customer by the piece of code responsible for handling the business logic. The invoice generation process in the business logic code may look as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6528c329395a46ea157c081dfde90d3a/href">https://medium.com/media/6528c329395a46ea157c081dfde90d3a/href</a></iframe><p>The current implementation allows for creating invoices for customers from Poland, the United States, and Saudi Arabia. <strong>To add support for other countries the created Factory can be very easily extended.</strong> All you need to do is to create a new case in the public method, a new private method, and a new specific class for a particular country. Note that I decided to create a separate class for each country. Otherwise, the Factory would end as one bloated class that for sure you’d like to avoid.</p><h3>Factory Method</h3><p>The solution proposed in the previous section has one significant issue. Excluding parts of the code that are specific to a particular country, <strong>there’s a part of the code that is common for each invoice</strong> such as file format or font settings (size, color, family, etc.).</p><p>To resolve this issue the Factory Method design pattern can be used. Thanks to this, it’s possible to extract a part of code that is common for all the invoice classes. The previous implementation converted to a Factory Method implementation may look as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/757e38a4f292f7f655d824ef49dc0317/href">https://medium.com/media/757e38a4f292f7f655d824ef49dc0317/href</a></iframe><p>The common part of the process of generating invoices has been wrapped in the _generateInvoice method in the abstract Invoice class. The specific implementations for particular countries are implemented in particular classes in the protected format method. <strong>The above code combines the Factory Method and Factory design patterns.</strong> <strong>It shows that design patterns can be used together and mixed to get the desired results!</strong> Combined patterns caused the solution to be clear, easy to extend, and free from code duplication.</p><p>The simplicity of the solution causes that introducing a new software engineer to this piece of the code will take less time and boost their productivity. The engineer does not have to be familiar with the low-level logic related to the process of generating invoices. All they have to do is to implement a very simple class with a finite number of options and attach it to the factory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*iNbq6vK97iw6cGxc.jpg" /><figcaption>source: pixabay.com</figcaption></figure><h3>Static Factory</h3><p>When the factory is ready another issue appeared. In the system, there were a few instances of the InvoiceFactory created. A few customers received an invoice with the same id. To eliminate this issue we could introduce a <strong>Static Factory</strong>. In this case, we can implement a simple in-memory solution that will store the ids of already generated invoices to prevent the described situation. In the case of duplication, an error will be thrown. The example implementation of the Static Factory may look as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/110d8d5840c8de185316c1e36b094ebe/href">https://medium.com/media/110d8d5840c8de185316c1e36b094ebe/href</a></iframe><p>Static Factories are also helpful in the case of various helpers and utils classes. <strong>In this case, pretty often it does not make sense to instantiate a factory class, and relying on static methods is simpler.</strong> Calling HelperClass.doX( params )is way simpler than creating a new instance of a HelperClass.</p><h3>Abstract Factory</h3><p>The described sales system has been successfully shipped into production. After some time a new set of requirements have been delivered to your team. Now, not only invoices but also internal sales reports have to be generated by the system. <strong>All types of documents have to be able to generate via a single interface. Moreover, the system must be ready to be extended by new document types in the future.</strong> The solution to this issue is to create an <strong>Abstract Factory</strong>. In short, <strong>the Abstract Factory uses other factories in its implementation and is a Factory at the same time</strong>. The example of the Abstract Factory is shown by the code below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6509ec78ec7c1fa856139969859cfbc7/href">https://medium.com/media/6509ec78ec7c1fa856139969859cfbc7/href</a></iframe><p>The prepared solution meets all the mentioned business requirements. Here I have to underline that all the factories must return a document that meets the IDocument interface. Abstract Factories are the perfect solution if your system produces various objects with a common interface. In our case all the created objects are documents.</p><h3>Summary</h3><p>I hope, after reading the article the idea of the Factory design pattern is clear to you. I encourage you to try the described factories out in your projects. I also will be grateful if you give a clap and leave a comment! Below you’ll find some extra materials and sources.</p><h3>Sources and extra materials</h3><ul><li><a href="https://blog.oshogunle.com/popular-design-patterns-revisited-in-javascript-ckepwexml02tskps10r090iz7">https://blog.oshogunle.com/popular-design-patterns-revisited-in-javascript-ckepwexml02tskps10r090iz7</a></li><li><a href="https://www.tutorialspoint.com/design_pattern/factory_pattern.htm">https://www.tutorialspoint.com/design_pattern/factory_pattern.htm</a></li><li><a href="https://stackoverflow.com/questions/13029261/design-patterns-factory-vs-factory-method-vs-abstract-factory">https://stackoverflow.com/questions/13029261/design-patterns-factory-vs-factory-method-vs-abstract-factory</a></li><li><a href="https://sourcemaking.com/design_patterns/factory_method">https://sourcemaking.com/design_patterns/factory_method</a></li><li><a href="https://www.javatpoint.com/factory-method-design-pattern">https://www.javatpoint.com/factory-method-design-pattern</a></li><li><a href="https://stackoverflow.com/questions/929021/what-are-static-factory-methods">https://stackoverflow.com/questions/929021/what-are-static-factory-methods</a></li><li><a href="https://www.geeksforgeeks.org/abstract-factory-pattern">https://www.geeksforgeeks.org/abstract-factory-pattern</a></li><li><a href="https://www.baeldung.com/java-abstract-factory-pattern">https://www.baeldung.com/java-abstract-factory-pattern</a></li><li><a href="https://sourcemaking.com/design_patterns/abstract_factory">https://sourcemaking.com/design_patterns/abstract_factory</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bf683514a92a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A brief introduction to mutation tests]]></title>
            <link>https://dominikszczepaniak.medium.com/a-brief-introduction-to-mutation-tests-8c036d807f75?source=rss-a7a40f499568------2</link>
            <guid isPermaLink="false">https://medium.com/p/8c036d807f75</guid>
            <category><![CDATA[stryker]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[mutation]]></category>
            <category><![CDATA[mutation-testing]]></category>
            <dc:creator><![CDATA[Dominik Szczepaniak]]></dc:creator>
            <pubDate>Tue, 10 May 2022 16:43:06 GMT</pubDate>
            <atom:updated>2022-05-10T17:02:20.916Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YCMsE6mp8IhpHZRwpE2vkA.jpeg" /></figure><p><strong>Mutation testing</strong> is an approach designed to validate the quality of unit tests. The main idea of mutated testing is based on creating mutants programs. <strong>The mutant program is a slightly modified copy of the original program. The changes should be very small and should not affect the program overall.</strong> After creating a set of mutants, all the tests that are used for testing the original program are run both for the original program, and for mutants.</p><h3>The process of mutation testing</h3><ol><li>The first step is preparing a set of mutants. Each mutant has to contain exactly <strong>one change</strong> in the comparison with the original program. Mutants created during this step are called<strong> first-order mutants</strong>. This step is called <em>infection</em>.</li><li>After creating a set of mutants the unit tests set is run both for the original program and for all the modified programs (mutants).</li><li>Test results from the original program are compared with test results run for each created mutant. For this reason, tests need to be stable. As a stable test, I consider a test that produces neither false-positive nor false-negative results. Unstable tests make mutation testing pointless.</li><li>If a mutant program will cause a different test result than the original program, the mutant is terminated. Otherwise, the mutant is kept alive. Alive mutants are called <strong>equivalent mutants</strong>.</li></ol><p><strong>The more mutants are killed the better. The number of alive mutants should strive for zero. </strong>The value of killed mutants divided by all the mutants is called a <strong>mutation score</strong>. A test that did not fail for any mutant is a good candidate to be verified in the context of its usability. Such a test is not sensitive to changes in the source code. There are a few reasons why such tests should be inspected:</p><ul><li>A test may be badly written. For example, an assertion may check a condition that is always true.</li><li>A test may not check anything useful. For example, the code always produces a result that will cause a test’s success.</li></ul><p>A low number of alive mutants is a factor that may indicate (but it does not have to!) that tests for the original program are well-designed.</p><h3>Types of mutations</h3><p>Statement mutations — a part of code from the original program is removed:</p><ul><li>Remove if statements.</li><li>Remove else statement from if.</li></ul><p>Value mutations — the default values in the original code are replaced:</p><ul><li>Change default values for constants from the original code.</li><li>Change default parameters in methods or objects.</li><li>Change hardcoded values e.g. static string values.</li></ul><p>Decision mutations — statements from the original code are changed:</p><ul><li>Increment returned number values.</li><li>Replace in if conditions e.g x &lt; y with x &gt; y, or x &lt; y with x =&lt; y.</li><li>Replace a variable in condition with a static value e.g. change x === y to 100 === y.</li><li>Replace or remove &amp;&amp; and || statements.</li><li>Change returned data type, e.g. instead of 5 return &#39;5&#39;.</li><li>Replace the arithmetic operators e.g. replace + with -.</li><li>Keyword replacement e.g. replacing true with false. or replace let with const.</li></ul><h3>Mutation testing technologies</h3><p>The most trivial way to start the adventure with mutation testing is to create mutants manually. However, let’s be honest, it is frustrating and neither fast nor effective. Fortunately, some tools allow automating this process:</p><ul><li>Stryker Mutator (JS, C#, Scala)</li><li>PIT (Java, Kotlin)</li><li>Infection (PHP)</li><li>mull (C, C++)</li><li>mutmut (Python)</li></ul><h3>Pros of mutation testing</h3><ul><li>Mutation tests check the real code coverage for testing statements. Nevertheless, there are dedicated tools for it such as Istanbul for JavaScript test frameworks. Note that, the code coverage metric in the context of tests’ quality is discussable. Code coverage means only that a test touched a covered part of the code. This metric says nothing about tests’ accuracy or completeness.</li><li>Allows for detecting human errors faster.</li><li>Provides a metric that could be used to measure the quality of existing tests.</li><li>Helps to find missing tests.</li><li>Sometimes it helps to detect a dead code.</li><li>Detects a high coupling in the code — a small change may cause a cascade effect. In such a case a mutant will cause a massive number of test fails.</li></ul><h3>Cons of mutation testing</h3><ul><li>The time required to generate mutants can be very long as well as running tests for all the generated mutants.</li><li>A lot of automatically generated mutants are redundant. It’s not a trivial thing to determine the usability of the mutant. In edge cases, nearly 99% of mutants can be redundant!</li><li>Without automation tools, mutation testing is extremely ineffective.</li><li>Mutation testing is applicable only to white-box testing.</li></ul><h3>Sources and extra materials</h3><ul><li><a href="https://csharp.academy/mutation-testing/">https://csharp.academy/mutation-testing</a></li><li><a href="https://medium.com/analytics-vidhya/unit-testing-in-python-mutation-testing-7a70143180d8">https://medium.com/analytics-vidhya/unit-testing-in-python-mutation-testing-7a70143180d8</a></li><li><a href="https://medium.com/digio-australia/introduction-to-mutation-testing-with-stryker-1338451ad4e5">https://medium.com/digio-australia/introduction-to-mutation-testing-with-stryker-1338451ad4e5</a></li><li><a href="https://www.guru99.com/mutation-testing.html">https://www.guru99.com/mutation-testing.html</a></li><li><a href="https://nexocode.com/blog/posts/mutation-testing/">https://nexocode.com/blog/posts/mutation-testing</a></li><li><a href="https://www.techtarget.com/searchitoperations/definition/mutation-testing">https://www.techtarget.com/searchitoperations/definition/mutation-testing</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8c036d807f75" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[About JavaScript observers]]></title>
            <link>https://dominikszczepaniak.medium.com/about-javascript-observers-2b8790f4e775?source=rss-a7a40f499568------2</link>
            <guid isPermaLink="false">https://medium.com/p/2b8790f4e775</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[observer-pattern]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[front-end-development]]></category>
            <dc:creator><![CDATA[Dominik Szczepaniak]]></dc:creator>
            <pubDate>Sat, 21 Nov 2020 16:21:13 GMT</pubDate>
            <atom:updated>2021-08-22T11:54:32.647Z</atom:updated>
            <content:encoded><![CDATA[<p>The article has been originally posted on my Polish blog — <a href="https://devszczepaniak.pl/o-obserwatorach-w-javascript/">devszczepaniak.pl</a>.</p><p>If you have any experience with JavaScript, you have probably used <strong>listeners</strong>. Listeners, as the name says, listen to a particular event or events. After the event occurrence, they execute previously defined actions. For those who have never had a chance to use JavaScript listeners, let’s take a look at the sample code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b159e66460585c6aba63db6988b06933/href">https://medium.com/media/b159e66460585c6aba63db6988b06933/href</a></iframe><p>The code passed to callback will execute, every single time when an element with an id equals foo will be clicked. Of course, there are much more events than click. For the full list of events, visit <a href="https://developer.mozilla.org/pl/docs/Web/Events">MDN</a>.</p><p>Similarly, the<strong> observer</strong> Web APIs provided by browsers work. Before I start describing all the observers I need to explain some theory. As you can see I still write about observers, observing, and so on. This concept is described and defined in the programming world as the <strong>observer design pattern</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hwZnBZ7XPj8DvoH2UWmYXg.jpeg" /></figure><h3>A few words about the observer</h3><p>As the name may suggest, the core element of this pattern is the <strong>observer and observables</strong>. It may sound weird but shortly: the observer observes observables and execute a previously defined action when some declared condition will occur. For example, in our neighborhood lives an annoying neighbor who doesn’t like children. This neighbor tries to chase away children every time when children play football next to his house. The neighbor is the <strong>observer</strong>, and the children are <strong>observables</strong>. When the children start playing football,<strong> the observer executes a previously defined action</strong> - he tries to chase the children away or call the police. It depends on how annoying the neighbor is 😄</p><p>There are many more use cases of this pattern in daily life. If you subscribe to a channel on YouTube you can click a bell icon and receive a notification when a new video will be added. So you create an observer that notifies you when a particular action will be done — a new video release. This mechanism is implemented also in almost every mobile app!</p><h3>JavaScript observers</h3><p>When you create a browser app in JavaScript, a few observer Web APIs are provided:</p><ul><li><strong>MutationObserver</strong></li><li><strong>PerformanceObserver</strong></li><li><strong>ResizeObserver</strong></li><li><strong>IntersectionObserver</strong></li></ul><h4>MutationObserver</h4><p>As the name says, the <strong>MutationObserver</strong> listens to <strong>mutations</strong> (changes) in the observed object. To clarify it, let’s take a look at the example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d96eff1a49b18517478975ec4d42eb12/href">https://medium.com/media/d96eff1a49b18517478975ec4d42eb12/href</a></iframe><p>At first glance, this code doesn’t seem to be complicated. First, a new observer is created, where we declare an action that will be executed when the event will be observed. Then, the observe() method is called. The element with the foo id is added to the <strong>observables pool</strong> with some additional parameters that allow specifying whether e.g. children or attributes should be observed as well.</p><p>The first option is related to <strong>attributes change</strong>. The example attributes are class, id, href, checked, etc. However, it doesn’t affect data-value attributes. For <strong>data attributes</strong> there’s a dedicated option — characterData. Another option is childList that listens to <strong>adding or removing children</strong>. Last but not least is the subtree option, that causes all <strong>children are observed too</strong>.</p><p>Here, I need to point out these options should be used carefully. For example, if you create a mutation observer on the body element it may bring a huge impact on performance. <strong>In this case, every single change in the DOM tree will trigger the defined action!</strong> Besides these options, there are also some other options to set:</p><ul><li><strong>attributeOldValue</strong> — defines whether old attribute value should be passed to observer callback,</li><li><strong>characterDataOldValue</strong> — same as the previous one but related to data attributes,</li><li><strong>attributeFilter </strong>— allows specifying an array of attributes to observe. It doesn&#39;t make any sense to observe all attributes when it is not needed.</li></ul><p>Do not forget to disable the observer when it is not needed anymore using the observer.disconnect() method.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JOUDfTuwnm8qsENH.jpg" /></figure><h4>PerformanceObserver</h4><p>I mentioned the performance factor in this article once. For measuring performance, the <strong>PerformanceObserver</strong> can be used. In this case, a piece of code may be useful too:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/95fa481d736d904893c042328e5ede6d/href">https://medium.com/media/95fa481d736d904893c042328e5ede6d/href</a></iframe><p>As you can see, creating other observers looks similar. As the argument, a callback with defined action is passed. In the observe() method a list of entryTypesis defined. In this case only the measure event is handled. The above code will measure how much time will take adding numbers from <em>0</em> to <em>50000</em>. Each occurrence of the performance.measure(&#39;sum&#39;) call, is added to the entries array. Then, it is easy to calculate a time difference between each occurrence. The full list of available entryTypes is available on <a href="https://developer.mozilla.org/en-US/docs/Web/API/PerformanceEntry/entryType">MDN</a>.</p><h4>ResizeObserver</h4><p>When I heard about the <strong>ResizeObserver</strong> for the first time I had some doubts about it. I can use the resize event, that is emitted on the window or the document size change. The game-changer is that <strong>ResizeObserver allows listening to size change for any element on the website.</strong></p><p>It includes also changes caused by adding or removing elements to the observed element. What’s more, we don’t have to look for element dimensions in its properties — the information is available in the callback directly:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6505db3dc8157917fcaa7ea11c74f4a3/href">https://medium.com/media/6505db3dc8157917fcaa7ea11c74f4a3/href</a></iframe><p>Using this observer is trivial and there’s no difference in comparison with others. We just create a new instance and execute the observe() method with the observed element inside.</p><h4>IntersectionObserver</h4><p>Last but not least is the <strong>IntersectionObserver</strong>. The use case of this observer is when you need to check whether an observed element is physically visible on the browser view. It can be used for example for <strong>lazy loading</strong> or <strong>infinite scrolling</strong> features. The code for this observer is identical to the previous but I’ll add it anyway:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/07bab9116b134ebe1c3be2038326962c/href">https://medium.com/media/07bab9116b134ebe1c3be2038326962c/href</a></iframe><p>The interesting property of theentry object is intersectionRatio that says what percentage of the observed object is visible in the browser view.</p><h3>Sources</h3><ul><li><a href="https://developer.mozilla.org/pl/docs/Web/Events">https://developer.mozilla.org/pl/docs/Web/Events</a></li><li><a href="https://davidwalsh.name/mutationobserver-api">https://davidwalsh.name/mutationobserver-api</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver">https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/API/PerformanceObserver">https://developer.mozilla.org/en-US/docs/Web/API/PerformanceObserver</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/API/PerformanceEntry/entryType">https://developer.mozilla.org/en-US/docs/Web/API/PerformanceEntry/entryType</a></li><li><a href="https://developers.google.com/web/updates/2016/06/performance-observer">https://developers.google.com/web/updates/2016/06/performance-observer</a></li><li><a href="https://web.dev/resize-observer/">https://web.dev/resize-observer/</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/API/ResizeObserver">https://developer.mozilla.org/en-US/docs/Web/API/ResizeObserver</a></li><li><a href="https://developers.google.com/web/updates/2016/04/intersectionobserver">https://developers.google.com/web/updates/2016/04/intersectionobserver</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/API/IntersectionObserver">https://developer.mozilla.org/en-US/docs/Web/API/IntersectionObserver</a></li><li><a href="https://hackernoon.com/observer-vs-pub-sub-pattern-50d3b27f838c">https://hackernoon.com/observer-vs-pub-sub-pattern-50d3b27f838c</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2b8790f4e775" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[REST API — introduction]]></title>
            <link>https://dominikszczepaniak.medium.com/rest-api-introduction-e8e90a84a7cd?source=rss-a7a40f499568------2</link>
            <guid isPermaLink="false">https://medium.com/p/e8e90a84a7cd</guid>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[rest-api]]></category>
            <dc:creator><![CDATA[Dominik Szczepaniak]]></dc:creator>
            <pubDate>Sun, 18 Oct 2020 18:23:05 GMT</pubDate>
            <atom:updated>2021-08-22T11:55:55.649Z</atom:updated>
            <content:encoded><![CDATA[<h3>REST API — introduction</h3><p>The article has been originally posted on my Polish blog — <a href="https://devszczepaniak.pl/wstep-do-rest-api/">devszczepaniak.pl</a>.</p><p>At the very beginning let’s decipher the <strong>REST</strong> acronym. REST stands for <strong>Re</strong>presentational <strong>S</strong>tate <strong>T</strong>ransfer. REST is a programming architecture style that determines the way how application resources can be accessed. The following term has been introduced in 2000 by Roy Fiedling.</p><p>The next acronym is <strong>API </strong>— <strong>A</strong>pplication <strong>P</strong>rogramming<strong> I</strong>nterface. API is the set of rules and tools that defines how to communicate with a system. It includes human-computer communication but also communication between systems/applications.</p><p>To sum it up briefly — <strong>API defines how to communicate with a system, and REST is an architecture style that defines the API shape.</strong></p><p>The last acronym, inseparably related to the topic is <strong>HTTP</strong> — <strong>H</strong>yper<strong>t</strong>ext<strong> T</strong>ransfer <strong>P</strong>rotocol. HTTP (but way more often its secure version — HTTPS) is a protocol that you use every day, also to read this article. To communicate with REST APIs, the HTTP methods are used. In general, there are <strong>nine</strong> HTTP methods, but in practice, most of APIs uses only <strong>four</strong> of them:</p><ul><li><strong>GET</strong></li><li><strong>POST</strong></li><li><strong>PUT</strong></li><li><strong>DELETE</strong></li><li>CONNECT</li><li>OPTIONS</li><li>TRACE</li><li>PATCH</li><li>HEAD</li></ul><p>As I mentioned, <strong>for most of the cases the first four methods are sufficient</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eKODkTKH1xQQylA_VrqGRQ.jpeg" /></figure><h3>How do APIs work?</h3><p>The workflow with API can be described in a few points:</p><ol><li>A client prepares a request for a particular address — endpoint.</li><li>The client sends the prepared request.</li><li>The system receives a request and prepares a response.</li><li>The response is sent back by the system to the client.</li><li>The client receives and processes the response.</li></ol><p>For most of the readers, this workflow may be obvious by my goal for this article is <strong>EVERYONE,</strong> after reading this article knows what an API is and how it works.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*49glYe-285UPvYW9xp7JFw.jpeg" /></figure><h3>The HTTP methods</h3><p>Because it is just an introduction, I’m going to describe only four basic HTTP methods:</p><p><strong>GET</strong> — as the name says, it is used mostly to getting data. All additional data are passed in the <strong>headers or as query params</strong>. The example request may look like <a href="http://example.com/api/resource?per_page=10&amp;page=2.">http://example.com/api/resource?per_page=10&amp;page=2</a>. Pretty often the GET method is also used to determine whether a particular resource exists. However, in my opinion, a way more useful HTTP method for this purpose is the <strong>HEAD</strong> method. The main difference is that the HEAD method response is more lightweight and includes only headers. In this case, the only information that you need is a status code that is included in the HTTP header response (usually it is 200).</p><p><strong>POST</strong> — this method dedicated to creating and sending data by using the <strong>request body</strong>. Note that, the POST response should return the Location header with the location of the newly created resources.</p><p><strong>PUT </strong>— similar to the POST method. The main difference is that a <strong>PUT endpoint should point to the exact resource</strong>. PUT is mostly used to updating existing resources. Worth mentioning is the fact, that PUT overwrites the whole resource — for a partial update, the PATCH method is recommended.</p><p><strong>DELETE</strong> — the method dedicated to deleting resources. In most of the cases, this method will return just a set of headers with status code equals 204(no content).</p><h3>The REST rules</h3><p>To say an API is RESTful, it needs to meet a few assumptions:</p><ol><li><strong>Separate user interface (UI) from the operations on the application server. </strong>The client application can only affect the server by sending HTTP requests. Also, the server-side part of the application cannot affect the user interface. It allows using the API in various systems, and reuse the UI for different APIs.</li><li><strong>Stateless</strong> — it is said that REST is stateless. It means that every single request has to include the full set of information to process the request. There are no constructs like states, sessions, etc..</li><li><strong>Cacheability </strong>— the response returned by the API has to clearly define whether it’s cacheable or not. It has a huge meaning in the case of different types of resources. Let’s say we have a system for tracking airplanes. Some information, for example, an airplane position, should not be cacheable — it changes dynamically. However, the information about the color, available seats, or the airplane name for sure should be cacheable.</li><li><strong>Endpoints</strong> — the resources’ addresses — should clearly define what resources they point on. Their structure should describe the accessed resource. Also, the endpoint structure should not rely on the database structure. Of course, it may be that the endpoints may look like a database structure but for sure these parts of the system should not be dependent on each other.</li><li><strong>Layers separation</strong> — data access, presentation, and business logic layers should be separated. None of the layers should have an impact on others. Moreover, the use of additional APIs used by the server-side application should be hidden. For example, the information about the airplane color may come from another API. A user doesn’t have to know about it.</li><li><strong>Providing additional scripts and adapters for the API</strong>. If we know that our solution is used together with other solutions it is worth considering creating a dedicated integration app or adapter. For example, pretty often use cases are authentication mechanisms.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i168FlkpQgXes6manG0jyg.jpeg" /></figure><h3>The advantages of using APIs</h3><p>The main advantage is <strong>versatility</strong>. Let’s say you have to prepare a web application and a mobile app for an online bookstore. You can use the same API for both projects!</p><p>For the second — <strong>the truly RESTful interfaces are intuitive</strong> and using them is easy and convenient. It reduces the time spent on reading documentation.</p><p>Also, you can use resources from various APIs for a single application.</p><p>The last advantage is that there are many tools to work with APIs more convenient. One of the most popular is <a href="https://www.postman.com/">Postman</a>.</p><h3>The data format</h3><p>APIs mostly return data in the <strong>J</strong>ava<strong>S</strong>cript <strong>O</strong>bject <strong>N</strong>otation (<strong>JSON</strong>) format. Sometimes, but less and less, the XML format is used. The JSON format is pretty readable and intuitive.</p><h3>The examples of popular APIs</h3><ul><li>Google Geolocation API,</li><li>YouTube Data API,</li><li>WordPress REST API,</li><li>SWAPI</li><li><strong>and tons of other solutions!</strong></li></ul><h3>Summary</h3><p>I hope you found something useful in this short introduction to this topic.</p><p>The original source of this article is the <a href="https://devszczepaniak.pl/wstep-do-rest-api/">blog post</a> from my Polish <a href="https://devszczepaniak.pl/">blog</a>. I’d like to thank <a href="https://www.comandeer.pl/">Comandeer</a> who added a supplement for this topic under the original article.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e8e90a84a7cd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CSS code cleanup]]></title>
            <link>https://dominikszczepaniak.medium.com/css-code-cleanup-107ca3b79aad?source=rss-a7a40f499568------2</link>
            <guid isPermaLink="false">https://medium.com/p/107ca3b79aad</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[css]]></category>
            <category><![CDATA[webdev]]></category>
            <category><![CDATA[refactoring]]></category>
            <dc:creator><![CDATA[Dominik Szczepaniak]]></dc:creator>
            <pubDate>Sun, 27 Sep 2020 14:45:49 GMT</pubDate>
            <atom:updated>2021-08-22T11:56:59.162Z</atom:updated>
            <content:encoded><![CDATA[<p>The article has been originally posted on my Polish blog — <a href="https://devszczepaniak.pl/porzadkowanie-kodu-css">devszczepaniak.pl</a>.</p><p>At the beginning of my adventure with programming, I didn’t take care of the quality of a CSS code I wrote. All the code was included in one, bloated file. Although class names ( usually ) were quite descriptive, there was a noticeable lack of consistency and order. After getting back to this code after some time it was challenging to twig to about class names meaning. For example, a .page-header didn’t say whether it’s the main page header or an article header. In this particular case, the class name is too generic.</p><h3>An example of a bad code</h3><p>Let’s take a look at the example of bad code (SCSS — only the nesting feature is used in this case):</p><pre>.name-item {<br> height: 100%;<br>}<br>.name-item &gt; h1 &gt; small {<br> display: block;<br> text-align: center;<br> padding-bottom: 30px;<br> padding-top: 1vmin;<br> color: rgba(0,0,0,0.4);<br> font-size: 3vmin;<br>}<br>.projects-container {<br> img {<br>  padding:3vmin;<br>  transition:0.4s all;<br> }<br> img:hover {<br>  transform: scale( 0.9 );<br> }<br>}<br>.text-justify {<br> box-sizing:border-box;<br> font-size: 1.6vmax;<br>}<br>.blog {<br> font-size:2rem;<br> color:#4d4646;<br>}</pre><p>Now let’s consider what is wrong with this code:</p><ul><li>At first, <strong>classes’ names are not descriptive enough and misleading.</strong> The names like .name-item or .blog says absolutely <strong>nothing</strong> about a styled element meaning. Whether the elements are headers, containers or list items, or maybe some block of text? It is neither clear nor consistent.</li><li>The worse situation is with the .text-justify class. <strong>This class doesn&#39;t justify the text!</strong> Even worse, this class adds another, not related styles!</li><li>I have also paid attention to the .project-container class. The problem is not with the class name itself but with the nested elements. I assume it is a container that includes some projects. Probably the element includes a list of projects with attached images. If we assume that the container includes only images the following code is acceptable.<br>However, let’s imagine a situation when we’d like to add a banner with some ads. In this case, all images ( also in the banner ) will be styled identically. For this reason, banner and thumbnails should be distinguished and img styles should be replaced with some class, for example .project-thumbnail.</li><li>I also try to <strong>avoid adding styles on ids and elements</strong> and style elements by using classes. However, I want to emphasize that it’s my personal practice.</li><li>The next aspect where there’s a noticeable lack of consistency is a color notation. Once the notation rgba(0,0,0,0.4) is used but later also another one (#4d4646) is in use. Mixing conventions is a bad practice. It is another example of inconsistency.<br>The best solution, in this case, could be extracting colors to variables and base on them. Currently, variables are available even with pure CSS, so I don&#39;t see any contraindications to use them.</li><li>The last point I paid attention to is the .text-justify class again. Personally, I’m not a fan of classes like .font-bold, .align-center, and so on. In my opinion, a class should describe what element is, not how it looks.<br>However, the most of UI frameworks and libraries like Boostrap offer such classes so as you can see there are various approaches. So the decision is up to you, I won’t judge you 😉</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-FycXFR_dWKcyB7T205qsA.jpeg" /></figure><h3>Specificity</h3><p>After analyzing the example of bad code, let’s consider what can we do to make it better. The first thing that will significantly improve our CSS code is <strong>specificity</strong>. It allows us to determine the uniqueness of a given element.</p><p>For sure, <strong>the most unique in our codebase are ids</strong>. On a website, only one element can have a particular id (so it’s the most specific). The next are classes and elements. I think it is pretty intuitive.</p><p>To check and calculate specificity you can use some online tools like <a href="https://specificity.keegan.st/">this one</a>.</p><p>Let’s analyze the following code example:</p><pre>&lt;style&gt;<br>#square {<br>  background-color: black;<br>}</pre><pre>.square {<br>  background-color: pink;<br>}</pre><pre>div {<br>  width: 100px;<br>  height: 100px;<br>  background-color: orange;<br>} <br>&lt;/style&gt;</pre><pre>&lt;div class=&quot;square&quot; id=&quot;square&quot; style=&quot;background-color: purple;&quot;&gt; &lt;/div&gt;</pre><p>After running this code in the browser we will see… a purple square. It is obviously caused by inline styles on the element. You should avoid inline styles. I use inline styles only for some unusual cases like dynamically loaded background images (but also this can be achieved without inline styles).</p><p>Now let’s focus on the style tag. When we remove inline styles, our square will become black, which may be at first glance a bit confusing. But why?</p><p>The answer is previously mentioned <strong>specificity</strong>. Styles for ids have higher priority than styles for classes and elements. Although the styles for color are redefined times more, these redefinitions are ignored because of the specificity mechanism. If we remove styles for the#square id, the square will become pink. It is caused by the specificity mechanism too. Classes are higher in the hierarchy than elements. Note that in the case of an equal level of specificity the last defined value will be used:</p><pre>#square {<br>  background-color: black;<br>}</pre><pre>#square {<br>  background-color: red;<br>}</pre><p>In this particular case, the square will become red.</p><p>To understand the specificity mechanism better just use the example from the article and modify it a little bit. You can also use the online tool I linked earlier.</p><h3>Splitting the code</h3><p>In the beginning, I mentioned that I kept all CSS code in one bloated file <br>(usually called style.css). A good practice is to separate styles into different files. However, project specificity and variety are extremely wide, so creating the universal recipe on how to split your CSS code is impossible. You need to determine a consistent set of rules for a particular project.</p><p>However, the number of files doesn&#39;t matter. If you use tools like <a href="https://webpack.js.org/">Webpack</a> you don’t have to care about it. Finally, all CSS code will be minified and merged into one file.</p><h3>CSS standardized methods</h3><p>The mechanisms that allow determining an exact structure of your CSS code in the project are standardized methods. There are many CSS standardized methods but for sure the most popular are:</p><ul><li>Object-Oriented CSS (<strong>OOCSS</strong>)</li><li>Atomic CSS (<strong>ACSS</strong>)</li><li>Atomic Design</li><li>SUIT CSS</li><li>Scalable and Modular Architecture for CSS (<strong>SMACSS</strong>)</li><li>Block Element Modifier (<strong>BEM</strong>)</li></ul><p>Of course, there are much more standardized methods but these are the most popular. Personally, I use<strong> BEM</strong>. It’s the most convenient for me and it matches my requirements best.</p><h3>The example of BEM use</h3><p>Let’s assume we have to style a sign in form. There are required fields for email and password.</p><p>The whole form needs to be wrapped in a container. Let’s add a .login-form class. This will be our block (<strong>B</strong>).</p><p>The next step will be adding a class for inputs. Let’s create a .login_form__field and use it for each input element. The crucial part of this class name is the double underscore determining elements (<strong>E</strong>) in BEM.</p><p>Every form should have some validation. For example, in the case of an invalid email or password, the invalid input should be marked somehow (for example by a red border). The responsible class for it can be called .login-form__field--invalid. The part after the double dash is called a modifier (<strong>M</strong>).</p><p>As you can see, BEM enforces some name convention. It is not only helpful during modifications, updates, adding new parts of the website, and so on, but also it creates some abstraction for the DOM structure. Now the website is not just a mix of divs and spans but a logical structure with distinguished elements like forms, toolbars, sidebars, menus, sliders, etc..</p><h3>The summary</h3><p>Personally, I believe that CSS code maintenance is not a trivial thing. On the other hand, if you know the basics of how to keep your code more consistent and readable, the CSS maintenance is not rocket science.</p><p>I know that I didn’t fully cover the topic. For sure really helpful are CSS preprocessors like LESS or SASS. They offer much more than pure CSS, for example. functions, loops, mixins, or conditionals. But the knowledge that I shared with you in this article is a good point to start the process of polishing your CSS code! 😉</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=107ca3b79aad" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What Minimum Viable Product is?]]></title>
            <link>https://dominikszczepaniak.medium.com/what-minimum-viable-product-is-f52552d3c78e?source=rss-a7a40f499568------2</link>
            <guid isPermaLink="false">https://medium.com/p/f52552d3c78e</guid>
            <category><![CDATA[startup]]></category>
            <category><![CDATA[minimum-viable-product]]></category>
            <category><![CDATA[mvp]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[product-development]]></category>
            <dc:creator><![CDATA[Dominik Szczepaniak]]></dc:creator>
            <pubDate>Sun, 07 Jun 2020 13:58:13 GMT</pubDate>
            <atom:updated>2021-08-22T12:11:59.861Z</atom:updated>
            <content:encoded><![CDATA[<p>The article has been originally posted on my Polish blog — <a href="https://devszczepaniak.pl/minimum-viable-product/">devszczepaniak.pl</a>.</p><p>In short — <strong>Minimum Viable Product </strong>( MVP ) is a product that has only the basic features that are required to run and use a product. The MVP term, according to <a href="https://en.wikipedia.org/wiki/Minimum_viable_product">Wikipedia</a>, was created by Frank Robinson in 2001.</p><p>The MVP approach has some important advantages. The biggest one is the relatively short development and releases time. Almost every product or application like Netflix, Facebook, and so on looked significantly different than the current version. Since the MVP release, <strong>they evolved and still are improved</strong> — new features are added and bugs are fixed.</p><p>The other advantage is that <strong>developing MVP is cheaper than developing the final and complete product</strong>. What’s more, if you make a decision that the product is not satisfying or not profitable <strong>you can stop developing it at a very early stage without wasting too many funds and time</strong>.</p><p>A great example could be Facebook Messenger. For that product, the MVP is an application that is able to send and read messages. All improvements like sending GIF files, stickers, video calls, games were added later when the product evolved.</p><h3>MVP in the work of a programmer</h3><p>Programmers are a group that uses the MVP approach for most of their work. The most obvious is creating a product roadmap, but also MVP is pretty useful during writing code.</p><p>If you write, for example, a signing up form you can split it up for a few phases. The first phase is to create a form that allows registering a new user, the second phase can be adding a validation. Probably this form will contain some bugs or performance issues ( caused by e.g. an invalid regular expression ). Fixing it could be the third phase.</p><p>Another place where you can notice the MVP approach is the <strong>Test Driven Development approach</strong>. TDD includes three phases: <em>red</em>, <em>green</em>, and <em>refactor</em>, where the green phase is the MVP. After creating a piece of code that works properly and meets the requirements ( MVP ) you refactor it, fix bugs, and improve the performance.</p><h3>How not to use the MVP approach?</h3><p>Here and in the further part of the article, I’ll use a vehicle as an example of a product to develop. To not complicate the example I’ll be using some simplifications and generalizations.</p><p>What is most important in a vehicle? Ability to drive. After this short explanation, we can make a conclusion — the most luxurious and advanced car that can’t drive does not the assumptions of the MVP approach.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xXuRM97Nj1sY1Uv0I7kpBg.jpeg" /></figure><p>Even the ugliest, rusted, without lights, turn signals, or even doors or a hood but that can drive <strong>meets the assumptions of MVP</strong>. Of course, it is only theoretical contemplation — that vehicle couldn’t be approved for road traffic because of law restrictions.</p><h3>So how to use the MVP approach?</h3><p><strong>First of all, you need to set the goal you would like to achieve</strong>. As I mentioned earlier in the case of a vehicle the goal is to make it driveable. To make a vehicle you will need a wheel, preferably a few wheels. Now you don’t even need an engine — to move you can use the power of your legs. After mounting wheels to a wooden plank you have created a skateboard!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4NIHiwCCLV2fHvwW7nKvTQ.jpeg" /></figure><p>And here’s your MVP! The created product gives you the ability to move from point A to point B. Although it is quite poor and imperfect it meets the basic requirements. Let’s improve it!</p><p>You could improve the steering of your vehicle. Of course, you can use body movement for turning but it is quite inconvenient. Let’s add some steering systems. <strong>And here’s your skateboard became a scooter!</strong> It still is able to drive but now it is simpler, more convenient, and comfortable. At this step, you can also add brakes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZGLvdDc0OdCwhV9ga2EPtw.jpeg" /></figure><p>The vehicle drives and turns but its speed is not amazing. The way how it accelerates isn’t also satisfying. What’s more, a small curb can be an insurmountable obstacle.</p><p>Let’s modify the vehicle — let’s improve the construction and accelerating mechanism. <strong>The next step is a huge refactor.</strong> The result of this refactor can be a bike. Thanks to this our mobility, acceleration, and safety were strongly improved!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ceNEbFZZQEk1zzCmgPU9lQ.jpeg" /></figure><p>At this moment your vehicle is able to drive, turn, and is quite convenient but a huge inconvenience is that you have to use the power of your body to move. The most obvious solution is adding an engine, so let’s do it. Don’t forget to add a fuel tank, turn signals, lights, and mirrors. Now your bike became a motorbike!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*zfKr7q8pjD9rFx8IgnNjRA.jpeg" /></figure><p>Now you are able to move with satisfying speed without using the power of your legs. However, you are not able to take any additional baggage. Also in case of a rainy day, your vehicle becomes inconvenient. These changes need the second huge refactor. Let’s replace the current engine with a better one, add seats, wrap it into a steel cage and your motorbike was transformed into a car. Now your vehicle is safer, more convenient, and is able to take additional baggage and use it in a case of bad weather.</p><p>You are almost there! At the last step, your product needs only some amenities like a radio, GPS, air condition, and other visual additions.<strong> After a few iterations of improvements and refactors, you have the final product.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*OnjrZtkXWwVS-TU1Y2XAxg.jpeg" /></figure><h3>Done!</h3><p>Your final product is ready to use and does not resemble the initial product. You started from a skateboard and finished with a luxurious car, but both products are able to move from point A to point B.</p><p>Of course, this example is full of simplifications and generalizations. In real life, it is not possible to create a car from a motorbike but I wanted only to show a product evolution process.</p><p>However, there are examples of huge refactors like making a car from a motorbike! You can read a <a href="https://engineering.fb.com/data-infrastructure/messenger/">case study of Facebook Messenger refactor</a> where the application size was reduced by 84 percent, from more than 1.7M lines to 360,000.</p><p><strong>Personally I use the MVP approach for most of my projects and I find it as extremely useful.</strong> This approach is also very useful from the marketing point of view. Publishing the very early version of the product and testing it on real users can give a better perspective and receive a lot of feedback. It helps us to detect UX issues, bugs, and suggestions for improvement. Another opportunity is selling pre-orders or starting a crowdfunding campaign on <a href="https://www.kickstarter.com/">Kickstarter</a> or <a href="https://www.indiegogo.com/">Indiegogo</a>.</p><p>The only disadvantage of the MVP approach I’ve found is that some users may be discouraged after using the not ready products but still, I think it is worth taking the risk.</p><p>Please let me know in a comment what do you think about the MVP approach!</p><h4>Image sources:</h4><ul><li><a href="https://pixabay.com/">https://pixabay.com/</a></li><li><a href="https://www.pexels.com/">https://www.pexels.com/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f52552d3c78e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The basics of automated software testing]]></title>
            <link>https://dominikszczepaniak.medium.com/the-basics-of-automated-software-testing-2ff317bac2c?source=rss-a7a40f499568------2</link>
            <guid isPermaLink="false">https://medium.com/p/2ff317bac2c</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[test-automation]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[testing]]></category>
            <dc:creator><![CDATA[Dominik Szczepaniak]]></dc:creator>
            <pubDate>Sun, 22 Mar 2020 18:29:12 GMT</pubDate>
            <atom:updated>2021-08-22T11:51:31.271Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, I’ll introduce you to the topic of automated software testing. I’ll show you also how to write your first test suites in JavaScript.</p><p>The article has been originally posted on my Polish blog — <a href="https://devszczepaniak.pl/podstawy-testow-automatycznych-oprogramowania/">devszczepaniak.pl</a></p><p>By most beginner programmers, the topic of automated software testing is skipped or at least neglected. Partly, I understand their motivations. For the beginners, automated testing may not have any sense — they have done it already manually. Their software works and by the way tests are hard and are a waste of time. I have to point it now — <strong>writing tests isn’t a challenge if our code is written according to good practices</strong>. If our core is chaotic and doesn’t keep the good coding standards, testing it can be a serious problem. On the other hand, writing code dedicated to tests is also a mistake. You need to find a happy medium.</p><h3>Why test?</h3><p>To appreciate the value of automated tests I’ll provide you a bunch of their advantages:</p><ul><li>For the first, we ensure <strong>the code works as you expec</strong>t. Very often we can test it manually. The problem appears when manual testing becomes very time-consuming. For example, let’s take a function that as an argument data in many different formats. After changes in this function, you should test this function manually for every format. In this particular case, manual testing is, in fact, a waste of time.</li><li><strong>Tests can be additional documentation for your code.</strong> Of course, it cannot be a replacement for official documentation and documentation tools like JSDoc. However, tests can be a supplement. In a test suite, you can see what kind of data is passed to a tested method and what result is expected. In addition, every test suite should contain a description, which also could be helpful. It becomes especially useful when you need to introduce a new person to the project.</li><li><strong>Tests help to avoid regression</strong> — breaking a previously working code. It is pretty often case when a little change in one place breaks the other part of an application. Thanks to tests it is possible to detect it on a development stage. It is always to get information from tests than from a customer. You don’t have a guarantee you fully reduced the risk of regression. However, the chance of regression is significantly lower.</li><li><strong>Tests are a marketing advantage and are also proof of the quality of our product.</strong> Scrupulously tested software can be a real advantage in the software market. On the market, where you need to gain and retain customers. From the customer point of view, tests are a huge benefit. Thanks to tests, customers trust you more. It is worth to mention that tests may be a compulsory factor to make a deal with some customers.</li><li><strong>Tests help to save time for manual testers</strong>. Time is money — work time of tester isn’t cheap. Tests can reduce the time testers need to spend to fully test your software after every change. Without automated tests, manual testers need to test all details that should be covered by automated test suites.</li></ul><h3>The test pyramid</h3><p>The basic types of tests are described by a popular schema <strong>called the test pyramid</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/521/1*sYcY-2PbEtRw_8pFntKBoQ.png" /></figure><h3>Unit tests</h3><p>At the very bottom of the pyramid are <strong>unit tests</strong>. These tests are responsible for testing <strong>very small pieces of code like methods or functions</strong>. They should focus on testing this exact part of a code. That’s why all external elements e.g. repositories, controllers, etc. should be <strong>mocked</strong>. There is a reason why unit tests are at the bottom of the pyramid. In most projects, the number of unit tests is higher than the number of other kinds of tests.</p><h3>Integration tests</h3><p>The next kind of test is the <strong>integration tests</strong>. They are responsible for testing integration between components. They should verify whether the component works as we expect. There you should use the real repositories and controllers instances instead of mocks. If you want to see how valuable integration tests are, google the <em>“2 unit tests 0 integration tests”</em> phrase. You will get a bunch of funny pictures where integration tests were missing.</p><h3>End-to-end tests (e2e)</h3><p>Last but not least are <strong>end-to-end tests</strong> called also <strong>e2e</strong>. Their responsibility is to check the whole responsibilities and processes in an application. Now, you don’t care about what is a result of some function or if a function was called or not. These tests check e.g. a post was added, a comment was removed, an order changed its status and so on. These processes can be built with even hundreds of methods but <strong>e2e tests check only the final result</strong>.</p><h3>AAA pattern</h3><p>Before you write your first test it is worth learning the pattern that helps to write tests in an exact schema. For this purpose, there is a pattern called <br><strong>AAA — Arrange, Act, Assert</strong>.</p><p>This pattern assumes tests consist of three parts:</p><ol><li><strong>Arrange</strong> — in this part, you need to set up the test environment. There you should create mocks, required objects, and other needed variables and structures.</li><li><strong>Act</strong> — this part contains the test scenario. There is the actual use of the tested code.</li><li><strong>Assert</strong> — the phase responsible for checking the received result. In this step, you need to verify if the received result equals to expected result or whether a method was called or not.</li></ol><p>It is worth to avoid sequences like <strong>arrange -&gt; act -&gt; assert -&gt; act -&gt; assert</strong>. It is not a huge mistake but one test suite should cover only one test case. These sequences can be split into two separate tests.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5z7o2M8kikvrK6gnswi3ug.jpeg" /></figure><h3>Testing tools in JavaScript</h3><p>For creating tests there are a lot of useful tools. Before you write your first test it is good to get know a list of useful tools:</p><ul><li>Test runners: Mocha, Jest, Jasmine,</li><li>Assertions: Chai,</li><li>Mocks: Sinon,</li><li>Code coverage: Istanbul.</li></ul><h3>The real example</h3><p>To fully illustrate the topic of automated software testing, I’ll show you how a very simple set of unit tests can look. The first step is to create some function that will be tested:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d96bb6e394e3c7aca70fd4869a596bf6/href">https://medium.com/media/d96bb6e394e3c7aca70fd4869a596bf6/href</a></iframe><p>The function above receives two parameters and depends on the second parameter its behavior is different.</p><p>After creating a piece of code I need to test it. I have to prepare the test environment, create test suites and verify received results. To complete this step I used previously mentioned <strong>Mocha, Sinon, and Chai</strong>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3a3411b00a254dbef98485f089917617/href">https://medium.com/media/3a3411b00a254dbef98485f089917617/href</a></iframe><p>This piece of code needs a few words of explanation. In the beginning, I import needed dependencies and the tested function. Next, I create <em>describes</em><strong> </strong>— wrappers for test suites. <em>Describe()</em> can be nested — it allows to group test cases related to the same part of code.</p><h3>Before the test — beforeEach</h3><p>The next step is <em>beforeEach()</em> function. The whole code inside of this function will be invoked before every test suite for given describe. <strong>Thanks to beforeEach, the first step — arrange — is written only once</strong>. Another useful function is <em>afterEach()</em> which is invoked after every test suite. It is useful e.g. closing a connection with a database or stopping processes. There are also <em>before()</em> and <em>after()</em> functions that are invoked only once for every <em>describe()</em>.</p><p>In <em>beforeEach()</em> I created mock — <strong>the “false” function that imitates the real dependency</strong>. In this particular case, I’ll use mock a repository to check whether its method was called.</p><p>Using <em>beforeEach()</em> has also one more advantage. The mock is created anew before every test suite. If I created mock only once, I’d be able to read a result of one test in another test. It is a bad practice. Every test case should be separated and don’t have an impact on others.</p><h3>Test case — it</h3><p><strong>A further step is to define exact test suites</strong>. For this purpose, I used <em>it()</em> function. As a first argument, I provided a test case description. The second argument is a function that includes the invoked code. To fully test the function I’ve created three test cases. In my opinion, there is no need to describe in detail every test suite. Their descriptions are sufficient. <strong>That’s why the description is important</strong>. If you take a look at descriptions every description starts from <strong>“should”</strong> — it is a good practice.</p><p>If you analyze the structure of each test you will see the two elements of AAA pattern — <strong>act and assert</strong>. Firstly, the real function is invoked ( <strong>act</strong> ). Next, there is a verification of the received results and whether the function was invoked ( <strong>assert </strong>).</p><h3>Summary</h3><p>I hope, after reading this article you are a bit more familiar with automated software testing. I think the return of investment from writing tests is tremendous. It also has a positive impact on coding comfort. I encourage you to try it yourself and read the sources.</p><h3>Sources:</h3><ul><li><a href="https://www.telerik.com/products/mocking/utilize-arrange-act-assert-aaa-pattern.aspx">https://www.telerik.com/products/mocking/utilize-arrange-act-assert-aaa-pattern.aspx</a></li><li><a href="https://freecontent.manning.com/making-better-unit-tests-part-1-the-aaa-pattern">https://freecontent.manning.com/making-better-unit-tests-part-1-the-aaa-pattern</a></li><li><a href="https://jasmine.github.io/">https://jasmine.github.io</a></li><li><a href="https://mochajs.org/">https://mochajs.org</a></li><li><a href="https://jestjs.io/">https://jestjs.io</a></li><li><a href="https://www.chaijs.com/">https://www.chaijs.com</a></li><li><a href="https://sinonjs.org/">https://sinonjs.org</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2ff317bac2c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>