<?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 Emir Husic on Medium]]></title>
        <description><![CDATA[Stories by Emir Husic on Medium]]></description>
        <link>https://medium.com/@emirhusic63?source=rss-3fe5d956ad9b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*x09fo5_1ktnCgiLz.jpg</url>
            <title>Stories by Emir Husic on Medium</title>
            <link>https://medium.com/@emirhusic63?source=rss-3fe5d956ad9b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 22:31:50 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@emirhusic63/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[Automatic Software Version Bump Using GitLab CI/CD]]></title>
            <link>https://makeitnew.io/automatic-software-version-bump-using-gitlab-ci-cd-f5854a8d510c?source=rss-3fe5d956ad9b------2</link>
            <guid isPermaLink="false">https://medium.com/p/f5854a8d510c</guid>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[versioning]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Emir Husic]]></dc:creator>
            <pubDate>Mon, 07 Mar 2022 12:52:42 GMT</pubDate>
            <atom:updated>2022-03-07T12:52:42.686Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/837/1*2O5jJ_QH6DizBraGgI8c_w.png" /><figcaption>The version being bumped by a robot with a magic wand</figcaption></figure><p>Do you want your code to automatically bump a version number? <em>Automatic</em> in the sense of not having to manually edit a text file containing the version of your software.</p><p>In this blog, we’ll begin with the challenge we faced in our team with manual version bumps. The investigations we did, and the solution we implemented to solve our challenge.</p><p><strong>TLDR;</strong> we use the npm package <a href="https://github.com/conventional-changelog/standard-version">Standard-Version</a> in our GitLab pipeline to automize semantic versioning for our Java project being versioned in the build.gradle file. If you want to jump directly to the<strong> Configure version bump for Gradle</strong> section or view the configuration in <a href="https://github.com/emir-husic/semver-java-gradle"><strong>Github</strong></a>.</p><p>Tags: <a href="https://semver.org/">Semantic Versioning</a>, <a href="https://github.com/conventional-changelog/standard-version">Standard-Version</a>, Java, <a href="https://gradle.org/">Gradle</a>, Build.Gradle, <a href="https://www.conventionalcommits.org/">Conventional Commits</a>, GitLab</p><h3>The background</h3><p>For one of our applications, we used <strong>Java</strong> together with the build tool <strong>Gradle</strong>. In the project, we followed semantic versioning: Major.Minor.Patch as e.g., 1.2.3. <a href="https://semver.org/">Read more about semantic versioning</a>.</p><p>The project version was specified in a file as a version variable:</p><pre>// build.gradle <br>version = &#39;1.2.3&#39;</pre><p>Whenever a developer modified the code this file had to be updated manually to reflect a new version. However, this was easily forgotten, which resulted in new code being pushed with an old version number. Of course in our ways of working a requirement was to check if the version number had been bumped, however, it got missed, a lot. Also, the CI/CD pipeline was configured to ignore the deployment of software where the version numbers were identical to the deployed one. This meant that new software (without a version bump) never got <em>deployed</em> to our development or production servers. The software was new, but the version, however, was not, resulting in a green successful pipeline status without new software.</p><p>We realized we spent a lot of time troubleshooting why our code was working locally but not when deployed — it never got deployed! — duh!</p><p>To solve our issue, we could force the pipeline to always redeploy the binaries, and not ignore the installation of versions that are identical. Or, we could look into the issue of version bumping and possibly automize version bumps in our CI/CD pipeline. We looked into the latter.</p><p><strong>The Goal</strong></p><p>The main goal was to find a way of adding minimal overhead to the developer while at the same time solving the issue. With that said, we went for automizing it in the pipeline instead of letting the developer run standard-version locally. The reason is that we believe it&#39;s the same amount of work to remember to edit a file as having to run an extra command-line script before pushing your code.</p><h3>The Manual Task to Automize</h3><p>There were a few requirements when automizing:</p><ul><li>We still want to be able to manually bump a version number if needed</li><li>We want the software version to be marked with a prerelease tag when in a development branch: e.g., 1.1.1-feature-branch.0</li><li>When a prerelease branch is merged into master, it should automatically be bumped to a release version without the prerelease. E.g., 1.1.1</li><li>A patch (major.minor.<strong>patch</strong>) should always be bumped automatically.</li><li>The automatization should work for projects written in different languages (c#, java, javascript)</li></ul><h3>The Setup of Our Project</h3><p>In our project, we used Java with Gradle. For our CI/CD pipeline we used GitLab so the configuration will mainly be for this project, however, it can be adapted to other languages and pipelines.</p><h3>Standard-Version</h3><p>Standard-version supports semantic versioning through conventional commits. Also, it is configurable to specify variables and files where standard-version should look for a version to bump. This is great if you want to re-use your setup in different projects that may contain the version number in a different place and/or format.</p><p>What standard-version simply does is:</p><ol><li>Look through your commit history.</li><li>Modify the variables fields in the files you have specified based on (1).</li><li>Creates a commit with the changes in (2).</li></ol><h4>Pros</h4><ul><li>Supports conventional commits</li><li>Works with node projects out of the box</li><li>Configurable for other coding languages</li></ul><h4>Cons</h4><ul><li>Adds an npm package dependency to your project (if not installed globally by every developer)</li></ul><p>Example of how it looks like with standard-version being run locally:</p><figure><img alt="Screenshot of standard-version being run locally" src="https://cdn-images-1.medium.com/max/715/1*dddIOu14fUXCP6fFJa0k3A.png" /><figcaption>Figure 1: Screenshot of running standard-version locally</figcaption></figure><p>Also, it can create good looking changelog history:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/452/1*mNXcxbt_teLJJoz3zp3YcA.png" /><figcaption>Figure 2: Screenshot of CHANGELOG.md created by standard-version from the commit history</figcaption></figure><h3>Configure version bump for Gradle</h3><h4>Adding standard-version npm package</h4><p>Install the npm package:</p><pre>npm install --save standard-version</pre><p>Configure the packages.json:</p><pre>{<br>  &quot;scripts&quot;: {<br>    &quot;release&quot;: &quot;standard-version&quot;<br>  },<br>  &quot;dependencies&quot;: {<br>    &quot;standard-version&quot;: &quot;^9.3.2&quot;<br>  }<br>}</pre><h4>Configure Standard-Version for Build.Gradle</h4><p>With standard-version, it’s possible to write javascript functions that find specific files, variables and bumps the version in them. In our case, we want to bump the variable named <strong>version </strong>that exists in the build.gradle file. It looks something like the following;</p><pre>// build.gradle</pre><pre>version = &#39;139.6.16-fixsomething.3&#39;</pre><p>Also, we want to find versions in a format that matches the semantic version structure, e.g.:</p><ul><li>1.1.1</li><li>13.413.321</li><li>3.12.3-branch-name.10</li></ul><p>So we define a .versionrc.js file with the following structure:</p><pre>//.versionrc.js<br>const versionRegex = /version = &#39;(\d+.\d+.\d+(-\S+.\d+)?)&#39;/;<br>const gradleFile = &#39;build.gradle&#39;;</pre><pre>const gradleFileUpdater = {<br>    filename: gradleFile,<br>    updater: {<br>        readVersion: contents =&gt; {<br>            const match = contents.match(versionRegex);</pre><pre>if (match &amp;&amp; match[1]) {<br>                return match[1];<br>            }</pre><pre>throw Error(`Could not read version from ${gradleFile}`);<br>        },<br>        writeVersion: (contents, version) =&gt; contents.replace(versionRegex, `version = &#39;${version}&#39;`)<br>    }<br>};</pre><pre>module.exports = {<br>    header: &#39;# Changelog&#39;,<br>    types: [<br>        {<br>            type: &#39;feat&#39;,<br>            section: &#39;⚡️ Features&#39;<br>        },<br>        {<br>            type: &#39;fix&#39;,<br>            section: &#39;🐛 Bug Fixes&#39;<br>        }<br>    ],<br>    packageFiles: [gradleFileUpdater],<br>    bumpFiles: [gradleFileUpdater]<br>};</pre><p>It should now be possible to run standard-version locally, you can try it out by doing a dry run:</p><pre>npm run release -- --dry-run</pre><p>You should get similar output:</p><pre>&gt; standard-version &quot;--dry-run&quot;</pre><pre>✔ bumping version in build.gradle from 139.6.16 to 139.6.17<br>✔ created CHANGELOG.md<br>✔ outputting changes to CHANGELOG.md</pre><pre>---<br>### 139.6.17 (2022-03-01)<br>---</pre><pre>✔ committing build.gradle and CHANGELOG.md<br>✔ tagging release v139.6.17<br>ℹ Run `git push --follow-tags origin main` to publish</pre><h3>Running it in the GitLab pipeline</h3><h4>Generic GitLab user and environment variables</h4><p>Firstly, you need to have a generic user that has read and write access to your repository. let’s assume this user is called <em>versionBumper</em>.</p><blockquote>The reason for the generic user is that we need a generic user that can create version bump commits so we can differ from automatic and manual commits.</blockquote><p><a href="https://docs.gitlab.com/ee/user/profile/personal_access_tokens.html">Extract a personal access token from the user versionBumper in GitLab</a>.</p><p>Add the personal access token as an environment variable to the CI/CD pipeline for the repository.</p><p>We needed three environment variables:</p><pre>CI_GIT_URI #the uri to your git repository</pre><pre>CI_USER #in this case versionBumper</pre><pre>CI_USER_ACCESS_TOKEN #the personal access token of versionBumper</pre><h4>Configuring the gitlab-ci.yml</h4><pre>#.gitlab-ci-yml<br>variables:<br>CI_NAME: versionBumper<br>CI_EMAIL: ${CI_NAME}@company.com</pre><pre># template<br>.version_bumping: &amp;version_bumping<br>stage: version-bump<br>image: timbru31/node-alpine-git<br>#default rules<br>rules:<br>- if: &#39;$GITLAB_USER_LOGIN != $CI_NAME &amp;&amp; $CI_PIPELINE_SOURCE == &quot;merge_request_event&quot;&#39;<br>before_script:<br>- npm ci<br>- git config --global user.email $CI_EMAIL<br>- git config --global user.name $CI_NAME<br>- git config receive.advertisePushOptions true<br>- git config --global http.sslVerify false<br>- git checkout -B &quot;$CI_COMMIT_REF_NAME&quot; &quot;$CI_COMMIT_SHA&quot;<br>#default script<br>script:<br>- npm run release -- --prerelease $CI_COMMIT_REF_NAME<br>- git push https://${CI_USER}:${CI_USER_ACCESS_TOKEN}@${CI_GIT_URI} --follow-tags $CI_COMMIT_BRANCH:$CI_COMMIT_BRANCH</pre><pre>stages:<br>- version-bump</pre><pre># dev job in merge-request<br>version-bump-dev:<br>&lt;&lt;: *version_bumping</pre><pre># master job when merge-request is accepted into master<br>version-bump-master:<br>&lt;&lt;: *version_bumping<br>#override rules<br>rules:<br>- if: &#39;$GITLAB_USER_LOGIN != $CI_NAME &amp;&amp; $CI_PIPELINE_SOURCE == &quot;push&quot; &amp;&amp; $CI_BUILD_REF_NAME == &quot;master&quot;&#39;<br>#override script<br>script:<br>- npm run release<br>- git push https://${CI_USER}:${CI_USER_ACCESS_TOKEN}@${CI_GIT_URI} --follow-tags $CI_COMMIT_BRANCH:$CI_COMMIT_BRANCH</pre><h4>Explanation of the yml</h4><p>We specify variables to be able to differ from a manual commit from a developer and an automatic bump created through standard-version in the pipeline. We need this to prevent infinite version bump commits. This is reflected in the rule&#39;s condition</p><pre>$GITLAB_USER_LOGIN != $CI_NAME</pre><p>If the committer differs from versionBumper, run the version bump script, otherwise, skip.</p><p>Then we have a template for some default and shared settings to reduce duplicate code in the yml.</p><pre># template<br>.version_bumping: &amp;version_bumping<br>stage: version-bump<br>image: timbru31/node-alpine-git<br>#default rules<br>rules:<br>- if: &#39;$GITLAB_USER_LOGIN != $CI_NAME &amp;&amp; $CI_PIPELINE_SOURCE == &quot;merge_request_event&quot;&#39;<br>before_script:<br>- npm ci<br>- git config --global user.email $CI_EMAIL<br>- git config --global user.name $CI_NAME<br>- git config receive.advertisePushOptions true<br>- git config --global http.sslVerify false<br>- git checkout -B &quot;$CI_COMMIT_REF_NAME&quot; &quot;$CI_COMMIT_SHA&quot;<br>#default script<br>script:<br>- npm run release -- --prerelease $CI_COMMIT_REF_NAME<br>- git push https://${CI_USER}:${CI_USER_ACCESS_TOKEN}@${CI_GIT_URI} --follow-tags $CI_COMMIT_BRANCH:$CI_COMMIT_BRANCH</pre><p>We want the pipeline to run standard-version accordingly to our conditions. Bump the version number. File changes require a new commit, so this requires our pipeline to have access to <strong>git</strong> and <strong>node</strong>. We solved this by using a <a href="https://github.com/timbru31/docker-node-alpine-git">docker image</a> containing them both.</p><pre>image: timbru31/node-alpine-git</pre><p>Then have the two jobs that differ depending on their conditions</p><pre># dev job in merge-request<br>version-bump-dev:<br>&lt;&lt;: *version_bumping</pre><pre># master job when merge-request is accepted into master<br>version-bump-master:<br>&lt;&lt;: *version_bumping<br>#override rules<br>rules:<br>- if: &#39;$GITLAB_USER_LOGIN != $CI_NAME &amp;&amp; $CI_PIPELINE_SOURCE == &quot;push&quot; &amp;&amp; $CI_BUILD_REF_NAME == &quot;master&quot;&#39;<br>#override script<br>script:<br>- npm run release<br>- git push https://${CI_USER}:${CI_USER_ACCESS_TOKEN}@${CI_GIT_URI} --follow-tags $CI_COMMIT_BRANCH:$CI_COMMIT_BRANCH</pre><p>The first job version-bump-dev, runs the default configuration for when a development branch is being updated. Therefore we have the following condition check:</p><pre>- if: &#39;$GITLAB_USER_LOGIN != $CI_NAME &amp;&amp; $CI_PIPELINE_SOURCE == &quot;merge_request_event&quot;&#39;</pre><p>When running in the dev branch and creating an MR, the version bumps should occur accordingly to the branch name in the format of: 1.1.1-branch-name.0</p><p>So the default script is:</p><pre>- npm run release -- --prerelease $CI_COMMIT_REF_NAME</pre><p>This one creates a new version with a prerelease with the format: 1.1.1-branch-name.0</p><p>The second job, for being merged into master version-bump-master differs in the condition for running and the script. When the dev branch is merged into the master branch, we want the version to automatically be bumped from 1.1.1-branch-name.0 to 1.1.1</p><p>Condition:</p><pre>- if: &#39;$GITLAB_USER_LOGIN != $CI_NAME &amp;&amp; $CI_PIPELINE_SOURCE == &quot;push&quot; &amp;&amp; $CI_BUILD_REF_NAME == &quot;master&quot;&#39;</pre><p>Script:</p><pre>- npm run release</pre><p>This standard script releases a sharp version and this is why we call it when a merge request has been accepted. <a href="https://docs.gitlab.com/ee/ci/variables/predefined_variables.html">Read more about GitLab Predefined Variables</a>.</p><p>Before Script:</p><pre>before_script:<br>- npm ci<br>- git config --global user.email $CI_EMAIL<br>- git config --global user.name $CI_NAME<br>- git config receive.advertisePushOptions true<br>- git config --global http.sslVerify false<br>- git checkout -B &quot;$CI_COMMIT_REF_NAME&quot; &quot;$CI_COMMIT_SHA&quot;</pre><p>Here we install our npm package dependencies (standard-version). Then we set some git configurations to be able to fetch and push to our repository using the <em>generic</em> git user (versionBumper).</p><h3>Discussions</h3><p>There are different ways of solving the specific problem, however, something to simplify the workday of a developer automizing the patch version bump saved a lot of time for our case. It turns out standard-version is configurable in a team where you work with different languages or multiple stacks it’s beneficial of having the same way of working when handling version bumps.</p><p>Through the way, we also realized if this was automated, we could expand the usage of the software version. For a front-end project, we could e.g., set a variable that shows the version number at the bottom of the page — :)</p><h4>Drawbacks:</h4><ul><li>Requires the project to have an npm package as part of the project.</li><li>Requires a generic git user for version bump commits.</li></ul><h4>Benefits:</h4><ul><li>Automatic versioning bumping in the CI/CD pipeline</li><li>Major/Minor/Patch bumps can be specified in the commit tags by following conventional commits.</li><li>Manual bumping and verification are still available.</li><li>Can be reused in different projects not dependent on the programming language.</li></ul><h3>Conclusion</h3><p>Most things can be automized, however, you have to think about if everything should be automized or if you should discuss your ways of working and try to automize things that can simplify your work. In our case, this solved two issues:</p><ol><li>We could spend less time thinking about manually editing a version number in a file.</li><li>We will save time on not troubleshooting why our code is not working in production for cases where we forgot to bump the version number.</li></ol><h3>Relative Links</h3><p><a href="https://github.com/emir-husic/semver-java-gradle">https://github.com/emir-husic/semver-java-gradle</a></p><p><a href="https://dwmkerr.com/conventional-commits-and-semantic-versioning-for-java/">https://dwmkerr.com/conventional-commits-and-semantic-versioning-for-java/</a></p><p><a href="https://github.com/conventional-changelog/standard-version">https://github.com/conventional-changelog/standard-version</a></p><p><a href="https://semver.org/">https://semver.org/</a></p><p><a href="https://gradle.org/">https://gradle.org/</a></p><p><a href="https://www.conventionalcommits.org/">https://www.conventionalcommits.org/</a></p><p><a href="https://docs.gitlab.com/ee/user/profile/personal_access_tokens.html">https://docs.gitlab.com/ee/user/profile/personal_access_tokens.html</a></p><p><a href="https://github.com/timbru31/docker-node-alpine-git">https://github.com/timbru31/docker-node-alpine-git</a></p><p><a href="https://docs.gitlab.com/ee/ci/variables/predefined_variables.html">https://docs.gitlab.com/ee/ci/variables/predefined_variables.html</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f5854a8d510c" width="1" height="1" alt=""><hr><p><a href="https://makeitnew.io/automatic-software-version-bump-using-gitlab-ci-cd-f5854a8d510c">Automatic Software Version Bump Using GitLab CI/CD</a> was originally published in <a href="https://makeitnew.io/">Make It New</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[N-Layer Architecture In A Multi-Project Solution]]></title>
            <link>https://makeitnew.io/n-layer-architecture-in-a-multi-project-solution-d72604f0e030?source=rss-3fe5d956ad9b------2</link>
            <guid isPermaLink="false">https://medium.com/p/d72604f0e030</guid>
            <category><![CDATA[dependency-injection]]></category>
            <category><![CDATA[multi-project-di]]></category>
            <category><![CDATA[layer-n]]></category>
            <category><![CDATA[n-tiers]]></category>
            <category><![CDATA[dependency-inversion]]></category>
            <dc:creator><![CDATA[Emir Husic]]></dc:creator>
            <pubDate>Wed, 24 Nov 2021 07:23:07 GMT</pubDate>
            <atom:updated>2021-11-24T07:23:07.719Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/924/1*6YipWW2dvrBu0stznytXcw.png" /></figure><p>What is N-Layer architecture? How to apply it to a dotnet core ASP.NET application? In this article, C# is used, however, the concept is not platform nor language dependant. We tried to apply the concept of a three-layer architecture and encountered questions that are presented in this article. We discuss our findings and state the pros and cons of implementing the architecture. The goal is to simplify the process and understand how to concretely implement it in a project. In this article, to achieve an N-layer architecture we split a single project solution into a multi-project solution together with the use of <a href="https://en.wikipedia.org/wiki/Dependency_inversion_principle#Dependency_inversion_pattern"><strong>Dependency Inversion</strong></a><strong> </strong>and<strong> </strong><a href="https://docs.microsoft.com/en-us/dotnet/core/extensions/dependency-injection"><strong>Dependency Injection</strong></a><strong>.</strong></p><h3>What is N Layer Architecture</h3><p>N-Layer (also called N-Tier) architecture enables the separation of functionality both physically and logically. The <em>N</em> stands for the number of layers the architecture consists of.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/562/1*bliMd-GaC_A3UgufUNaRfw.png" /><figcaption>Figure 1</figcaption></figure><ol><li><strong>REST API — </strong>handles the API calls from e.g., a user.</li><li><strong>Service layer — </strong>handles specific service call implementations.</li><li><strong>Data Layer — </strong>handles data call implementations, e.g., MYSQL, MongoDB, etc…</li></ol><blockquote>To avoid <a href="https://en.wikipedia.org/wiki/Circular_dependency"><strong>circular dependencies</strong></a> layers should only be able to depend on layers directly next to them</blockquote><p>Figure 1 consists of three layers, therefore, this represents a three-layer architecture. We see a separation in logic and responsibility for each layer. To avoid <a href="https://en.wikipedia.org/wiki/Circular_dependency"><strong>circular dependencies</strong></a> layers should only be able to depend on layers directly next to them. Observing figure 1 (with three layers), the API layer (layer one) should not be able to directly reference the data layer (layer three) — It should go in a sequence. The API layer may reference the service layer, which in turn, references the data layer.</p><p>It is possible to go even further to physically divide the functionality so that one layer may be deployed independently of another as for micro-services, however, this is a different topic and will not be discussed in this article.</p><h3>So… How to apply it in in code?</h3><p>Firstly, assume the following code project structure for a Quiz program:</p><pre>Quiz<br>│   README.md<br>│   Quiz.sln<br>│<br>└───Quiz.Api<br>│       QuestionsController.cs<br>│       Startup.cs<br>│<br>└───Quiz.Services<br>│       QuestionsService.cs<br>│<br>└───Quiz.Data<br>        QuestionRepository.cs</pre><p>In the above structure, the possible <em>layers</em> have already been separated by being moved into separate projects, but we could as well have started with a single project having all classes in the<strong> Quiz.Api.</strong></p><p>Let us assume the project <strong>Quiz.Api</strong> has a simple <strong>QuestionsController</strong> with a GET endpoint/questions that, in turn, calls the Q<strong>uestionService </strong>which calls the <strong>QuestionRepository </strong>that is responsible for accessing a database and fetching the stored questions.</p><p>The first question to answer is:</p><blockquote><em>where should the concrete class be defined with a </em><em>newclass object</em>?</blockquote><p>Each layer may have the responsibility for creating the next layer. An example:</p><ol><li>The API Layer declares new QuestionsService()</li><li>The Service layer declares new QuestionRepository()</li></ol><p>However, to reduce coupling we introduced <a href="https://en.wikipedia.org/wiki/Dependency_inversion_principle#Dependency_inversion_pattern"><strong>Dependency Inversion</strong></a> to pass down an interface class to the next layer. This makes the class independent of the actual implementation, it only expects the class to be passed to its constructor. So now, the API layer is responsible to pass down a repository to the service class.</p><ol><li>The API Layer declares <br>new QuestionsService(IQuestionRepository)</li></ol><p>But how can the service know which database to use when we pass down an interface? We need to instantiate the database before we pass it down, right?</p><pre>//QuestionsController.cs</pre><pre>IQuestionRepository db = new QuestionRepository();<br>IQuestionsService service = new QuestionsService(db);</pre><p>This means that The QuestionsController needs to reference IQuestionRepository, QuestionRepository, IQuestionsService, QuestionsService . And this is inevitable because somewhere the concrete class needs to be declared.</p><p>However, using <a href="https://en.wikipedia.org/wiki/Dependency_inversion_principle#Dependency_inversion_pattern"><strong>Dependency Inversion</strong></a><strong> </strong>and<strong> </strong><a href="https://makingloops.com/the-stairway-pattern/#the-stairway-pattern"><strong>The Stairway Pattern</strong></a> we can simplify our code further.</p><h4>The Stairway Pattern</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/781/1*P-PwyXG8gY9mI1rymdRstw.png" /><figcaption>Figure 2: The stairway pattern</figcaption></figure><p>We can implement it using <a href="https://makingloops.com/the-stairway-pattern/#the-stairway-pattern"><strong>stairway patter</strong></a><strong> </strong>(so-called due to the looks of a stairway). Here we let each layer depend on the abstraction (interface) of the next layer and the behavior is then implemented through the actual class.</p><p>Each step also represents one unique layer. The diagram is modified to clarify where the <em>original</em> class <em>could</em> be instantiated, therefore each layer has a reference to both the interface class and the implementing class.</p><p>We begin with breaking out the code to different projects/folders. One project for the start point, in this case, the API. Then two projects per layer where one represents all the service interfaces and one for all service implementations, the same applies to the data layer.</p><p>For a project structure in C# we get the following folder structure (notice changes in bold):</p><pre>Quiz<br>│   README.md<br>│   Quiz.sln<br>│<br>└───Quiz.Api<br>│       QuestionsController.cs<br>│       Startup.cs     <br>│   <br>└───<strong>Quiz.Service.Interfaces</strong><br>│       <strong>IQuestionsService.cs</strong><br>│   <br>└───Quiz.Services<br>│       QuestionsService.cs<br>│<br>└───<strong>Quiz.Data.Interfaces</strong><br>│       <strong>IQuestionRepository.cs</strong><br>│   <br>└───Quiz.Data<br>        QuestionRepository.cs</pre><p>Instead of declaring an instance every time, we will use Dependency Injection to declare it once in our startup.cs which will be responsible for the concrete class.</p><pre>// This method gets called by the runtime. Use this method to add services to the container.<br> public void ConfigureServices(IServiceCollection services)<br> {<br>     services.AddScoped&lt;IQuestionsService, QuestionsService&gt;();<br>     services.AddScoped&lt;IQuestionRepository, QuestionRepository&gt;();<br>     services.AddControllers();<br> }</pre><p>In this case, the API project still has a reference to all other projects because Startup.cs needs to import all the projects to be able to declare them for the dependency injection.</p><h4>Moving the startup configuration to each project</h4><p>We may move the responsibility to each layer by having a configuration file in each project. With a sequence of Startup.cs -&gt; ServiceConfiguration.cs -&gt; RepositoryConfiguration.cs we can remove references from the API project and let each project only refer to layers below. Observe the following structure:</p><pre>Quiz<br>│   README.md<br>│   Quiz.sln<br>│<br>└───Quiz.Api<br>│       QuestionsController.cs<br>│       Startup.cs     <br>│   <br>└───Quiz.Service.Interfaces<br>│       IQuestionsService.cs<br>│  <br>└───Quiz.Services<br>│       QuestionsService.cs<br>│       <strong>ServiceConfiguration.cs </strong><br>│<br>└───Quiz.Data.Interfaces<br>│       IQuestionRepository.cs<br>│   <br>└───Quiz.Data<br>        QuestionRepository.cs<br>        <strong>DataConfiguration.cs</strong></pre><p>This is how the startup configuration will look like for each project:</p><p><strong>API project</strong> — Startup.cs with a reference to Quiz.Services &amp; Quiz.Service.Interfaces projects.</p><pre>//Startup.cs<br> public void ConfigureServices(IServiceCollection services)<br> {<br>    <strong>services.AddServiceDependencies(Configuration);</strong><br>    services.AddScoped&lt;IQuestionsService, QuestionsService&gt;();<br>    services.AddControllers();<br> }</pre><p><strong>Service project</strong> — ServiceDependencies.cs with a reference to Quiz.Repositories&amp; Quiz.Repository.Interfaces</p><pre>//ServiceDependencies.cs<br>public static IServiceCollection AddServicesDependencies(this IServiceCollection services, IConfiguration configuration)<br>{<br>    <strong>services.AddRepositoryDependencies(configuration);</strong><br>    services.AddScoped&lt;IQuestionRepository, QuestionRepository&gt;();<br>    return services;<br>}</pre><p><strong>Data project — </strong>Last layer, so no more dependencies, however, a configuration, for example, a database can be needed from an external dependency, therefore, we need a configuration file to represent these injections. Here we use MySql with the connection string passed from <strong>appsettings.json.</strong></p><pre>//appsettings.json<br>{<br>  “Logging”: {<br>  “LogLevel”: {<br>  “Default”: “Information”,<br>  “Microsoft”: “Warning”,<br>  “Microsoft.Hosting.Lifetime”: “Information”<br> }<br> },<br>   “AllowedHosts”: “*”,<br>   “ConnectionStrings”: {<br>   “Database”: “Server = db;<br>                port = 3306;<br>                database = quiz_db;<br>                user = quiz_user;<br>                password = quiz_password;<br>                Persist Security Info = false;<br>                Connect Timeout = 300”<br> }<br>}</pre><pre>//RepositoryDependencies.cs<br>public static IServiceCollection AddMyClasses(this IServiceCollection services, IConfiguration configuration)<br>{<br>    <strong>services.AddDbContext&lt;QuizContext&gt;(<br>    options =&gt;<br>    {<br>        string V = configuration.GetConnectionString(&quot;Database&quot;);<br>        options.UseMySql(V, ServerVersion.AutoDetect(V));<br>    });</strong></pre><pre>     return services;<br>}</pre><p><strong>What if we want to have a DTO (Data Transfer Object) that is being shared from the repository to the API?</strong></p><p>Objects that are <em>common</em> or <em>shared </em>across different layers can be packed in a separate project. This way, changes to DTO are only done in one place to avoid circular dependencies by not allowing the common project to have bi-directional dependencies. Hence, the layers may refer to the common project but not the other way around, notice the blue dotted lines in figure 3.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/809/1*2uXN37jj3I8CKqRHTFF82A.png" /><figcaption>Figure 3: Dependencies in Stairway Pattern with a common project</figcaption></figure><h3>Discussion</h3><h4>Cleaner Code</h4><p>It gets easier to work with the code by being able to choose one layer to look into and handling one responsibility one layer at a time. The dependency configuration with dependency injection and dependency inversion simplifies future replacements in the layers. E.g., to change the repository implementation, you create a new concrete class that implements the interface and change one row in the service configuration to make sure it uses the new implementation.</p><pre>// OLD repository<br>// services.AddScoped&lt;IQuestionRepository, QuestionRepository&gt;();<br>// new Improved repository<br><strong>services.AddScoped&lt;IQuestionRepository,<br>                   ImprovedQuestionRepository&gt;();</strong></pre><h4>Unit Testing</h4><p>Think of <a href="https://devopedia.org/mock-testing"><strong>mock testing</strong></a>, imagine you want to test a single API call that calls a service class and also does a database call. Testing would require a mock of the service and the database. However, if we split them up into layers, the API only references the service layer, hence, only the service layer needs to be mocked for testing the API. The same is applied when testing services, only the database layer needs to be mocked.</p><h4>Pros</h4><p>+ Code readability.<br>+ No Cirucular Dependencies<br>+ Easier to write unit tests<br>+ Single responsibility</p><h4>Cons</h4><p>- May make deployment more difficult since you have multiple projects instead of a single one.</p><h3>Conclusion</h3><p>So what do we gain from this? We get an improved code structure as well with no circular dependencies. It is also easier to get an overview of the code since you now both have the responsibilities divided into layers and interfaces. It gets easier to replace concrete code implementations with new ones by simply editing the start-up configurations. Also, it is easier to write <a href="https://www.tutorialspoint.com/software_testing_dictionary/unit_testing.htm"><strong>Unit tests</strong></a><strong> </strong>for each layer<strong> </strong>since each layer only requires one layer of dependency to test the specific layer.</p><h3>Source Code</h3><p>The source code can be found <strong>@</strong> <a href="https://github.com/emir-husic/n-layer-dotnet">GitHub</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d72604f0e030" width="1" height="1" alt=""><hr><p><a href="https://makeitnew.io/n-layer-architecture-in-a-multi-project-solution-d72604f0e030">N-Layer Architecture In A Multi-Project Solution</a> was originally published in <a href="https://makeitnew.io/">Make It New</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[An Example of Why You Should Write Tests For Bugs Before Fixing The Problem]]></title>
            <link>https://makeitnew.io/an-example-of-why-you-should-write-tests-for-bugs-before-fixing-the-problem-459776d4a4c1?source=rss-3fe5d956ad9b------2</link>
            <guid isPermaLink="false">https://medium.com/p/459776d4a4c1</guid>
            <category><![CDATA[coding-test]]></category>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[bugs]]></category>
            <category><![CDATA[testing]]></category>
            <dc:creator><![CDATA[Emir Husic]]></dc:creator>
            <pubDate>Wed, 02 Oct 2019 13:29:49 GMT</pubDate>
            <atom:updated>2021-11-05T10:15:54.017Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/759/1*XqT0WlZby5btBkhafBNZtw.png" /></figure><p>Many are familiar with the importance of tests and how they successively decrease the amounts of bugs being pushed to production. However, more often than not, developers dedicate themselves to writing solutions to bugs and rapidly push a new version of the code to production — without writing a test case in the test suite for the bug. If you ask them about it, they probably didn’t have time to do it or will do it later. I will describe a scenario to show why it&#39;s important to write tests for bugs and add them to the test suite.</p><h3>An E-commerce Website</h3><p>Imagine you work as a full-stack developer on a basic math quiz website. The user receives math questions, supplies his answers, the website marks the quiz and returns the number of correct results. In the back-end, you have a SQL database where you (using your favorite language) implement a REST-API which may fetch data from the DB.</p><p>The DB has the following tables:</p><pre><strong>CREATE TABLE</strong> Questions (<br> QuestionID int,<br> Value varchar(255),<br><strong> PRIMARY KEY</strong> (QuestionID)<br> )<br>            <br> <strong>CREATE TABLE</strong> Answers (<br> QuestionID int,<br> Answer int<br> );</pre><p>The back-end has two endpoints:</p><p>1. Fetch questions.<br>2. Post answers.</p><p>Example:</p><pre> GET /questions<br> Returns a JSON array with questions:<br> [<br>     {   <br>         “QuestionID”: 1,<br>         “Value”: “What is 2 + 2?”<br>     }<br> ]</pre><pre> POST /answers<br> Expects a JSON array:<br> [<br>     {<br>         “QuestionID”: 1,<br>         “Answer”: 4<br>     }<br> ]</pre><p>There is an Exam class that takes a DB in the constructor and implements two functions, one to mark an exam and one to fetch the questions from a database.</p><pre><strong> Class Exam</strong><br> {<br>     <strong>private</strong> Database db;<br>     <strong>Constructor</strong>(Database db){<br>         this.db = db;<br>     }<br>     <strong>public </strong>array GetQuesstions(){<br>         return db.getQuestions();<br>     }<br>     <strong>public </strong>int MarkExam(array examanswers){<br>         // compare answers to our db answers.<br>         // return exam result.<br> }</pre><p>You write unit tests for the exam class using a mock database. The mock database returns the previously mentioned <em>expected</em> values and we confirm the behavior of the <strong>MarkExam</strong> function through unit tests. We run the tests,<br>all tests pass, we feel confident and push the code to production. However, it turns out (in production) that the call to <strong>GetQuestions</strong> on the real database returns a JSON array where the ID:s are set as strings instead of integers:</p><pre>GET /questions<br>Returns a JSON array with questions:<br>[<br>    {<br>        “QuestionID”: “1”,<br>        “Value”: “What is 2 + 2?”<br>    }<br>]</pre><p>If not explicitly converted to an int (in the application using the API) the back-end may receive a JSON array in the POST endpoint looking like this:</p><pre> POST /answers<br> Expects a JSON array:<br> [<br>     {<br>         “QuestionID”: “1”,<br>         “Answer”: 4<br>     }<br> ]</pre><p>In our case, the <strong>MarkExam</strong> function extracts the value from the JSON object without explicitly converting it to an int, therefore, the code performs a comparison on the following objects:</p><pre> POST by an application<br> [<br>     {<br>         “QuestionID”: “1”,<br>         “Answer”: 4<br>     }<br> ]<br> Returned from DB<br> [<br>     {<br>         “QuestionID”: “1”,<br>         “Answer”: “4”<br>     }<br> ]</pre><p>The question ID:s will match, however, the answers will not, this is because there is a comparison of “1” to 1. Therefore, we have a bug in our production code.</p><h3>Scenario 1</h3><p>You decide to fix the bug and explicitly convert the ID:s fetched from the database to integers.</p><pre>// BEFORE<br> return <br>     {<br>         “QuestionID”: $questionID,<br>         “Answer”: $answer<br>     }</pre><pre>// AFTER<br> return <br>     {<br>         “QuestionID”: (int) $questionID,<br>         “Answer”: (int) $answer<br>     }</pre><p>You run your unit tests, everything looks fine. You push to production. The code works.</p><p>100 days later…</p><p>Bob checks out the code and realizes the DB specifies ID:s as integers and decides it’s therefore unnecessary to have an explicit conversion. Bob changes the code back to how it was previously:</p><pre>return <br>     {<br>         “QuestionID”: $questionID,<br>         “Answer”: $answer<br>     }</pre><p>Bob runs the unit tests, everything looks fine. Bob (<em>unknowingly</em>) pushes broken code to production. We got the same bug in the production as in the beginning, no one will be able to pass a quiz on the website since the <strong>MarkExam</strong> function won’t correctly calculate the results.</p><h3>Scenario 2</h3><p>You decide to fix the bug and explicitly convert the values fetched from the database to integers. Before you begin with your fix, you decide to write a test case that explicitly posts an answer where the answer field is an integer. You now run the tests and see that they fail. Now you go to your code and fix the problem.</p><pre>return <br>     {    <br>         “QuestionID”: (int) $questionID,<br>         “Answer”: (int) $answer<br>     }</pre><p>You run your unit tests, everything seems fine. You push to production. Everything works.</p><p>100 days later….</p><p>Bob checks out the code and realizes the DB specifies ID:s as integers and decides it’s therefore unnecessary to have an explicit conversion. Bob changes the code back to how it was previously:</p><pre>return <br>     {<br>         “QuestionID”: $questionID,<br>         “Answer”: $answer<br>     }</pre><p>Bob runs the tests, the tests FAIL. Bob reverts the changes and does not push breaking code to production.</p><h3>Merge Conflicts</h3><p>Working with systems where several developers are involved a bug fix may disappear due to a human error — by simply choosing the wrong side of a merge in a merge conflict. Sometimes an error is corrected by simply editing one line, and even, one value at that line of code. Running the test suite after a merge rapidly informs that there is an error in the code.</p><h3>Conclusion</h3><p>Tests may act as documentation to the software; it describes how it works and increase’s the degree of confidence that it works. Don’t forget to begin with writing a test case that simulates the bug, it significantly decreases the chance for the bug to <em>magically </em>appear again.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=459776d4a4c1" width="1" height="1" alt=""><hr><p><a href="https://makeitnew.io/an-example-of-why-you-should-write-tests-for-bugs-before-fixing-the-problem-459776d4a4c1">An Example of Why You Should Write Tests For Bugs Before Fixing The Problem</a> was originally published in <a href="https://makeitnew.io/">Make It New</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>