<?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 Amirhosein Gharaati on Medium]]></title>
        <description><![CDATA[Stories by Amirhosein Gharaati on Medium]]></description>
        <link>https://medium.com/@AG1380?source=rss-10919b3a8296------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*0esXHeJ7AmeXJy1lLFM9gg.jpeg</url>
            <title>Stories by Amirhosein Gharaati on Medium</title>
            <link>https://medium.com/@AG1380?source=rss-10919b3a8296------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 07:47:14 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@AG1380/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[Continuous Integration in Action with GitLab]]></title>
            <link>https://blog.stackademic.com/continuous-integration-in-action-with-gitlab-7c9f28e2283a?source=rss-10919b3a8296------2</link>
            <guid isPermaLink="false">https://medium.com/p/7c9f28e2283a</guid>
            <category><![CDATA[gitlab-ci]]></category>
            <category><![CDATA[gitlab]]></category>
            <category><![CDATA[continuous-integration]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Amirhosein Gharaati]]></dc:creator>
            <pubDate>Mon, 06 Oct 2025 05:51:47 GMT</pubDate>
            <atom:updated>2025-10-06T05:51:47.329Z</atom:updated>
            <content:encoded><![CDATA[<p>Continuous Integration (CI) is one of those buzzwords every developer hears early on — but what does it really mean? And how does <strong>GitLab CI</strong> help us automate and improve our development workflow? Let’s break it down in simple terms.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7gCKN2uPepUJTrCd6ChxxQ.png" /></figure><h3>What is CI/CD?</h3><p><strong>CI/CD</strong> stands for <strong>Continuous Integration</strong> and <strong>Continuous Deployment</strong>.</p><p>It <strong>falls under DevOps</strong> (the joining of development and operations teams) and combines the <strong>practices of continuous integration and continuous delivery</strong>.</p><p>CI/CD <strong>automates</strong> much or all of the manual human intervention traditionally needed to get new code from a commit into production, encompassing the <strong>build, test, and deploy phases, as well as infrastructure provisioning.</strong></p><h3>More About CI</h3><p>Continuous integration involves <strong>automating builds, executing tests, and merging code</strong> from individual developers into a shared repository.</p><p>The primary goal of continuous integration is to efficiently <strong>integrate source code into shared repositories</strong>.</p><p>Once changes are committed to the version control system, automated builds and test cases are executed to ensure the functionality and validity of the code.</p><h3>CI Tools</h3><p>There are many CI/CD tools available today — like <strong>Jenkins</strong>, <strong>GitHub Actions</strong>, <strong>CircleCI</strong>, and <strong>GitLab CI</strong>.<br>Each tool connects to your code repository, watches for changes, and runs a pipeline to test or deploy your app.</p><p>We’ll focus on <strong>GitLab CI</strong>, since it’s built right into the GitLab platform.</p><h3>What is GitLab?</h3><p><strong>GitLab</strong> is an all-in-one DevOps platform that includes:</p><ul><li>Git repository hosting (like GitHub)</li><li>Built-in CI/CD pipelines</li><li>Issue tracking</li><li>Container registry</li><li>Deployment management</li></ul><p>You don’t need to install anything extra — CI/CD is ready to go as soon as you create a repo.</p><h3>Example: CI/CD for a Python Project</h3><p>Imagine you have a simple Python app in a GitLab repository.</p><h4>Pipeline</h4><blockquote>A <strong>pipeline</strong> is a series of <strong>jobs</strong> that run in stages.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_ZfauBuj5oY5XJTN.png" /></figure><p>To setup GitLab pipeline, create a file named <strong>.gitlab-ci.yml</strong> in the root of your project.</p><h4>Job</h4><blockquote>A <strong>job</strong> is a single task in your pipeline — like running tests or deploying the app.</blockquote><p>Jobs run inside isolated environments (called <em>runners</em>), often using Docker images such as python:3.11.</p><p>We will build a simple pipeline with three jobs:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c5RI-xsvaX3YD21k3eGsVw.png" /></figure><p>Here’s a simple example starting with lint_job:</p><pre>stages:<br>  - lint<br><br>lint_job:<br>  image: ghcr.io/astral-sh/ruff:0.12.9-alpine<br>  stage: lint<br>  script:<br>    - ruff check</pre><p><em>ruff is a fast Python linter that checks for code style and formatting issues.</em></p><p>This job runs first in the pipeline to catch problems early.</p><p>Now, let’s add a test_job:</p><pre>stages:<br>  - lint<br>  - test<br><br>lint_job:<br>  image: ghcr.io/astral-sh/ruff:0.12.9-alpine<br>  stage: lint<br>  script:<br>    - ruff check<br><br>test_job:<br>  stage: test<br>  image: python:3.11<br>  script:<br>    - pip install -r requirements.txt<br>    - pip install pytest<br>    - pytest</pre><p><em>This pipeline runs your lint and tests every time you push code.</em></p><p>Here each lint_job and test_job will <strong>run in an isolated environment using docker</strong> with their specified docker images.</p><p>Then in script section, the commands will run in order. In the example in test_job, first we want to install the requirements, pytest tool, and then run the tests using pytest.</p><h4>Variables</h4><blockquote><strong>Variables</strong> store values you want to reuse, like secrets or configurations.</blockquote><p>You can define them in .gitlab-ci.yml or in the GitLab UI.</p><p>For example you may need to set ENV variable in your tests:</p><pre>test_job:<br>  stage: test<br>  image: python:3.11<br><br>  variables:<br>    ENV: &quot;test&quot;<br>  <br>  script:<br>    - pip install -r requirements.txt<br>    - pip install pytest<br>    - pytest</pre><h4>Rules</h4><blockquote><strong>Rules</strong> control <em>when</em> a job runs.</blockquote><p>Assume we might need to run tests <strong>only</strong> when:</p><ul><li>a merge request is created, or</li><li>a commit is added to the develop branch.</li></ul><pre>test_job:<br>  stage: test<br>  image: python:3.11<br><br>  variables:<br>    ENV: &quot;test&quot;<br>  <br>  script:<br>    - pip install -r requirements.txt<br>    - pip install pytest<br>    - pytest<br><br>  rules:<br>    - if: &#39;$CI_PIPELINE_SOURCE == &quot;merge_request_event&quot;&#39;<br>    - if: &#39;$CI_COMMIT_BRANCH == &quot;develop&quot;&#39;</pre><h4>Artifacts</h4><blockquote><strong>Artifacts</strong> are files generated by a job that you want to keep for later.</blockquote><p>If you use the pytest-cov plugin, you can generate a coverage report and store it as an artifact:</p><pre>test_job:<br>  stage: test<br>  image: python:3.11<br><br>  variables:<br>    ENV: &quot;test&quot;<br>  <br>  script:<br>    - pip install -r requirements.txt<br>    - pip install pytest pytest-cov<br>    - pytest --cov=app --cov-report=html:coverage_html<br>    <br>  artifacts:<br>    paths:<br>      - coverage_html/<br>    expire_in: 1 week<br><br>  rules:<br>    - if: &#39;$CI_PIPELINE_SOURCE == &quot;merge_request_event&quot;&#39;<br>    - if: &#39;$CI_COMMIT_BRANCH == &quot;develop&quot;&#39;</pre><h4>Manual Job</h4><blockquote>A <strong>manual job</strong> is a job that doesn’t run automatically — it waits for someone to trigger it in the GitLab UI.</blockquote><p>For example, once your tests pass, you might want to manually trigger an AI-based review using an <strong>n8n workflow</strong>:</p><pre>stages:<br>  - lint<br>  - test<br>  - review<br><br>lint_job:<br>  ...<br><br>test_job:<br>  ...<br><br>ai_review_job:<br>  stage: review<br>  image: curlimages/curl:latest<br>  script:<br>    - |<br>      curl -X POST https://DOMAIN.app.n8n.cloud/webhook-test/SOME-ID \<br>           -H &quot;Content-Type: application/json&quot; \<br>           -d &#39;{<br>                 &quot;project&quot;: {<br>                   &quot;path_with_namespace&quot;: &quot;&#39;$CI_PROJECT_PATH&#39;&quot;<br>                 },<br>                 &quot;object_attributes&quot;: {<br>                   &quot;iid&quot;: &quot;&#39;$CI_MERGE_REQUEST_IID&#39;&quot;<br>                 }<br>               }&#39;<br>  rules:<br>    - if: &#39;$CI_PIPELINE_SOURCE == &quot;merge_request_event&quot;&#39;<br>      when: manual</pre><p><em>The script will send a POST request to the n8n webhook URL to trigger a workflow.</em></p><p>Here is the full pipeline with three lint, test and AI review job:</p><pre>stages:<br>  - lint<br>  - test<br>  - review<br><br>lint_job:<br>  image: ghcr.io/astral-sh/ruff:0.12.9-alpine<br>  stage: lint<br>  script:<br>    - ruff check<br><br>test_job:<br>  stage: test<br>  image: python:3.11<br><br>  variables:<br>    ENV: &quot;test&quot;<br>  <br>  script:<br>    - pip install -r requirements.txt<br>    - pip install pytest pytest-cov<br>    - pytest --cov=app --cov-report=html:coverage_html<br>    <br>  artifacts:<br>    paths:<br>      - coverage_html/<br>    expire_in: 1 week<br><br>  rules:<br>    - if: &#39;$CI_PIPELINE_SOURCE == &quot;merge_request_event&quot;&#39;<br>    - if: &#39;$CI_COMMIT_BRANCH == &quot;develop&quot;&#39;<br><br>ai_review_job:<br>  stage: review<br>  image: curlimages/curl:latest<br>  script:<br>    - |<br>      curl -X POST https://DOMAIN.app.n8n.cloud/webhook-test/SOME-ID \<br>           -H &quot;Content-Type: application/json&quot; \<br>           -d &#39;{<br>                 &quot;project&quot;: {<br>                   &quot;path_with_namespace&quot;: &quot;&#39;$CI_PROJECT_PATH&#39;&quot;<br>                 },<br>                 &quot;object_attributes&quot;: {<br>                   &quot;iid&quot;: &quot;&#39;$CI_MERGE_REQUEST_IID&#39;&quot;<br>                 }<br>               }&#39;<br>  rules:<br>    - if: &#39;$CI_PIPELINE_SOURCE == &quot;merge_request_event&quot;&#39;<br>      when: manual</pre><h3>Takeaway</h3><p>In a simple Python project, we’ve built a complete GitLab CI/CD pipeline that includes:</p><ul><li><strong>Linting</strong> with ruff</li><li><strong>Testing</strong> with pytest and pytest-cov</li><li><strong>Variables</strong> for configuration</li><li><strong>Rules</strong> to control when jobs run</li><li><strong>Artifacts</strong> to save reports</li><li><strong>Manual jobs</strong> for human-triggered workflows</li></ul><p>Start small — run your linter and tests automatically.<br>Then extend your pipeline with deploy or AI-review stages as your project grows.</p><blockquote>Automation doesn’t just save time — it builds confidence in your code. 🚀</blockquote><h3>GitLab Docs</h3><ul><li><strong>Getting Started</strong>: <a href="https://docs.gitlab.com/ci/">https://docs.gitlab.com/ci/</a><br><strong>Pipelines</strong>: <a href="https://docs.gitlab.com/ee/ci/pipelines/">https://docs.gitlab.com/ee/ci/pipelines/</a></li><li><strong>Pipeline Architectures</strong>: <a href="https://docs.gitlab.com/ci/pipelines/pipeline_architectures/">https://docs.gitlab.com/ci/pipelines/pipeline_architectures/</a></li><li><strong>Job</strong>: <a href="https://docs.gitlab.com/ci/jobs">https://docs.gitlab.com/ci/jobs</a></li><li><strong>Variables</strong>: <a href="https://docs.gitlab.com/ee/ci/variables/">https://docs.gitlab.com/ee/ci/variables/</a></li><li><strong>Predefined Variables</strong>: <a href="https://docs.gitlab.com/ci/variables/predefined_variables/">https://docs.gitlab.com/ci/variables/predefined_variables/</a></li><li><strong>Rules</strong>: <a href="https://docs.gitlab.com/ee/ci/jobs/job_rules.html">https://docs.gitlab.com/ee/ci/jobs/job_rules.html</a></li></ul><h3>A message from our Founder</h3><p><strong>Hey, </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>Sunil</strong></a><strong> here.</strong> I wanted to take a moment to thank you for reading until the end and for being a part of this community.</p><p>Did you know that our team run these publications as a volunteer effort to over 3.5m monthly readers? <strong>We don’t receive any funding, we do this to support the community. ❤️</strong></p><p>If you want to show some love, please take a moment to <strong>follow me on </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>LinkedIn</strong></a><strong>, </strong><a href="https://tiktok.com/@messyfounder"><strong>TikTok</strong></a>, <a href="https://instagram.com/sunilsandhu"><strong>Instagram</strong></a>. You can also subscribe to our <a href="https://newsletter.plainenglish.io/"><strong>weekly newsletter</strong></a>.</p><p>And before you go, don’t forget to <strong>clap</strong> and <strong>follow</strong> the writer️!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7c9f28e2283a" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/continuous-integration-in-action-with-gitlab-7c9f28e2283a">Continuous Integration in Action with GitLab</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Open-Closed Principle in Action]]></title>
            <link>https://levelup.gitconnected.com/open-closed-principle-in-action-219ff29f7108?source=rss-10919b3a8296------2</link>
            <guid isPermaLink="false">https://medium.com/p/219ff29f7108</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[open-closed-principle]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Amirhosein Gharaati]]></dc:creator>
            <pubDate>Thu, 21 Nov 2024 22:16:34 GMT</pubDate>
            <atom:updated>2024-11-21T22:16:34.386Z</atom:updated>
            <content:encoded><![CDATA[<p>Classes should be <strong>open for extension</strong> but <strong>closed for modification</strong>. In doing so, we stop ourselves from modifying existing code and causing potential new bugs.</p><p>This principle addresses one of the common challenges in software development: how to incorporate new requirements into existing systems without destabilizing them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VZc7CcZz3tbkZKe2JpAYOw.png" /></figure><p>By building systems that comply with OCP, developers can make their codebase more adaptable to change while preserving its robustness. In this article, we will explore how to implement the Open-Closed Principle in a practical scenario using Java, demonstrating the benefits of modular design and separation of concerns.</p><h3><strong>Example: </strong>Applying OCP to a Validation Service</h3><p>Assume you have a Validator service in your program which is going to validate different fields of your data, and return the errors related.</p><p>For simplicity we assume our data is a list of products.</p><pre>public class ProductValidator {<br><br>    public ProductValidator() {<br>    }<br>    <br>    public Map&lt;String, List&lt;ErrorContent&gt;&gt; validate(List&lt;Product&gt; products) {<br>    }<br>}</pre><pre>public record ErrorContent (<br>        String title,<br>        String content<br>) {<br>}</pre><pre>@Getter<br>@Setter<br>@NoArgsConstructor<br>public class Product {<br>    private String id;<br>    private String name;<br>}</pre><p>Let’s say we are going to validate these fields:</p><ul><li>The name field: is not empty</li><li>The price field: is not lower than 0</li></ul><p>This is only a validation for name field:</p><pre>public class ProductValidator {<br><br>    public ProductValidator() {<br>    }<br><br>    public Map&lt;String, List&lt;ErrorContent&gt;&gt; validate(List&lt;Product&gt; products) {<br><br>        return products.stream()<br>                .map(product -&gt; {<br>                    List&lt;ErrorContent&gt; errors = Stream.of(<br>                            validateName(product)<br>                    ).flatMap(Optional::stream).toList();<br><br>                    return new AbstractMap.SimpleEntry&lt;&gt;(product.getId(), errors);<br>                })<br>                .filter(entry -&gt; !entry.getValue().isEmpty())<br>                .collect(<br>                        Collectors.toMap(<br>                                AbstractMap.SimpleEntry::getKey,<br>                                AbstractMap.SimpleEntry::getValue,<br>                                (entry1, entry2) -&gt; entry2<br>                        )<br>                );<br>    }<br><br>    private Optional&lt;ErrorContent&gt; validateName(Product product) {<br>        if (product.getName().isEmpty()) {<br>            return Optional.of(new ErrorContent(&quot;name&quot;, &quot;is empty&quot;));<br>        }<br>        return Optional.empty();<br>    }<br>}</pre><p>Now let’s say we want to add price field validation, or any other fields later! What will you do?</p><p>Adding another function to this class and calling the method within the stream??</p><pre>public Map&lt;String, List&lt;ErrorContent&gt;&gt; validate(List&lt;Product&gt; products) {<br><br>    return products.stream()<br>            .map(product -&gt; {<br>                List&lt;ErrorContent&gt; errors = Stream.of(<br><br>                        validateName(product),<br>                        validatePrice(product),<br>                        ...<br><br><br><br>                ).flatMap(Optional::stream).toList();<br><br>                return new AbstractMap.SimpleEntry&lt;&gt;(product.getId(), errors);<br>            })<br>            .filter(entry -&gt; !entry.getValue().isEmpty())<br>            .collect(<br>                    Collectors.toMap(<br>                            AbstractMap.SimpleEntry::getKey,<br>                            AbstractMap.SimpleEntry::getValue,<br>                            (entry1, entry2) -&gt; entry2<br>                    )<br>            );<br>}</pre><p>We said that “Classes should be <strong>open for extension</strong> but <strong>closed for modification</strong>”. But we are modifying the class here.</p><p>So what is the solution? For example in Java we have ServiceLoader.<br>We can have an interface for our validations. For each field we can have a separate validator class and register it for our validator:</p><pre>package app.example.myproject;<br><br>public interface Validator {<br>    Optional&lt;ErrorContent&gt; validate(Product product);<br>}</pre><pre>package app.example.myproject.validations;<br><br>import java.util.Optional;<br><br>public class NameValidator implements Validator {<br><br>    @Override<br>    public Optional&lt;ErrorContent&gt; validate(Product product) {<br>        if (product.getName().isEmpty()) {<br>            return Optional.of(new ErrorContent(&quot;name&quot;, &quot;is empty&quot;));<br>        }<br>        return Optional.empty();<br>    }<br>}</pre><p>Now we should register the Validator interface, and let other classes register them there.</p><p>In our project, in “resources/META-INF/services” we create a file named “app.example.myproject”.</p><p>Within the file now we can register the class validators. We should pass the path of the file in each line:</p><pre>app.example.myproject.validations.NameValidator</pre><p>Now we can use ServiceLoader to load all the validators in our main validator class:</p><pre>public class ProductValidator {<br>    private final List&lt;Validator&gt; validators;<br><br>    public ProductValidator() {<br>        this.validators = new ArrayList&lt;&gt;();<br>        loadValidationStrategies();<br>    }<br><br>    private void loadValidationStrategies() {<br>        ServiceLoader&lt;Validator&gt; loader = ServiceLoader.load(Validator.class);<br>        for (Validator strategy : loader) {<br>            validators.add(strategy);<br>        }<br>    }<br>    <br>    ...<br>}</pre><p>Now we use the validators field:</p><pre>public class ProductValidator {<br>    private final List&lt;Validator&gt; validators;<br>    <br>    public ProductValidator() {<br>        this.validators = new ArrayList&lt;&gt;();<br>        loadValidationStrategies();<br>    }<br><br>    private void loadValidationStrategies() {<br>        ServiceLoader&lt;Validator&gt; loader = ServiceLoader.load(Validator.class);<br>        for (Validator strategy : loader) {<br>            validators.add(strategy);<br>        }<br>    }<br><br>    public Map&lt;String, List&lt;ErrorContent&gt;&gt; validate(List&lt;Product&gt; products) {<br>        return products.stream()<br>                .map(product -&gt; {<br>                    List&lt;ErrorContent&gt; errors = validators.stream()<br>                            .map(validator -&gt; validator.validate(product))<br>                            .flatMap(Optional::stream).toList();<br>                    return new AbstractMap.SimpleEntry&lt;&gt;(product.getId(), errors);<br>                })<br>                .filter(entry -&gt; !entry.getValue().isEmpty())<br>                .collect(<br>                        Collectors.toMap(<br>                                AbstractMap.SimpleEntry::getKey,<br>                                AbstractMap.SimpleEntry::getValue,<br>                                (entry1, entry2) -&gt; entry2<br>                        )<br>                );<br>    }<br>}</pre><p>Now you can easily add any validator and use the interface, add the path of your validator to the<br>“resources/META-INF/services/app.example.myproject” file.</p><p>In this case you are open for extension and close to modification.</p><p>Congratulations! :D</p><h3>Conclusion</h3><p>In practice, adopting OCP leads to numerous advantages, such as fewer regression bugs, more straightforward code reviews, and the ability to scale systems with ease. While implementing OCP might seem like additional overhead initially, it pays off when new requirements emerge or systems grow in complexity.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=219ff29f7108" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/open-closed-principle-in-action-219ff29f7108">Open-Closed Principle in Action</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Single Responsibility Principle in Action]]></title>
            <link>https://levelup.gitconnected.com/single-responsibility-principle-in-action-838826e90c53?source=rss-10919b3a8296------2</link>
            <guid isPermaLink="false">https://medium.com/p/838826e90c53</guid>
            <category><![CDATA[single-responsibility]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[principles]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Amirhosein Gharaati]]></dc:creator>
            <pubDate>Mon, 11 Nov 2024 02:49:02 GMT</pubDate>
            <atom:updated>2024-11-11T02:49:02.013Z</atom:updated>
            <content:encoded><![CDATA[<p>In software engineering, adhering to the <strong>Single Responsibility Principle</strong> (SRP) is fundamental for building robust, maintainable code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KS1l_kdtYsPkJEMyB_6RsA.png" /></figure><p><em>SOLID</em> is an acronym for the first five object-oriented design principles by Robert C. Martin (also known as <a href="http://en.wikipedia.org/wiki/Robert_Cecil_Martin">Uncle Bob</a>).</p><p>The “S” letter stands for: Single Responsibility.</p><p>This principle asserts that:</p><blockquote>A class should have only and only one reason to change.</blockquote><p>This means each class should handle one responsibility — no more, no less.</p><p>Also this responsibility can be applied in different levels which we will talk about it in the article.</p><h3>Why Single Responsibility Matters</h3><p>Imagine a class that manages product data in a retail application. If this class takes on responsibilities beyond its primary purpose — such as handling complex transformations, performing validations, or even mocking data for testing — its <strong>functionality can become tangled</strong>. This not only makes the code harder to understand but also increases the risk of bugs.</p><p>Following the principle helps keep code clean and modular, so <strong>each component can be tested and changed independently</strong>, leading to a more <strong>maintainable and flexible codebase</strong>.</p><p>In this article, I’ll demonstrate how we can apply Single Responsibility Principle in a real world retail application.</p><h3>Examples</h3><h4>Example 1: Class-Level Violation</h4><p>Assume we have a ProductService class responsible for handling business logic around products. Here’s a basic example:</p><pre>@Service<br>public class ProductService {<br>    ...<br><br>    public Product save(ProductSaveRequest productRequest) {<br>        validate(productRequest);<br>        Product product = transformer.transform(productRequest);<br>        return repository.save(product);<br>    }<br>    ...<br>}</pre><p>Now, let’s say we want to provide a simple response to an endpoint that allows users to <strong>search for a product</strong>.</p><p>Instead of implementing complex search logic, we’re tempted to just add a mock search method:</p><pre>@Service<br>public class ProductService {<br><br>    public Product save(ProductSaveRequest productRequest) {<br>        ...<br>    }<br><br>    public List&lt;Product&gt; search(ProductSearchRequest request) {<br>        Product product1 = new Product();<br>        product1.setName(&quot;test-1&quot;);<br>        product1.setStoreId(&quot;123&quot;);<br><br>        Product product2 = new Product();<br>        product2.setName(&quot;test-2&quot;);<br>        product2.setStoreId(&quot;456&quot;);<br><br>        return List.of(product1, product2);<br>    }<br>    ...<br>}</pre><p><strong>Is This Correct? No!</strong></p><p>The ProductService now handles <strong>two responsibilities</strong>: <strong>saving products</strong> and <strong>generating mock data</strong>.</p><p>Mocking product data is <strong>not</strong> the responsibility of ProductService—it muddies the purpose of the class, breaking SRP.</p><p><strong>Solution: Separate the Concerns</strong><br>We can solve this by creating a separate ProductMockService responsible for handling mock data:</p><pre>@Service<br>public class ProductMockService {<br>    public List&lt;Product&gt; getDefaultProducts(ProductSearchRequest request) {<br>        // Mocking default products<br>        Product product1 = new Product();<br>        product1.setName(&quot;test-1&quot;);<br>        product1.setStoreId(&quot;123&quot;);<br><br>        Product product2 = new Product();<br>        product2.setName(&quot;test-2&quot;);<br>        product2.setStoreId(&quot;456&quot;);<br><br>        return List.of(product1, product2);<br>    }<br>}</pre><p>With ProductMockService handling mock products, ProductService can now delegate to it when needed, staying focused on main business logics:</p><pre>@Service<br>public class ProductService {<br>    private final ProductMockService mockService;<br><br>    public ProductService(ProductMockService mockService) {<br>        this.mockService = mockService;<br>    }<br><br>    public Product save(ProductSaveRequest productRequest) {<br>        validate(productRequest);<br>        Product product = transformer.transform(productRequest);<br>        return repository.save(product);<br>    }<br><br>    public List&lt;Product&gt; search(ProductSearchRequest request) {<br>        return mockService.getDefaultProducts(request);<br>    }<br><br>    ...<br>}</pre><h4>Example 2: Method-Level Violation</h4><p>Did you notice the save method in the previous examples? What if we implemented the method like this:</p><pre>@Service<br>public class ProductService {<br><br>    public Product save(ProductSaveRequest productRequest) {<br>        if (productRequest.getGtin().isEmpty()) {<br>            throw new RuntimeException(&quot;Gtin is empty&quot;);<br>        }<br>        if (productRequest.getName().isEmpty()) {<br>            throw new RuntimeException(&quot;Product name is empty&quot;);<br>        }<br>        if (productRequest.getPrice() &lt; 0) {<br>            throw new RuntimeException(&quot;Product price is lower than 0&quot;);<br>        }<br><br>        Set&lt;String&gt; categoryCodes = new HashSet&lt;&gt;(productRequest.getCategoryCodes());<br>        if (productRequest.getCategoryCodes().size() != categoryCodes.size()) {<br>            throw new RuntimeException(&quot;Duplicate category code for the product&quot;);<br>        }<br><br>        Product product = new Product();<br>        product.setName(productRequest.getName());<br>        product.setPrice(productRequest.getPrice());<br>        product.setGtin(productRequest.getGtin());<br>        product.setCategoryCodes(new HashSet&lt;&gt;(productRequest.getCategoryCodes()));<br><br>        return repository.save(product);<br>    }<br><br>    ...<br>}</pre><p>The method seems is doing multiple things, and the key note is that if <strong>any change regarding to adding a product in our system wanted to be applied, the </strong><strong>save method will be changed. </strong>But we don’t want this.</p><p>So by separating validation and transformation into dedicated methods, the save method is simplified to focus on the main flow of adding a product:</p><pre>public Product save(ProductSaveRequest productRequest) {<br>    validate(productRequest);<br>    Product product = transform(productRequest);<br>    return repository.save(product);<br>}</pre><p>That’s it! Just as simple as it is.</p><p>With this refactoring, each method has a single responsibility:</p><ul><li>validate: Ensures the product data meets necessary conditions.</li><li>transform: Converts a ProductSaveRequest into a Product.</li><li>save: Calls the other methods and persists the result.</li></ul><h3>Conclusion</h3><p>By applying Single Responsibility Principle, we make our code <strong>more modular, easier to test, and maintainable</strong>. SRP is not only a guideline for structuring classes but a mindset that can be applied at all levels of your codebase — from methods to microservices.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=838826e90c53" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/single-responsibility-principle-in-action-838826e90c53">Single Responsibility Principle in Action</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dive In Java Exception Handling]]></title>
            <link>https://medium.com/javarevisited/dive-in-java-exception-handling-0cd36e24b5ec?source=rss-10919b3a8296------2</link>
            <guid isPermaLink="false">https://medium.com/p/0cd36e24b5ec</guid>
            <category><![CDATA[exception-handling]]></category>
            <category><![CDATA[sofware-engineering]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[test]]></category>
            <dc:creator><![CDATA[Amirhosein Gharaati]]></dc:creator>
            <pubDate>Wed, 03 Jul 2024 15:38:17 GMT</pubDate>
            <atom:updated>2024-07-03T15:38:17.170Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*THC9_5iyYszj5D0qNmk9lw.png" /></figure><h3>Why do we use exception handling?</h3><p>Without handling exceptions, a healthy program may stop running altogether!</p><ol><li>We need to make sure that our code has a plan for when things go wrong.</li><li>One benefit is the stack trace itself. Because of this stack trace, we can often pinpoint offending code without needing to attach a debugger.</li></ol><h3>Advantages</h3><h4>Separating Error-Handling Code from “Regular” Code</h4><p>Consider the pseudo code method here that reads an entire file into memory:</p><pre>readFile {<br>    open the file;<br>    determine its size;<br>    allocate that much memory;<br>    read the file into memory;<br>    close the file;<br>}</pre><p>At first glance, this function seems simple enough, but it ignores all the following potential errors.</p><ul><li>What happens if the file can’t be opened?</li><li>What happens if the length of the file can’t be determined?</li><li>What happens if enough memory can’t be allocated?</li><li>What happens if the read fails?</li><li>What happens if the file can’t be closed?</li></ul><p>To handle such cases, the readFile function must have more code to do error detection, reporting, and handling. Here is an example of what the function might look like.</p><pre>errorCodeType readFile {<br>    initialize errorCode = 0;<br>    <br>    open the file;<br>    if (theFileIsOpen) {<br>        determine the length of the file;<br>        if (gotTheFileLength) {<br>            allocate that much memory;<br>            if (gotEnoughMemory) {<br>                read the file into memory;<br>                if (readFailed) {<br>                    errorCode = -1;<br>                }<br>            } else {<br>                errorCode = -2;<br>            }<br>        } else {<br>            errorCode = -3;<br>        }<br>        close the file;<br>        if (theFileDidntClose &amp;&amp; errorCode == 0) {<br>            errorCode = -4;<br>        } else {<br>            errorCode = errorCode and -4;<br>        }<br>    } else {<br>        errorCode = -5;<br>    }<br>    return errorCode;<br>}</pre><p>There’s so much error detection, reporting, and returning here. Worse yet, the logical flow of the code has also been lost.</p><p>It’s even more difficult to ensure that the code continues to do the right thing when you modify the method three months after writing it.</p><p>Exceptions enable you to write the main flow of your code and to deal with the exceptional cases elsewhere:</p><pre>readFile {<br>    try {<br>        open the file;<br>        determine its size;<br>        allocate that much memory;<br>        read the file into memory;<br>        close the file;<br>    } catch (fileOpenFailed) {<br>       doSomething;<br>    } catch (sizeDeterminationFailed) {<br>        doSomething;<br>    } catch (memoryAllocationFailed) {<br>        doSomething;<br>    } catch (readFailed) {<br>        doSomething;<br>    } catch (fileCloseFailed) {<br>        doSomething;<br>    }<br>}</pre><h4>Propagating Errors Up the Call Stack</h4><p>Suppose that the readFile method is the fourth method in a series of nested method calls made by the main program:</p><pre>method1 {<br>    call method2;<br>}<br><br>method2 {<br>    call method3;<br>}<br><br>method3 {<br>    call readFile;<br>}</pre><p>Suppose also that method1 is the only method interested in the errors that might occur within readFile.</p><p>Traditional error-notification techniques force method2 and method3 to propagate the error codes returned by readFile up the call stack until the error codes finally reach method1 .</p><pre>method1 {<br>    errorCodeType error;<br>    error = call method2;<br>    if (error)<br>        doErrorProcessing;<br>    else<br>        proceed;<br>}<br><br>errorCodeType method2 {<br>    errorCodeType error;<br>    error = call method3;<br>    if (error)<br>        return error;<br>    else<br>        proceed;<br>}<br><br>errorCodeType method3 {<br>    errorCodeType error;<br>    error = call readFile;<br>    if (error)<br>        return error;<br>    else<br>        proceed;<br>}</pre><p>A method can duck any exceptions thrown within it, thereby allowing a method farther up the call stack to catch it. Hence, only the methods that care about errors have to worry about detecting errors:</p><pre>method1 {<br>    try {<br>        call method2;<br>    } catch (exception e) {<br>        doErrorProcessing;<br>    }<br>}<br><br>method2 throws exception {<br>    call method3;<br>}<br><br>method3 throws exception {<br>    call readFile;<br>}</pre><p>However, as the pseudocode shows, ducking an exception requires some effort on the part of the middleman methods. Any checked exceptions that can be thrown within a method must be specified in its throws clause.</p><h4>Grouping and Differentiating Error Types</h4><p>A method can write specific handlers that can handle a very specific exception. The FileNotFoundException class has no descendants, so the following handler can handle only one type of exception.</p><pre>catch (FileNotFoundException e) {<br>    ...<br>}</pre><p>A method can catch an exception based on its group or general type by specifying any of the exception’s superclasses in the catch statement. For example, to catch all I/O exceptions, regardless of their specific type, an exception handler specifies an IOException argument.</p><pre>catch (IOException e) {<br>    ...<br>}</pre><p>This handler will be able to catch all I/O exceptions, including FileNotFoundException, EOFException, and so on. You can find details about what occurred by querying the argument passed to the exception handler. For example, use the following to print the stack trace.</p><pre>catch (IOException e) {<br>    // Output goes to System.err.<br>    e.printStackTrace();<br>    // Send trace to stdout.<br>    e.printStackTrace(System.out);<br>}</pre><p>You could even set up an exception handler that handles any Exception with the handler here.</p><pre>// A (too) general exception handler<br>catch (Exception e) {<br>    ...<br>}</pre><p>In most situations, however, you want exception handlers to be as specific as possible. The reason is that the first thing a handler must do is determine what type of exception occurred before it can decide on the best recovery strategy.</p><p>In effect, by not catching specific errors, the handler must accommodate any possibility. Exception handlers that are too general can make code more error-prone by catching and handling exceptions that weren’t anticipated by the programmer and for which the handler was not intended.</p><h3>Types of Exceptions</h3><p>There are mainly two types of exceptions: <strong>checked</strong> and <strong>unchecked</strong>. An error is considered as the unchecked exception. However, according to Oracle, there are three types of exceptions namely:</p><ol><li>Checked Exception</li><li>Unchecked Exception</li><li>Error</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*iIc41hcLUE8-Gxn4.jpeg" /></figure><h4>1. Checked Exception</h4><p>The classes that directly inherit the Throwable class except RuntimeException and Error are known as checked exceptions.</p><ul><li>IOException</li><li>SQLException</li><li>ServletException</li></ul><p>Checked exceptions are exceptions that the Java compiler requires us to handle. We have to either declaratively throw the exception up the call stack, or we have to handle it ourselves.</p><p><a href="https://docs.oracle.com/javase/tutorial/essential/exceptions/runtime.html">Oracle’s documentation</a> tells us to use checked exceptions when we can reasonably expect the caller of our method to be able to recover.</p><blockquote>Checked exceptions are checked at compile-time.</blockquote><h4>2. Unchecked Exception</h4><p>The classes that inherit the RuntimeException are known as unchecked exceptions.</p><ul><li>ArithmeticException</li><li>NullPointerException</li><li>ArrayIndexOutOfBoundsException</li><li>IllegalArgumentException</li></ul><p>Unchecked exceptions are exceptions that the Java compiler does <em>not</em> require us to handle.</p><p>Simply put, if we create an exception that extends <em>RuntimeException</em>, it will be unchecked; otherwise, it will be checked.</p><p>And while this sounds convenient, <a href="https://docs.oracle.com/javase/tutorial/essential/exceptions/runtime.html">Oracle’s documentation</a> tells us that there are good reasons for both concepts, like differentiating between a situational error (checked) and a usage error (unchecked).</p><blockquote>Unchecked exceptions are not checked at compile-time, but they are checked at runtime.</blockquote><h4>3. Error</h4><p>Error is irrecoverable.</p><ul><li>OutOfMemoryError</li><li>AssertionError</li><li>StackOverflowError</li></ul><p>Errors represent serious and usually irrecoverable conditions like a library incompatibility, infinite recursion, or memory leaks.</p><p>And even though they don’t extend <em>RuntimeException</em>, they are also unchecked.</p><p>In most cases, it’d be weird for us to handle, instantiate or extend <em>Errors</em>. Usually, we want these to propagate all the way up.</p><h3>Handling Exception In Java</h3><h4>throws</h4><p>The simplest way to “handle” an exception is to rethrow it:</p><pre>public int getPlayerScore(String playerFile)<br>  throws FileNotFoundException {<br> <br>    Scanner contents = new Scanner(new File(playerFile));<br>    return Integer.parseInt(contents.nextLine());<br>}</pre><p>Because <em>FileNotFoundException </em>is a checked exception, this is the simplest way to satisfy the compiler, but <strong>it does mean that anyone that calls our method now needs to handle it too!</strong></p><p><em>parseInt</em> can throw a<em> NumberFormatException</em>, but because it is unchecked, we aren’t required to handle it.</p><h4>try-catch</h4><p>If we want to try and handle the exception ourselves, we can use a <em>try-catch</em> block. We can handle it by rethrowing our exception:</p><pre>public int getPlayerScore(String playerFile) {<br>    try {<br>        Scanner contents = new Scanner(new File(playerFile));<br>        return Integer.parseInt(contents.nextLine());<br>    } catch (FileNotFoundException noFile) {<br>        throw new IllegalArgumentException(&quot;File not found&quot;);<br>    }<br>}</pre><p>Or by performing recovery steps:</p><pre>public int getPlayerScore(String playerFile) {<br>    try {<br>        Scanner contents = new Scanner(new File(playerFile));<br>        return Integer.parseInt(contents.nextLine());<br>    } catch ( FileNotFoundException noFile ) {<br>        logger.warn(&quot;File not found, resetting score.&quot;);<br>        return 0;<br>    }<br>}</pre><h4>try-with-resource</h4><p>The try-with-resources statement is a try statement that declares one or more resources. A <em>resource</em> is an object that must be closed after the program is finished with it. The try-with-resources statement ensures that each resource is closed at the end of the statement. Any object that implements java.lang.AutoCloseable, which includes all objects which implement java.io.Closeable, can be used as a resource.</p><pre>static String readFirstLineFromFile(String path) throws IOException {<br>     try (FileReader fr = new FileReader(path);<br>          BufferedReader br = new BufferedReader(fr)) {<br>         return br.readLine();<br>     }<br> }</pre><p>Because the FileReader and BufferedReader instances are declared in a try-with-resource statement, they will be closed regardless of whether the try statement completes normally or abruptly</p><h3>Java Exception Propagation</h3><p>An exception is first thrown from the top of the stack and if it is not caught, it drops down the call stack to the previous method.</p><p>If not caught there, the exception again drops down to the previous method, and so on until they are caught or until they reach the very bottom of the call stack. This is called exception propagation.</p><p>Exception can be handled in any method in call stack either in the main() method, p() method, n() method or m() method.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/0*sQMfnwgdorh_NzyO.png" /></figure><blockquote>By default, Checked Exceptions are not forwarded in calling chain (propagated).</blockquote><h3>Java Custom Exception</h3><p>We can create our own exceptions that are derived classes of the Exception class.</p><p>Basically, Java custom exceptions are used to customize the exception according to user need.</p><h4>Why use custom exceptions?</h4><p>Following are few of the reasons to use custom exceptions:</p><ul><li>To catch and provide specific treatment to a subset of existing Java exceptions.</li><li>Business logic exceptions: These are the exceptions related to business logic and workflow. It is useful for the application users or the developers to understand the exact problem.</li></ul><p><strong>Example</strong></p><p>Imagine you created a custom REST client for API calls.</p><p>This is just an example. You can implement it in any other way:</p><pre>public record ResponseEntity&lt;T&gt;(<br>        Integer code,<br>        Boolean successful,<br>        String message,<br>        T body<br>) {<br>    public ResponseEntity(Response response, T body) {<br>        this(<br>                response.code(),<br>                response.isSuccessful(),<br>                response.message(),<br>                body<br>        );<br>    }<br>}<br><br>public &lt;T&gt; ResponseEntity&lt;T&gt; send(Request request, Class&lt;T&gt; responseType) {<br>    OkHttpClient client = new OkHttpClient();<br><br>    try (Response response = client.newCall(request).execute()) {<br>        if (response.body() == null) {<br>            log.error(&quot;empty response body&quot;);<br>            throw new EmptyResponseException(&quot;empty response body&quot;);<br>        }<br><br>        String responseBody = response.body().string();<br>        if (!response.isSuccessful()) {<br>            log.error(&quot;response was not successful: {}&quot;, responseBody);<br>            throw new BadResponseException(&quot;response was not successful: %s&quot;.formatted(responseBody));<br>        }<br><br>        if (responseType == Void.class) {<br>            return new ResponseEntity&lt;&gt;(response, null);<br>        }<br><br>        T entity = objectMapper.readValue(responseBody, responseType);<br>        return new ResponseEntity&lt;&gt;(response, entity);<br><br>    } catch (IOException e) {<br>        log.error(&quot;error occurred while processing request: {}&quot;, e.getMessage());<br>        throw new ClientException(e.getMessage());<br>    }<br>}</pre><p>There are 3 custom exceptions here:</p><p><em>EmptyResponseException</em>, <em>BadResponseException</em>, and ClientException</p><p>All with extending RuntimeException:</p><pre>public class BadResponseException extends RuntimeException {<br>    public BadResponseException(String message) {<br>        super(message);<br>    }<br>}</pre><p>In the send method, you have more control to treat with the behavior and response.</p><blockquote>You can have your own exception with specific constructions and behavior.</blockquote><blockquote>You throw exception or print stack trace in the log. It is based in the project requirements and behaviors.</blockquote><h3>Questions</h3><h4><strong>Why did the designers decide to force a method to specify all uncaught checked exceptions that can be thrown within its scope?</strong></h4><p>Any Exception that can be thrown by a method is part of the method&#39;s public programming interface.</p><p>Those who call a method must know about the exceptions that a method can throw so that they can decide what to do about them. These exceptions are as much a part of that method&#39;s programming interface as its parameters and return value.</p><h4><strong>If it’s so good to document a method’s API, including the exceptions it can throw, why not specify runtime exceptions too?</strong></h4><p>Runtime exceptions represent problems that are the result of a programming problem, and as such, the API client code cannot reasonably be expected to recover from them or to handle them in any way.</p><p>Such problems include</p><ul><li>arithmetic exceptions, such as dividing by zero</li><li>pointer exceptions, such as trying to access an object through a null reference</li><li>indexing exceptions such as attempting to access an array element through an index that is too large or too small.</li></ul><h4><strong>Why we should create custom RuntimeExceptions?</strong></h4><p>Runtime exceptions can occur anywhere in a program, and in a typical one they can be very numerous.</p><p><strong>Having to add runtime exceptions in every method declaration would reduce a program’s clarity.</strong> Thus, the compiler does not require that you catch or specify runtime exceptions (although you can).</p><p>Generally speaking, do not throw a RuntimeException or create a subclass of RuntimeException simply because you don&#39;t want to be bothered with specifying the exceptions your methods can throw.</p><h4><strong>Where should I create checked or unchecked exceptions?</strong></h4><p>If a client can reasonably be expected to recover from an exception, make it a checked exception. If a client cannot do anything to recover from the exception, make it an unchecked exception.</p><h3>Anti-Patterns</h3><h4>Swallowing Exceptions</h4><p>Now, there’s one other way that we could have satisfied the compiler:</p><pre>public int getPlayerScore(String playerFile) {<br>    try {<br>        // ...<br>    } catch (Exception e) {} // &lt;== catch and swallow<br>    return 0;<br>}</pre><p>It doesn’t address the issue and it keeps other code from being able to address the issue, too.</p><p>In those cases that we are confident it will never happen, we should still at least add a comment stating that we intentionally ate the exception:</p><pre>public int getPlayerScore(String playerFile) {<br>    try {<br>        // ...<br>    } catch (IOException e) {<br>        // this will never happen<br>    }<br>}</pre><p>Another way we can “swallow” an exception is to print out the exception to the error stream simply:</p><pre>public int getPlayerScore(String playerFile) {<br>    try {<br>        // ...<br>    } catch (Exception e) {<br>        e.printStackTrace();<br>    }<br>    return 0;<br>}</pre><p>It’d be better, though, for us to use a logger:</p><pre>public int getPlayerScore(String playerFile) {<br>    try {<br>        // ...<br>    } catch (IOException e) {<br>        logger.error(&quot;Couldn&#39;t load the score&quot;, e);<br>        return 0;<br>    }<br>}</pre><p>One ideal thing we can do is throwing a custom related exception:</p><pre>public int getPlayerScore(String playerFile) {<br>    try {<br>        // ...<br>    } catch (IOException e) {<br>        throw new PlayerScoreException(e);<br>    }<br>}</pre><h4>Using return in a finally Block</h4><p>This is bad because, by returning abruptly, the JVM will drop the exception, even if it was thrown from by our code:</p><pre>public int getPlayerScore(String playerFile) {<br>    int score = 0;<br>    try {<br>        throw new IOException();<br>    } finally {<br>        return score; // &lt;== the IOException is dropped<br>    }<br>}</pre><h4>Using throw in a finally Block</h4><p>This will “erase” the original exception from the <em>try</em> block, and we lose all of that valuable information:</p><pre>public int getPlayerScore(String playerFile) {<br>    try {<br>        // ...<br>    } catch ( IOException io ) {<br>        throw new IllegalStateException(io); // &lt;== eaten by the finally<br>    } finally {<br>        throw new OtherException();<br>    }<br>}</pre><h4>Using throw as a goto</h4><p>This is odd because the code is attempting to use exceptions for flow control as opposed to error handling.</p><pre>public void doSomething() {<br>    try {<br>        // bunch of code<br>        throw new MyException();<br>        // second bunch of code<br>    } catch (MyException e) {<br>        // third bunch of code<br>    }  <br>}</pre><h3>Best Practices</h3><h4>Log errors, but be careful what you log</h4><p>You should log the errors to save information about why really an error happened in the system.</p><p>However, you must ensure no protected data is written in the log files.</p><h4>Don’t bury thrown exceptions</h4><p>Don’t catch an exception and then do nothing with it. That’s known as burying an exception.</p><p>Buried exceptions makes troubleshooting Java applications extremely hard.</p><h4>Use a global Exception handler</h4><p>There will always be uncaught RuntimeExceptions that creep into your code.</p><p>Always include a global Exception handler to deal with any uncaught exceptions.</p><h4>Throw early and handle exceptions late</h4><p>As soon as an exception condition happens in your code, throw an Exception.</p><p>The function to catch exceptions should go toward the end of a method. This puts fewer catch blocks in your methods, and makes your code much easier to read and maintain</p><h4>Don’t log and rethrow</h4><p>Never do both. You should <a href="https://www.theserverside.com/tip/Troubleshooting-Java-Code-Log-or-Re-Throw-but-Dont-Do-Both">never log and then rethrow</a> the same exception, as is done in the following example:</p><pre>/* log and rethrow exception example */<br>try {<br>  Class.forName(&quot;com.mcnz.Example&quot;);<br>} catch (ClassNotFoundException ex) {<br>  log.warning(&quot;Class was not found.&quot;);<br>  throw ex;<br>}</pre><p>Doing so causes code duplication, and litters the log files with duplicate entries which makes it much more difficult to troubleshoot code.</p><h4>Check for suppressed exceptions</h4><p>The <a href="https://www.theserverside.com/tutorial/OCPJP-OCAJP-Java-7-Suppressed-Exceptions-Try-With-Resources">suppressed exception</a> is a relatively new language feature that not all developers are aware of.</p><p>You can easily check this situation simply by querying for the suppressed exception’s existence, as is done in the example below:</p><pre>try ( Door door = new Door() ) {<br>  door.swing(); /* Throws the SwingException */<br>}<br>catch (Exception e) {<br>  System.out.println(&quot;Primary Exception:  &quot; + e.getClass());<br>  if (e.getSuppressed().length &gt; 0) {<br>    System.out.print(&quot;Suppressed Exception: &quot; + e.getSuppressed()[0]);<br>  }<br>}</pre><h4>Explicitly define exceptions in the throws clause</h4><p>Lazy developers use the generic Exception class in the <em>throws</em> clause of a method.</p><p>Instead, always explicitly state the exact set of exception a given method might throw. This allows other developers to know the various error handling routines they can employ if a given method fails to execute properly.</p><h3>References</h3><ul><li><a href="https://www.javatpoint.com/exception-handling-in-java">Exception Handling in Java | Java Exceptions - javatpoint</a></li><li><a href="https://www.javatpoint.com/custom-exception">Java Custom Exception - javatpoint</a></li><li><a href="https://docs.oracle.com/javase/tutorial/essential/exceptions/index.html">Lesson: Exceptions</a></li><li><a href="https://www.theserverside.com/blog/Coffee-Talk-Java-News-Stories-and-Opinions/Java-Exception-handling-best-practices">Java Exception handling best practices</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0cd36e24b5ec" width="1" height="1" alt=""><hr><p><a href="https://medium.com/javarevisited/dive-in-java-exception-handling-0cd36e24b5ec">Dive In Java Exception Handling</a> was originally published in <a href="https://medium.com/javarevisited">Javarevisited</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Top Java Static Code Analysis Rules By Sonar: Bugs, Vulnerabilities, Security Hotspots]]></title>
            <link>https://towardsdev.com/top-java-static-code-analysis-rules-by-sonar-bugs-vulnerabilities-security-hotspots-cdef2ea0d303?source=rss-10919b3a8296------2</link>
            <guid isPermaLink="false">https://medium.com/p/cdef2ea0d303</guid>
            <category><![CDATA[best-practices]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[clean-code]]></category>
            <dc:creator><![CDATA[Amirhosein Gharaati]]></dc:creator>
            <pubDate>Wed, 06 Mar 2024 05:10:40 GMT</pubDate>
            <atom:updated>2024-03-16T18:16:37.256Z</atom:updated>
            <content:encoded><![CDATA[<p>Writing clean and efficient code is crucial for building successful software projects.</p><p>Sonar’s static code analysis rules provide valuable guidance in this pursuit. These rules help developers identify and fix potential issues in their code, leading to better overall quality and reliability.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/797/1*_KbDYiq5vTS0AeWRv7fFFA.png" /></figure><blockquote>Secure, quality software comes from secure, quality code</blockquote><p>Sonar have defined many rules in different languages in different aspects which developers can accept them to help coding better.</p><p>In this article, I have tried to select popular rules in bugs, vulnerabilities, and security hotspots. We’ll take a closer look at how it can positively impact the performance and visibility of their projects.</p><h4><a href="https://rules.sonarsource.com/java/RSPEC-6437/">Credentials should not be hard-coded</a></h4><p>In most cases, trust boundaries are violated when a secret is exposed in a source code repository or an uncontrolled deployment environment.</p><p>Financial losses can occur when a secret is used to access a paid third-party-provided service and is disclosed as part of the source code of client applications.</p><p>A downgrade can happen when the disclosed secret is used to protect security-sensitive assets or features of the application.</p><p><strong>Solution: </strong>Use environments to get the secret</p><pre>import org.h2.security.SHA256;<br><br>String inputString = System.getenv(&quot;SECRET&quot;);<br>byte[] key         = inputString.getBytes();<br><br>SHA256.getHMAC(key, message);</pre><p><strong>Another Solution(Personal): </strong>Use Hashicorp-Vault for secret management</p><h4><a href="https://rules.sonarsource.com/java/RSPEC-5146/">HTTP request redirections should not be open to forging attacks</a></h4><p>Open redirection occurs when an application uses user-controllable data to redirect users to a URL.</p><p>An attacker with malicious intent could manipulate a user to browse into a specially crafted URL, such as https://trusted.example.com?url=evil.example.com, to redirect the victim to his evil domain.</p><p><strong>Non Compliant Code</strong></p><pre>protected void doGet(HttpServletRequest req, HttpServletResponse resp)<br>     throws IOException {<br>  String location = req.getParameter(&quot;url&quot;);<br>  resp.sendRedirect(location);<br>}</pre><p><strong>Compliant Code</strong></p><pre>protected void doGet(HttpServletRequest req, HttpServletResponse resp)<br>     throws IOException {<br>  String location = req.getParameter(&quot;url&quot;);<br><br>  List&lt;String&gt; allowedHosts = new ArrayList&lt;String&gt;();<br>  allowedHosts.add(&quot;https://trusted1.example.com/&quot;);<br>  allowedHosts.add(&quot;https://trusted2.example.com/&quot;);<br><br>  if (allowedHosts.contains(location))<br>    resp.sendRedirect(location);<br>}</pre><p>In case the application strictly requires external redirections based on user-controllable data, this could be done using the following alternatives:</p><ol><li>Validating the authority part of the URL against a statically defined value.</li><li>Using an allow-list approach in case the destination URLs are multiple but limited.</li><li>Adding a customized page to which users are redirected, warning about the imminent action and requiring manual authorization to proceed.</li></ol><h4><a href="https://rules.sonarsource.com/java/RSPEC-2275/">Printf-style format strings should not lead to unexpected behavior at runtime</a></h4><p><strong>Non Compliant Code</strong></p><pre>// Noncompliant; an &#39;int&#39; is expected rather than a String<br>String.format(&quot;The value of my integer is %d&quot;, &quot;Hello World&quot;);<br><br>//Noncompliant; X is not a supported time conversion character<br>String.format(&quot;Duke&#39;s Birthday year is %tX&quot;, c); <br><br>//Noncompliant; arguments are numbered starting from 1<br>String.format(&quot;Display %0$d and then %d&quot;, 1);<br><br>//Noncompliant; the second argument is missing<br>String.format(&quot;Not enough arguments %d and %d&quot;, 1);<br><br>// Noncompliant; the argument index &#39;&lt;&#39; refers to the<br>// previous format specifier but there isn&#39;t one<br>String.format(&quot;%&lt; is equals to %d&quot;, 2);<br><br>// Noncompliant; Not enough arguments. (first element is {0})<br>MessageFormat.format(&quot;Result {1}.&quot;, value);<br><br>// Noncompliant; Unbalanced number of quotes (single quote must be escaped)<br>MessageFormat.format(&quot;Result &#39; {0}&quot;, value);<br><br>java.util.logging.Logger logger;<br><br>// Noncompliant - Not enough arguments.<br>logger.log(java.util.logging.Level.SEVERE, &quot;Result {1}!&quot;, 14);<br><br>org.slf4j.Logger slf4jLog;<br>org.slf4j.Marker marker;<br><br>// Noncompliant - Not enough arguments.<br>slf4jLog.debug(marker, &quot;message {}&quot;); <br><br>org.apache.logging.log4j.Logger log4jLog;<br>// Noncompliant - Not enough arguments.<br>log4jLog.debug(&quot;message {}&quot;); </pre><h4><a href="https://rules.sonarsource.com/java/RSPEC-2229/">Methods should not call same-class methods with incompatible “@Transactional” values</a></h4><p>Transactional methods have a propagation type parameter in the @Transaction annotation that specifies the requirements about the transactional context in which the method can be called and how it creates, appends, or suspends an ongoing transaction.</p><p>When an instance that contains transactional methods is injected, Spring uses proxy objects to wrap these methods with the actual transaction code.</p><p>However, if a transactional method is called from another method in the same class, the this argument is used as the receiver instance instead of the injected proxy object, which bypasses the wrapper code.</p><p><strong>Non Compliant Code</strong></p><pre>public void doTheThing() {<br>  // ...<br>  actuallyDoTheThing(); // Noncompliant, call from non-transactional to transactional<br>}<br><br>@Transactional<br>public void actuallyDoTheThing() {<br>  // ...<br>}</pre><p><strong>Compliant Code</strong></p><pre>@Transactional<br>public void doTheThing() {<br>  // ...<br>  actuallyDoTheThing(); // Compliant<br>}<br><br>@Transactional<br>public void actuallyDoTheThing() {<br>  // ...<br>}</pre><h4><a href="https://rules.sonarsource.com/java/RSPEC-2095/">Resources should be closed</a></h4><p>Connections, streams, files, and other classes that implement the Closeable interface or its super-interface, AutoCloseable, needs to be closed after use. Further, that close call must be made in a finally block otherwise an exception could keep the call from being made. Preferably, when class implements AutoCloseable, resource should be created using &quot;try-with-resources&quot; pattern and will be closed automatically.</p><p>Failure to properly close resources will result in a resource leak which could bring first the application and then perhaps the box the application is on to their knees.</p><p><strong>Non Compliant Code</strong></p><pre>private void readTheFile() throws IOException {<br>  Path path = Paths.get(this.fileName);<br>  BufferedReader reader = Files.newBufferedReader(path, this.charset);<br>  // ...<br>  reader.close();  // Noncompliant<br>  // ...<br>  Files.lines(&quot;input.txt&quot;).forEach(System.out::println); // Noncompliant: The stream needs to be closed<br>}<br><br>private void doSomething() {<br>  OutputStream stream = null;<br>  try {<br>    for (String property : propertyList) {<br>      stream = new FileOutputStream(&quot;myfile.txt&quot;);  // Noncompliant<br>      // ...<br>    }<br>  } catch (Exception e) {<br>    // ...<br>  } finally {<br>    stream.close();  // Multiple streams were opened. Only the last is closed.<br>  }<br>}</pre><p><strong>Compliant Code</strong></p><pre>private void readTheFile(String fileName) throws IOException {<br>    Path path = Paths.get(fileName);<br>    try (BufferedReader reader = Files.newBufferedReader(path, StandardCharsets.UTF_8)) {<br>      reader.readLine();<br>      // ...<br>    }<br>    // ..<br>    try (Stream&lt;String&gt; input = Files.lines(&quot;input.txt&quot;))  {<br>      input.forEach(System.out::println);<br>    }<br>}<br><br>private void doSomething() {<br>  OutputStream stream = null;<br>  try {<br>    stream = new FileOutputStream(&quot;myfile.txt&quot;);<br>    for (String property : propertyList) {<br>      // ...<br>    }<br>  } catch (Exception e) {<br>    // ...<br>  } finally {<br>    stream.close();<br>  }<br>}</pre><p><strong>Side Note: </strong>Using try-with-resource is better option than closing the resource manually.</p><h4><a href="https://rules.sonarsource.com/java/RSPEC-4684/">Persistent entities should not be used as arguments of “@RequestMapping” methods</a></h4><p>With Spring, when a request mapping method is configured to accept bean objects as arguments, the framework will automatically bind HTTP parameters to those objects’ properties. If the targeted beans are also persistent entities, the framework will also store those properties in the storage backend, usually the application’s database.</p><p><strong>Non Compliant Code</strong></p><pre>import javax.persistence.Entity;<br><br>@Entity<br>public class Wish {<br>  Long productId;<br>  Long quantity;<br>  Client client;<br>}<br><br>@Entity<br>public class Client {<br>  String clientId;<br>  String name;<br>  String password;<br>}<br><br>import org.springframework.stereotype.Controller;<br>import org.springframework.web.bind.annotation.RequestMapping;<br><br>@Controller<br>public class PurchaseOrderController {<br><br>  @RequestMapping(path = &quot;/saveForLater&quot;, method = RequestMethod.POST)<br>  public String saveForLater(Wish wish) { // Noncompliant<br>    session.save(wish);<br>  }<br>}</pre><p><strong>Compliant Code</strong></p><pre>public class WishDTO {<br>  Long productId;<br>  Long quantity;<br>  Long clientId;<br>}<br><br>import org.springframework.stereotype.Controller;<br>import org.springframework.web.bind.annotation.RequestMapping;<br><br>@Controller<br>public class PurchaseOrderController {<br><br>  @RequestMapping(path = &quot;/saveForLater&quot;, method = RequestMethod.POST)<br>  public String saveForLater(WishDTO wish) {<br>    Wish persistentWish = new Wish();<br>    persistentWish.productId = wish.productId<br>    persistentWish.quantity = wish.quantity<br>    persistentWish.client = getClientById(with.clientId)<br>    session.save(persistentWish);<br>  }<br>}</pre><p>The compliant code implements a Data Transfer Object (DTO) layer. Instead of accepting a persistent Wish entity as a parameter, the vulnerable method accepts a WishDTO object with a safe, minimal set of properties.</p><h4><a href="https://rules.sonarsource.com/java/RSPEC-2631/">Regular expressions should not be vulnerable to Denial of Service attacks</a></h4><p>In cases where the complexity of the regular expression is exponential to the input size, a small, carefully-crafted input (for example, 20 chars) can trigger <em>catastrophic backtracking</em> and cause a denial of service of the application.</p><p>Super-linear regex complexity can produce the same effects for a large, carefully crafted input (thousands of chars).</p><p>However, a denial of service attack can be critical to the enterprise if it targets a SPOF(single point of failure) component. Sometimes the SPOF is a software architecture vulnerability or an operational vulnerability.</p><p><strong>Non Compliant Code</strong></p><pre>public boolean validate(HttpServletRequest request) {<br>  String regex = request.getParameter(&quot;regex&quot;);<br>  String input = request.getParameter(&quot;input&quot;);<br><br>  return input.matches(regex);<br>}</pre><p><strong>Compliant Code</strong></p><pre>public boolean validate(HttpServletRequest request) {<br>  String regex = request.getParameter(&quot;regex&quot;);<br>  String input = request.getParameter(&quot;input&quot;);<br><br>  return input.matches(Pattern.quote(regex));<br>}</pre><p>Metacharacters escape using native functions is a solution against regex injection.<br>The escape function sanitizes the input so that the regular expression engine interprets these characters literally.</p><h4><a href="https://rules.sonarsource.com/java/RSPEC-2119/">“Random” objects should be reused</a></h4><p>Creating a new Random object each time a random value is needed is inefficient and may produce numbers that are not random, depending on the JDK. For better efficiency and randomness, create a single Random, store it, and reuse it.</p><p><strong>Non Compliant Code</strong></p><pre>class MyClass {<br><br>    public void doSomethingCommon() {<br>      // Noncompliant - new instance created with each invocation<br>      Random random = new Random(); <br>      int rValue = random.nextInt();<br>    }<br>}</pre><p><strong>Compliant Code</strong></p><pre>class MyClass {<br>    private Random random = new Random();  // Compliant<br><br>    public void doSomethingCommon() {<br>      int rValue = this.random.nextInt();<br>    }<br>}</pre><h4><a href="https://rules.sonarsource.com/java/RSPEC-5443/">Using publicly writable directories is security-sensitive</a></h4><p>Operating systems have global directories where any user has write access. Those folders are mostly used as temporary storage areas like /tmp in Linux based systems. An application manipulating files from these folders is exposed to race conditions on filenames: a malicious user can try to create a file with a predictable name before the application does.</p><p>This rule raises an issue whenever it detects a hard-coded path to a publicly writable directory like:</p><p>/tmp ,/var/tmp ,/usr/tmp ,/dev/shm ,/dev/mqueue ,/run/lock ,/var/run/lock ,/Library/Caches ,/Users/Shared ,/private/tmp ,/private/var/tmp ,\Windows\Temp ,\Temp ,\TMP</p><p><strong>Sensitive Code</strong></p><pre>new File(&quot;/tmp/myfile.txt&quot;); // Sensitive<br>Paths.get(&quot;/tmp/myfile.txt&quot;); // Sensitive<br><br>// Sensitive, will be in the default temporary-file directory.<br>java.io.File.createTempFile(&quot;prefix&quot;, &quot;suffix&quot;);<br><br>// Sensitive, will be in the default temporary-file directory.<br>java.nio.file.Files.createTempDirectory(&quot;prefix&quot;); </pre><p><strong>Compliant Code</strong></p><pre>new File(&quot;/myDirectory/myfile.txt&quot;);  // Compliant<br><br>// Compliant<br>File.createTempFile(&quot;prefix&quot;, &quot;suffix&quot;, new File(&quot;/mySecureDirectory&quot;));  <br><br>if(SystemUtils.IS_OS_UNIX) {<br>  FileAttribute&lt;Set&lt;PosixFilePermission&gt;&gt; attr =<br>    PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString(&quot;rwx------&quot;));<br>  Files.createTempFile(&quot;prefix&quot;, &quot;suffix&quot;, attr); // Compliant<br>}<br>else {<br>  File f = Files.createTempFile(&quot;prefix&quot;, &quot;suffix&quot;).toFile();  // Compliant<br>  f.setReadable(true, true);<br>  f.setWritable(true, true);<br>  f.setExecutable(true, true);<br>}</pre><h4><a href="https://rules.sonarsource.com/java/RSPEC-5332/">Using clear-text protocols is security-sensitive</a></h4><p>Clear-text protocols such as ftp, telnet, or http lack encryption of transported data, as well as the capability to build an authenticated connection. It means that an attacker able to sniff traffic from the network can read, modify, or corrupt the transported content.</p><p><strong>Sensitive Code</strong></p><p>These clients from <a href="https://commons.apache.org/proper/commons-net/">Apache commons net</a> libraries are based on unencrypted protocols and are not recommended:</p><pre>TelnetClient telnet = new TelnetClient(); // Sensitive<br><br>FTPClient ftpClient = new FTPClient(); // Sensitive<br><br>SMTPClient smtpClient = new SMTPClient(); // Sensitive</pre><p>Unencrypted HTTP connections, when using <a href="https://square.github.io/okhttp/https/">okhttp</a> library for instance, should be avoided:</p><pre>ConnectionSpec spec = new ConnectionSpec.Builder(ConnectionSpec.CLEARTEXT)<br>  .build();</pre><p><strong>Compliant Code</strong></p><p>Use instead these clients from <a href="https://commons.apache.org/proper/commons-net/">Apache commons net</a> and <a href="http://www.jcraft.com/jsch/">JSch/ssh</a> library:</p><pre>JSch jsch = new JSch();<br><br>if(implicit) {<br>  // implicit mode is considered deprecated but offer the same security than explicit mode<br>  FTPSClient ftpsClient = new FTPSClient(true);<br>}<br>else {<br>  FTPSClient ftpsClient = new FTPSClient();<br>}</pre><p>Perform HTTP encrypted connections, with <a href="https://square.github.io/okhttp/https/">okhttp</a> library for instance:</p><pre>ConnectionSpec spec = new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS)<br>  .build();</pre><h4><a href="https://rules.sonarsource.com/java/RSPEC-4544/">Using unsafe Jackson deserialization configuration is security-sensitive</a></h4><p>When Jackson is configured to allow Polymorphic Type Handling (aka PTH), formerly known as Polymorphic Deserialization, “deserialization gadgets” may allow an attacker to perform remote code execution.</p><p>This rule raises an issue when:</p><ul><li>enableDefaultTyping() is called on an instance of com.fasterxml.jackson.databind.ObjectMapper or org.codehaus.jackson.map.ObjectMapper.</li><li>or when the annotation @JsonTypeInfo is set at class, interface or field levels and configured with use = JsonTypeInfo.Id.CLASS or use = Id.MINIMAL_CLASS.</li></ul><p><strong>Sensitive Code</strong></p><pre>ObjectMapper mapper = new ObjectMapper();<br>mapper.enableDefaultTyping(); // Sensitive</pre><pre>@JsonTypeInfo(use = Id.CLASS) // Sensitive<br>abstract class PhoneNumber {<br>}</pre><h4><a href="https://rules.sonarsource.com/java/RSPEC-6398/">JSON operations should not be vulnerable to injection attacks</a></h4><p>JSON injections occur when an application builds a JSON-formatted string from user input without prior validation or sanitation. In such a case, a tainted user-controlled value can tamper with the JSON string content.</p><p><strong>Non Compliant Code (Java SE)</strong></p><pre>import org.json.JSONObject;<br><br>public void doGet(HttpServletRequest req, HttpServletResponse resp)<br>      throws IOException {<br>    try {<br>        String tainted = request.getParameter(&quot;value&quot;);<br>        String json = &quot;{\&quot;key\&quot;:\&quot;&quot;+ tainted +&quot;\&quot;}&quot;;<br>        JSONObject obj = new JSONObject(json); // Noncompliant<br>    } catch (JsonException e) {<br>        resp.sendError(400)<br>    }<br>}</pre><p><strong>Compliant Code (Java SE)</strong></p><pre>import org.json.JSONObject;<br><br>public void doGet(HttpServletRequest req, HttpServletResponse resp)<br>      throws IOException {<br>    JSONObject obj = new JSONObject(json);<br>    obj.put(&quot;key&quot;, request.getParameter(&quot;value&quot;));<br>}</pre><h4><a href="https://rules.sonarsource.com/java/RSPEC-6287/">Applications should not create session cookies from untrusted input</a></h4><p>Session Cookie Injection occurs when a web application assigns session cookies to users using untrusted data.</p><p>Session cookies are used by web applications to identify users. Thus, controlling these enable control over the identity of the users within the application.</p><p>The injection might occur via a GET parameter, and the payload, for example, <a href="https://example.com/?cookie=injectedcookie">https://example.com?cookie=injectedcookie</a>, delivered using phishing techniques.</p><p><strong>Non Compliant Code</strong></p><pre>protected void doGet(HttpServletRequest request, HttpServletResponse response)<br>       throws IOException {<br>    Optional&lt;Cookie&gt; cookieOpt =<br>                Arrays.stream(request.getCookies())<br>                      .filter(c -&gt; c.getName().equals(&quot;jsessionid&quot;))<br>                      .findFirst();<br><br>    if (!cookieOpt.isPresent()) {<br>        String cookie = request.getParameter(&quot;cookie&quot;);<br>        Cookie cookieObj = new Cookie(&quot;jsessionid&quot;, cookie);<br>        response.addCookie(cookieObj);<br>    }<br><br>    response.sendRedirect(&quot;/welcome.jsp&quot;);<br>}</pre><p><strong>Compliant Code</strong></p><pre>protected void doGet(HttpServletRequest request, HttpServletResponse response)<br>        throws IOException {<br>    Optional&lt;Cookie&gt; cookieOpt =<br>              Arrays.stream(request.getCookies())<br>                        .filter(c -&gt; c.getName().equals(&quot;jsessionid&quot;))<br>                        .findFirst();<br><br>    if (!cookieOpt.isPresent()) {<br>        response.sendRedirect(&quot;/getCookie.jsp&quot;);<br>    } else {<br>        response.sendRedirect(&quot;/welcome.jsp&quot;);<br>    }<br>}</pre><h4><a href="https://rules.sonarsource.com/java/RSPEC-6863/">Set appropriate Status Codes on HTTP responses</a></h4><p>The request handler function in a Controller should set the appropriate HTTP status code based on the operation’s success or failure. This is done by returning a Response object with the appropriate status code.</p><p>If an exception is thrown during the execution of the handler, the status code should be in the range of 4xx or 5xx.</p><p>The status code should be 1xx, 2xx, or 3xx if no exception is thrown and the operation is considered successful.</p><p><strong>Non Compliant Code</strong></p><pre>@Controller<br>public class UserController {<br>    public ResponseEntity&lt;User&gt; getUserById(Long userId) {<br>        try {<br>            User user = userService.getUserById(userId);<br>            <br>            // Noncompliant: Setting 500 for a successful operation<br>            return ResponseEntity<br>                        .status(HttpStatus.INTERNAL_SERVER_ERROR)<br>                        .body(user);<br>        } catch (Exception e) {<br>            // Noncompliant: Setting 200 for exception<br>            return ResponseEntity.status(HttpStatus.OK).build(); <br>        }<br>    }<br>}</pre><p><strong>Compliant Code</strong></p><pre>@Controller<br>public class UserController {<br>    public ResponseEntity&lt;User&gt; getUserById(Long userId) {<br>        try {<br>            User user = userService.getUserById(userId);<br><br>            // Compliant: Setting 200 for a successful operation<br>            return ResponseEntity.ok(user); <br>        } catch (Exception e) {<br>            // Compliant: Setting 500 for exception<br>            return ResponseEntity<br>                        .status(HttpStatus.INTERNAL_SERVER_ERROR)<br>                        .build(); <br>        }<br>    }<br>}</pre><blockquote>Note: In this example, if we couldn’t find a user with the specified “userId”, the return status would be 4xx. Because there were no issue in the system and its the client fault that passed a userId that is not valid in the system.</blockquote><h4><a href="https://rules.sonarsource.com/java/RSPEC-6816/">Nullable injected fields and parameters should provide a default value</a></h4><p>The @Value annotation does not guarantee that the property is defined. Particularly if a field or parameter is annotated as nullable, it indicates that the developer assumes that the property may be undefined.</p><p>An undefined property may lead to a runtime exceptions when the Spring framework tries to inject the autowired dependency during bean creation.</p><p><strong>Non Compliant Code</strong></p><pre>@Nullable<br>@Value(&quot;${my.property}&quot;) <br>private String myProperty;</pre><p><strong>Compliant Code</strong></p><pre>@Nullable<br>@Value(&quot;${my.property:#{null}}&quot;) // Compliant, a default value is provided<br>private String myProperty;</pre><h4><a href="https://rules.sonarsource.com/java/RSPEC-6417/">Collections should not be modified while they are iterated</a></h4><p>This rule raises an issue when a method modifies the size of a collection, while the same collection is iterated.</p><p><strong>Non Compliant Code</strong></p><pre>public static void foo(List&lt;String&gt; lst) {<br>    for (String element : lst) {<br>      if (element.startsWith(&quot;x&quot;)) {<br>        // Noncompliant: lst size has been modified by &quot;remove&quot; call while it&#39;s iterated.<br>        lst.remove(element); <br>      }<br>    }<br>  }</pre><p><strong>Compliant Code</strong></p><pre>public static void foo(List&lt;String&gt; lst) {<br>  List&lt;String&gt; toRemove = new ArrayList&lt;&gt;();<br>  for (String element : lst) {<br>    if (element.startsWith(&quot;x&quot;)) {<br>      toRemove.add(element);<br>    }<br>  }<br>  lst.removeAll(toRemove);<br>}</pre><p><strong>Side Note</strong>: Using stream api is better option:</p><pre>return lst.stream.filter(e -&gt; !e.startsWith(&quot;x&quot;)).toList();</pre><h4><a href="https://rules.sonarsource.com/java/RSPEC-5960/">Assertions should not be used in production code</a></h4><p>Assertions are intended to be used in <strong>test</strong> code, but not in <strong>production</strong> code. It is confusing, and might lead to ClassNotFoundException when the build tools only provide the required dependency in test scope.</p><h4><a href="https://rules.sonarsource.com/java/RSPEC-5863/">Assertions should not compare an object to itself</a></h4><p>Assertions comparing an object to itself are more likely to be bugs due to developer’s carelessness.</p><p><strong>Non Compliant Code</strong></p><pre>assertThat(actual).isEqualTo(actual); // Noncompliant</pre><p><strong>Compliant Code</strong></p><pre>assertThat(actual).isEqualTo(expected);</pre><h4><a href="https://rules.sonarsource.com/java/RSPEC-3959/">Consumed Stream pipelines should not be reused</a></h4><p>Stream operations are divided into intermediate and terminal operations, and are combined to form stream pipelines. After the terminal operation is performed, the stream pipeline is considered consumed, and cannot be used again. Such a reuse will yield unexpected results.</p><p><strong>Non Compliant Code</strong></p><pre>Stream&lt;Widget&gt; pipeline = widgets.stream().filter(b -&gt; b.getColor() == RED);<br>int sum1 = pipeline.sum();<br>int sum2 = pipeline.mapToInt(b -&gt; b.getWeight()).sum(); // Noncompliant</pre><h4><a href="https://rules.sonarsource.com/java/RSPEC-3958/">Intermediate Stream methods should not be left unused</a></h4><p>There are two types of stream operations: intermediate operations, which return another stream, and terminal operations, which return something other than a stream. Intermediate operations are lazy, meaning they aren’t actually executed until and unless a terminal stream operation is performed on their results. Consequently, if the result of an intermediate stream operation is not fed to a terminal operation, it serves no purpose, which is almost certainly an error.</p><p><strong>Non Compliant Code</strong></p><pre>widgets.stream().filter(b -&gt; b.getColor() == RED); // Noncompliant</pre><p><strong>Compliant Code</strong></p><pre>int sum = widgets.stream()<br>                      .filter(b -&gt; b.getColor() == RED)<br>                      .mapToInt(b -&gt; b.getWeight())<br>                      .sum();<br>Stream&lt;Widget&gt; pipeline = widgets.stream()<br>                                 .filter(b -&gt; b.getColor() == GREEN)<br>                                 .mapToInt(b -&gt; b.getWeight());<br>sum = pipeline.sum();</pre><h4><a href="https://rules.sonarsource.com/java/RSPEC-3346/">Expressions used in “assert” should not produce side effects</a></h4><p>Since assert statements aren’t executed by default, developers should never rely on their execution the evaluation of any logic required for correct program function.</p><p><strong>Non Compliant Code</strong></p><pre>assert myList.remove(myList.get(0));  // Noncompliant</pre><p><strong>Compliant Code</strong></p><pre>boolean removed = myList.remove(myList.get(0));<br>assert removed;</pre><h4><a href="https://rules.sonarsource.com/java/RSPEC-2111/">“BigDecimal(double)” should not be used</a></h4><p>The BigDecimal is used to represents immutable, arbitrary-precision signed decimal numbers.</p><p>Differently from the BigDecimal, the double primitive type and the Double type have limited precision due to the use of double-precision 64-bit IEEE 754 floating point. Because of floating point imprecision, the BigDecimal(double) constructor can be somewhat unpredictable.</p><p><strong>Non Compliant Code</strong></p><pre>double d = 1.1;<br><br>BigDecimal bd1 = new BigDecimal(d);   // Noncompliant<br>BigDecimal bd2 = new BigDecimal(1.1); // Noncompliant</pre><p><strong>Compliant Code</strong></p><pre>double d = 1.1;<br><br>BigDecimal bd1 = BigDecimal.valueOf(d); // Compliant<br>BigDecimal bd2 = new BigDecimal(&quot;1.1&quot;); // Compliant</pre><h4><a href="https://rules.sonarsource.com/java/RSPEC-5145/">Logging should not be vulnerable to injection attacks</a></h4><p>Log injection occurs when an application fails to sanitize untrusted data used for logging.</p><p>An attacker can forge log content to prevent an organization from being able to trace back malicious activities.</p><p><strong>Non Compliant Code</strong></p><pre>private static final Logger logger = Logger.getLogger(&quot;Logger&quot;);<br><br>protected void doGet(HttpServletRequest request, HttpServletResponse response) <br>      throws IOException {<br><br>  String data = request.getParameter(&quot;data&quot;);<br>  if(data != null){<br>    logger.log(Level.INFO, &quot;Data: {0} &quot;, data);<br>  }<br>}</pre><p><strong>Compliant Code</strong></p><pre>private static final Logger logger = Logger.getLogger(&quot;Logger&quot;);<br><br>protected void doGet(HttpServletRequest request, HttpServletResponse response)<br>       throws IOException {<br><br>  String data = request.getParameter(&quot;data&quot;);<br>  if(data != null){<br>    data = data.replaceAll(&quot;[\n\r]&quot;, &quot;_&quot;);<br>    logger.log(Level.INFO, &quot;Data: {0} &quot;, data);<br>  }<br>}</pre><h4><a href="https://rules.sonarsource.com/java/RSPEC-3599/">Double Brace Initialization should not be used</a></h4><p>Because Double Brace Initialization (DBI) creates an anonymous class with a reference to the instance of the owning object, its use can lead to memory leaks if the anonymous inner class is returned and held by other objects. Even when there’s no leak, DBI is so obscure that it’s bound to confuse most maintainers.</p><p><strong>Non Compliant Code</strong></p><pre>Map source = new HashMap(){{ // Noncompliant<br>    put(&quot;firstName&quot;, &quot;John&quot;);<br>    put(&quot;lastName&quot;, &quot;Smith&quot;);<br>}};</pre><p><strong>Compliant Code</strong></p><pre>Map source = new HashMap();<br>// ...<br>source.put(&quot;firstName&quot;, &quot;John&quot;);<br>source.put(&quot;lastName&quot;, &quot;Smith&quot;);<br>// ...</pre><p><strong>Side Note</strong>: Using “.of()” method is better option here:</p><pre>Map&lt;String,String&gt; source = Map.of(&quot;firstName&quot;, &quot;John&quot;, &quot;lastName&quot;, &quot;Smith&quot;);</pre><h4><a href="https://rules.sonarsource.com/java/RSPEC-3306/">Constructor injection should be used instead of field injection</a></h4><p>Field injection seems like a tidy way to get your classes what they need to do their jobs, but it’s really a NullPointerException waiting to happen unless all your class constructors are private. That’s because any class instances that are constructed by callers, rather than instantiated by a Dependency Injection framework compliant with the JSR-330 (Spring, Guice, …​), won’t have the ability to perform the field injection.</p><p><strong>Non Compliant Code</strong></p><pre>class MyComponent {  // Anyone can call the default constructor<br><br>  @Inject MyCollaborator collaborator;  // Noncompliant<br><br>  public void myBusinessMethod() {<br>    collaborator.doSomething();  // this will fail in classes new-ed by a caller<br>  }<br>}</pre><p><strong>Compliant Code</strong></p><pre>class MyComponent {<br><br>  private final MyCollaborator collaborator;<br><br>  @Inject<br>  public MyComponent(MyCollaborator collaborator) {<br>    Assert.notNull(collaborator, &quot;MyCollaborator must not be null!&quot;);<br>    this.collaborator = collaborator;<br>  }<br><br>  public void myBusinessMethod() {<br>    collaborator.doSomething();<br>  }<br>}</pre><p><strong>Side Note</strong>: In newly version of Spring Boot, dependency injection works fine without using annotations for “final” fields.</p><h3>References</h3><p>For more information about the bugs and vulnerabilities, check the link here:</p><p><a href="https://rules.sonarsource.com/">SonarSourcestatic code analysissince2008</a></p><p>Checkout SonarLint for Intellij IDEA</p><p><a href="https://plugins.jetbrains.com/plugin/7973-sonarlint">SonarLint - IntelliJ IDEs Plugin | Marketplace</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cdef2ea0d303" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/top-java-static-code-analysis-rules-by-sonar-bugs-vulnerabilities-security-hotspots-cdef2ea0d303">Top Java Static Code Analysis Rules By Sonar: Bugs, Vulnerabilities, Security Hotspots</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Git: Git Objects]]></title>
            <link>https://towardsdev.com/mastering-git-git-objects-cc4fbf0a9bcd?source=rss-10919b3a8296------2</link>
            <guid isPermaLink="false">https://medium.com/p/cc4fbf0a9bcd</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[git]]></category>
            <category><![CDATA[version-control]]></category>
            <category><![CDATA[software]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Amirhosein Gharaati]]></dc:creator>
            <pubDate>Mon, 12 Feb 2024 19:15:11 GMT</pubDate>
            <atom:updated>2024-02-16T17:12:26.694Z</atom:updated>
            <content:encoded><![CDATA[<p>There are multiple concepts about Git internals like Objects, References, Packfiles, and more.</p><p>In Git, objects are fundamental entities that represent different types of data in the repository. For example blobs, trees, commits . . .</p><p>To understand the Git better what exactly happens behind the scenes, we will explore git objects in this article.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LMK3L11-RTrW7NNVKpGNVQ.png" /></figure><h3>Blob Objects</h3><p>Git is a content-addressable file system.</p><p>At the core of Git is a simple key-value data store. What this means is that you can insert any kind of content into a Git repository, for which Git will hand you back a unique key you can use later to retrieve that content.</p><p>So we can say it is like a <strong>key-value </strong>store which:</p><ul><li><strong>the key is the hash of the data</strong></li><li><strong>the value is the data</strong></li></ul><p>And we can use the key to retrieve the data.</p><h4>The Key</h4><p>As most of you noticed, the key is the <strong>SHA-1 hash</strong> — a checksum of the content you’re storing plus a header (which you’ll learn about in a bit).</p><p>SHA1 Is a <strong>cryptographic hash function</strong>. If you give a piece of data, it produces a <strong>40-digit hexadecimal number.<br></strong>And as may you know, the value should always be the same if the given input is the same.</p><h4>The Value</h4><p>This object type that git is storing in the repository is called a <strong>blob.</strong></p><p>Let’s simplify the structure. We separate the blob value into two groups:</p><ol><li>header</li><li>content</li></ol><p><strong>Header</strong></p><p>The header is made up of three elements:</p><ol><li>the identifier <strong>blob </strong>(or tree)</li><li>size of the content in bytes</li><li>\0 delimiter</li></ol><p><strong>Content</strong></p><p>It is the data that you are storing in a file like a “what is up, doc?” text.</p><blockquote>Git <strong>compresses</strong> the content with Zlib.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1022/1*SNstiSqL4bZ775wI4sitGg.png" /></figure><p>Let’s see it in action!</p><p>If you pass the text above to the hash-object command in git, you will see a hash output.</p><pre>echo &quot;what is up, doc?&quot; | git hash-object --stdin</pre><p>output:</p><pre>7108f7ecb345ee9d0084193f147cdad4d2998293</pre><blockquote><em>git hash-object</em> would take the content you handed to it and merely return the unique key that <strong>would</strong> be used to store it in your Git database.</blockquote><blockquote>the --stdin option tells git hash-object to get the content to be processed from stdin; otherwise, the command would expect a filename argument at the end of the command containing the content to be used.</blockquote><p>Now let’s examine the structure and see if the hash will be the same or not.</p><p>I will use the shasum command to directly generate the hash for the content I will pass to it:</p><pre>echo -e &#39;blob 17\0what is up, doc?&#39; | shasum</pre><p>output:</p><pre>7108f7ecb345ee9d0084193f147cdad4d2998293</pre><p>The hashes are the same!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1022/1*AHHqolVcsVSFTqT-XYIeRw.png" /></figure><p>The blobs are stored in the “.git/objects directory (the <strong>object database</strong>)”. If you use tree .git command you will see the folder structure:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/625/1*i-wo5OBcaJKQtz3jOcsd0A.png" /><figcaption>.git/objects directory (the <strong>object database</strong>)</figcaption></figure><p><strong>This object type is called a blob.</strong></p><p>The first two characters are considered as a folder, and the rest are the characters of the hash value.</p><blockquote>You can see the content by using this command:</blockquote><blockquote>git cat-file -p &lt;hash-value&gt;</blockquote><h3>Tree Objects</h3><p>There is a key point here that the blob does not have some information like the filename or directory structure.</p><p>The next type of Git object is the <strong>tree </strong>which solves the problem of storing the filename and also allows you to store a group of files together.</p><p>Git stores content like a UNIX filesystem, but a bit simplified.</p><p>All the content is stored as tree and blob objects, with <strong>trees corresponding to UNIX directory entries</strong> and <strong>blobs corresponding more or less to inodes or file contents</strong>.</p><p>A tree contains pointers to blobs or other trees, and it has some metadata like the <strong>type of the pointer</strong>, <strong>filename, mode(executable or symbolink, …).</strong></p><p>Following the previous repository, let’s create a directory and copy the file in it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/248/1*oZnPk6FL0IYrIDFKRqwlwg.png" /></figure><p>The main tree object in git will be something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zSklnXWWDOjunTUUIRVa9w.png" /></figure><p>In more detail:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-kdN9AI47Vv1mCF7GwcSBQ.png" /></figure><p>Notice that the “hello-copy.txt” hash value is the same with as the “hello.txt” file. Why? Because the content are same.</p><p><strong>Identical content is stored only once!</strong></p><p>If we examine the tree of the “test” directory, we see a blob that was stored before.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CC04xJMmQvH_zJEx92zeJQ.png" /></figure><p>So if you have multiple files and folders in your git repository, the structure will be something like this: <strong>trees point to blobs and other trees.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/497/1*YFX7UfyA4-5XSh3RufzG3w.png" /></figure><blockquote>Notice that <strong>no leaf is a tree!</strong> This is because git tracks blob objects rather than tree objects. This is the reason that you can’t store empty directories in the repository.</blockquote><h3>Commit Objects</h3><p>So git stores different snapshots of your project that you want to track.</p><p>There is a big problem here: you must remember all SHA-1 values to recall the snapshots.<br>You also don’t have any information about who saved the snapshots, when they were saved, or why they were saved.</p><p>This is the basic information that the commit object stores for you. <strong>A commit points to a tree</strong> and contains: <strong>author, parent commits, author and committer, and commit message:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MP82Z9YS_3v6Nwuz9CtTgw.png" /></figure><p><strong>And the commits can not change!</strong></p><p>If you change any data about the commit, the commit will have a new SHA1 hash. Even if the files don’t change, the created date will.</p><p>You can see more information about git objects in the main documentation:</p><p><a href="https://git-scm.com/book/en/v2/Git-Internals-Git-Objects">Git - Git Objects</a></p><p>If you liked my article, please give me feedback to improve and write more! :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cc4fbf0a9bcd" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/mastering-git-git-objects-cc4fbf0a9bcd">Mastering Git: Git Objects</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Git: Cherry Pick]]></title>
            <link>https://levelup.gitconnected.com/mastering-git-cherry-pick-708ad5950460?source=rss-10919b3a8296------2</link>
            <guid isPermaLink="false">https://medium.com/p/708ad5950460</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[cherry-picking]]></category>
            <category><![CDATA[version-control]]></category>
            <category><![CDATA[git]]></category>
            <dc:creator><![CDATA[Amirhosein Gharaati]]></dc:creator>
            <pubDate>Tue, 21 Nov 2023 16:17:17 GMT</pubDate>
            <atom:updated>2023-11-21T16:17:17.570Z</atom:updated>
            <content:encoded><![CDATA[<p>Cherry-picking in git means choosing a commit from one branch and applying it to another.</p><p>It is a useful tool but <strong>not always a best practice</strong>. Cherry picking can cause duplicate commits and many scenarios where cherry picking would work, traditional merges are preferred instead.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/913/1*iiAsaJ9wm51TRopXDT_9xg.png" /></figure><h3>Use Cases</h3><h4>Team collaboration</h4><p>Maybe a new product feature has a backend and frontend component. There may be some shared code between to two product sectors. Maybe the backend developer creates a data structure that the frontend will also need to utilize.</p><p>The frontend developer could use git cherry-pick to pick the commit in which this hypothetical data structure was created. This pick would enable the frontend developer to continue progress on their side of the project.</p><h4>Bug hotfixes</h4><p>When a bug is discovered it is important to deliver a fix to end users as quickly as possible. For an example scenario, say a developer has started work on a new feature. During that new feature development they identify a pre-existing bug.</p><p>The developer creates an explicit commit patching this bug. This new patch commit can be cherry-picked directly to the main branch to fix the bug before it effects more users.</p><h4>Undoing changes and restoring lost commits</h4><p>Sometimes a feature branch may go stale and not get merged into main. Sometimes a pull request might get closed without merging. Git never loses those commits and through commands like <a href="https://www.atlassian.com/git/tutorials/git-log">git log</a> and <a href="https://www.atlassian.com/git/tutorials/rewriting-history/git-reflog">git reflog</a> they can be found and cherry picked back to life.</p><h3>How to use cherry-pick</h3><p>Imagine for your application you have different branches on different stages. Your main branch is dev and another branch is for qa team qa.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/434/1*DxQDGDIAjg9pncQ0iHIKtw.png" /></figure><p>Let’s say the “A4” commit is a feature that the QA team is planning to have for a release, but not the “A3” and “A5” commits since they are other features or bugfixes or . . .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/434/1*LMgX1u2fJG0Wkg9kHtwvfg.png" /></figure><p>In this scenario you first check the commit id of the commit you want to apply:</p><pre>git log dev --oneline</pre><p>We assume the commit id of the “A4” is: 82ae636b</p><p>Change your current branch to qa:</p><pre>git checkout qa</pre><p>Then you apply the change you want with cherry-pick command with the id you got from the previous step:</p><pre>git cherry-pick 82ae636b</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/434/1*tnMXS5wlHRMzTGn37qk3Jg.png" /></figure><p>In this case, a new commit will be created on the qa branch which we named: “B2”. If you check the log of the qa branch, you see a new commit with a new id.</p><h3>More Usages</h3><h4>Resolving conflicts</h4><p>Conflicts can occur during cherry-picking if the changes being applied conflict with changes in the target branch. In case of conflicts, Git will pause and ask you to resolve them manually before proceeding with the cherry-pick operation.</p><p>Let’s say you got a conflict in a file name “app.config” after applying the cherry-pick command.</p><p>In this case, open the app.config file in your text editor. You will see Git markers (&lt;&lt;&lt;&lt;&lt;&lt;&lt;, =======, and &gt;&gt;&gt;&gt;&gt;&gt;&gt;) indicating the conflicting changes. Manually resolve the conflict and save the file. (or use a git tool)</p><blockquote>If you encounter difficulties during conflict resolution and want to abort the cherry-pick:</blockquote><blockquote>git cherry-pick --abort</blockquote><blockquote>This option is used to abort the current cherry-pick operation and return the repository to the state it was in before the cherry-pick started.</blockquote><p>After resolving the conflict, stage the changes and continue with the cherry-pick:</p><pre>git add app.config<br>git cherry-pick --continue</pre><h4>Apply multiple commits</h4><p>Using the same cherry-pick command specified above, you can apply multiple commits for cherry-picking by adding multiple commit ids:</p><pre>git cherry-pick &lt;commit-hash1&gt; &lt;commit-hash2&gt;</pre><h4>Apply changes with no commit</h4><p>Usually, the cherry-pick command automatically creates a sequence of commits. The flag “-n” or “--no-commit” applies the changes necessary to cherry-pick each named commit to your working tree and the index, without making any commit.</p><pre>git cherry-pick &lt;commit-hash&gt; -n</pre><h4>Edit commit message on cherry-pick</h4><p>With the “-e” or “-<strong>-</strong>edit” you can edit the commit message interactively before applying the changes.</p><pre>git cherry-pick -e &lt;commit-hash&gt;</pre><h4>Consider Using Rebase Instead</h4><p>If you’re cherry-picking multiple commits, consider using git rebase for a cleaner history, especially when working with feature branches.</p><h3>Summary</h3><p>Cherry picking is a powerful and convenient command that is incredibly useful in a few scenarios.</p><p>Cherry picking should not be misused in place of <a href="https://www.atlassian.com/git/tutorials/using-branches/git-merge">git merge</a> or <a href="https://www.atlassian.com/git/tutorials/rewriting-history/git-rebase">git rebase</a>. The <a href="https://www.atlassian.com/git/tutorials/git-log">git log</a> command is required to help find commits to cherry-pick.</p><h3>References</h3><ul><li><a href="https://www.atlassian.com/git/tutorials/cherry-pick">Git Cherry Pick | Atlassian Git Tutorial</a></li><li><a href="https://git-scm.com/docs/git-cherry-pick">Git - git-cherry-pick Documentation</a></li><li><a href="https://stackoverflow.com/questions/9339429/what-does-cherry-picking-a-commit-with-git-mean">What does cherry-picking a commit with Git mean?</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=708ad5950460" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/mastering-git-cherry-pick-708ad5950460">Mastering Git: Cherry Pick</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Learn Spring Data JPA Practically (Part 2)]]></title>
            <link>https://medium.com/@AG1380/learn-spring-data-jpa-practically-part-2-37d50bf84831?source=rss-10919b3a8296------2</link>
            <guid isPermaLink="false">https://medium.com/p/37d50bf84831</guid>
            <category><![CDATA[database]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[jpa]]></category>
            <dc:creator><![CDATA[Amirhosein Gharaati]]></dc:creator>
            <pubDate>Wed, 08 Nov 2023 11:25:44 GMT</pubDate>
            <atom:updated>2023-11-08T11:25:44.563Z</atom:updated>
            <content:encoded><![CDATA[<p>In the previous part, we talked about how you can design a schema and tables for a Retail system.</p><p>In this part, we are going to talk about how we can use Repositories to use some CRUD operations by interacting with a database.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/828/0*_GFC6xhNHDS0sxt0.png" /></figure><blockquote>Before you start make sure to add the proper properties of your database in application.properties .</blockquote><p>For defining a simple repository for JPA, we extend the JpaRepository by specifying the object name and ID type:</p><pre>public interface ProductRepository extends JpaRepository&lt;Product, Long&gt; {<br>}</pre><p>This repository will be implemented by Spring JPA itself. It has some pre-defined implementations which you can use:</p><p>“findAll”, “deleteAll”, “save”, “saveAll” and . . .</p><p>To use this repository, you have to inject it into your service:</p><pre>@Service<br>public class ProductService {<br>    private final ProductRepository productRepository;<br><br>    public ProductService(ProductRepository productRepository) {<br>        this.productRepository = productRepository;<br>    }<br>}</pre><p>If you have Lombok, you can use @RequiredArgsConstructor to automatically build the constructor for yourself.</p><p>Let’s see what we can do with this repository interface.</p><p>When we try to create a method by ourselves, one way is by only specifying what we want with the method name, JpaRepository will implement it for us.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/871/1*W2MG2RzVy9lp_dLGKRKPzA.png" /></figure><p>This is JPQL which is JPA’s query language enables you to define your query based on your domain instead of the table model. That requires 3 steps. You need to:</p><ol><li>Define and instantiate the query</li><li>Set all bind parameter values</li><li>Execute the query</li></ol><p>There are some popular pre-defined queries in JPQL:</p><ul><li>find</li><li>delete</li><li>exists</li><li>count</li><li>update</li></ul><p>When you want to query for multiple things, you should use All keyword after those words.</p><p>Be aware that if you find a single entity, it will return an Optional .</p><p>Now if we want to query based on a specific field, we should mention the field name. For example, I want to query all products whose prices are equal to 10:</p><pre>public interface ProductRepository extends JpaRepository&lt;Product, Long&gt; {<br>    List&lt;Product&gt; findAllByPriceEquals(int price);<br>}</pre><p>There are some other keywords you can use while defining your query with the function. For example, here we say Equals to specify the Price field should be equal to the parameter we pass.</p><blockquote>See a list of reserved keyword queries in this link: <a href="https://openjpa.apache.org/builds/1.2.3/apache-openjpa/docs/jpa_langref.html">https://openjpa.apache.org/builds/1.2.3/apache-openjpa/docs/jpa_langref.html</a></blockquote><p>Let’s define some queries:</p><p>We want to find a product by its name. It may not exist though:</p><pre>public interface ProductRepository extends JpaRepository&lt;Product, Long&gt; {<br>    Optional&lt;Product&gt; findByName(String name);<br>}</pre><p>findBy<strong>Name: </strong>which we should pass the field. Notice it returns an <strong>Optional</strong>. Because it may not find the product.</p><p>Now imagine you need only just first 10 products in the system. This is something called <strong>paging. </strong>For pagination in JPA, we can achieve it by using this:</p><pre>public interface ProductRepository extends JpaRepository&lt;Product, Long&gt; {<br>    Page&lt;Product&gt; findUsingPaging(Pageable pageable);<br>}</pre><p>The name of the function does not do any some sort of specific thing, it is just a simple name, and you can use it in your service like this:</p><pre>@Service<br>public class ProductService {<br>    private final ProductRepository productRepository;<br><br>    public ProductService(ProductRepository productRepository) {<br>        this.productRepository = productRepository;<br>    }<br><br>    public Page&lt;Product&gt; findByPageable() {<br>        int pageNumber = 1;<br>        int pageSize = 10;<br>        String fileNameToSortBy = &quot;...&quot;;<br><br>        Pageable pageable = PageRequest.of(<br>                pageNumber,<br>                pageSize,<br>                Sort.by(Sort.Direction.ASC, fileNameToSortBy)<br>        );<br>        return productRepository.findUsingPaging(pageable);<br>    }<br><br>}</pre><p>You should create a pageable, and then pass it to the repository based on the properties you want.</p><p>You can also write your queries (if you see JPA does not support). This is a simple example:</p><pre>public interface ProductRepository extends JpaRepository&lt;Product, Long&gt; {<br>    @Query(&quot;SELECT p FROM Product p WHERE p.price &gt; :threshold&quot;)<br>    List&lt;Product&gt; findProductsAbovePrice(@Param(&quot;threshold&quot;) int threshold);<br>}</pre><p>Using a parameter “threshold”, we need to get all products whose price is above this. So I can write SQL and my database is PostgreSQL. If it was MongoDB for example, then you would write Mongodb aggregation.</p><p>If you want to check if a product exists in your database, you would use the “exists” keyword:</p><pre>public interface ProductRepository extends JpaRepository&lt;Product, Long&gt; {<br>    boolean existsByName(String name);<br>}</pre><p>The thing is that you only need to check if something exists in your database. You don’t need to load it. So it would have higher performance.</p><p>You can implement your repository for more customization:</p><pre>public interface ProductCustomRepository {<br>    Optional&lt;Product&gt; findProductByName(String name); // my method<br>}</pre><p>You should implement your code:</p><pre>@Repository<br>public class ProductCustomRepositoryImpl implements ProductCustomRepository {<br>    @Override<br>    public Optional&lt;Product&gt; findProductByName(String name) {<br>        // TODO<br>        return Optional.empty();<br>    }<br>}</pre><blockquote>Don’t forget @Repository annotation.</blockquote><p>It is your time to investigate the schema and implement the queries you need.</p><p>You can do magic things with Spring Data JPA. More features are implemented in spring data JPA which you can read and find in the documentation:</p><p><a href="https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repositories.custom-implementations">Spring Data JPA - Reference Documentation</a></p><h3>Conclusion</h3><p>One part of spring data JPA is Repositories which there are multiple features which you find there.</p><p>Don’t forget to give feedback about your learning!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=37d50bf84831" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Learn Spring Data JPA Practically (Part 1)]]></title>
            <link>https://levelup.gitconnected.com/learn-spring-data-jpa-practically-part-1-89b5af0ad120?source=rss-10919b3a8296------2</link>
            <guid isPermaLink="false">https://medium.com/p/89b5af0ad120</guid>
            <category><![CDATA[spring-data-jpa]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[postgres]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Amirhosein Gharaati]]></dc:creator>
            <pubDate>Tue, 17 Oct 2023 00:42:26 GMT</pubDate>
            <atom:updated>2023-11-07T20:01:56.590Z</atom:updated>
            <content:encoded><![CDATA[<p>Spring Data JPA stands out as a powerful tool for making database interactions more straightforward and efficient.</p><p>This technology simplifies the way developers work with relational databases, making it a valuable asset for anyone looking to streamline data access within their Java applications.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/858/1*NHm1dtrhWoT7ghI_JuFAVw.png" /></figure><p>Let’s implement a simple Retail system schema with Spring Data JPA and PostgreSQL.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*op2t_ZAeDhyh8ZFXP3WG6Q.jpeg" /></figure><p>Checkout the final code in this repository:<br><a href="https://github.com/AmirHosein-Gharaati/spring-jpa">https://github.com/AmirHosein-Gharaati/spring-jpa</a></p><p>In this project we “Lombok” library for simplicity.</p><h3>Schema Implementation</h3><p>Let’s start with the Customer “entity”.</p><h4>Customer</h4><pre>@Entity(name = &quot;Customer&quot;)<br>@Table(name = &quot;customer&quot;)<br>@Getter<br>@NoArgsConstructor<br>public class Customer {<br>    @Id<br>    @SequenceGenerator(<br>            name = &quot;customer_sequence&quot;,<br>            sequenceName = &quot;customer_sequence&quot;,<br>            allocationSize = 1<br>    )<br>    @GeneratedValue(<br>            strategy = GenerationType.SEQUENCE,<br>            generator = &quot;customer_sequence&quot;<br>    )<br>    private Long id;<br><br>    @Column(nullable = false)<br>    private String firstName;<br><br>    @Column(nullable = false)<br>    private String lastName;<br><br>    @Column(nullable = false, unique = true)<br>    private String email;<br><br>    private String address;<br>}</pre><p>There are some annotations that we used here:</p><p><strong>Entity</strong></p><blockquote>Declares that the class definition will correspond to a database table with a similar name.</blockquote><p>For defining an entity in our system, we have to annotate the class using @Entity annotation, and we defined its name similar to the class name.</p><p><strong>Table</strong></p><blockquote>Allows you to specify the details of the table that will be used to persist the entity in the database.</blockquote><p>We wanted to use a table for this entity in our database. So we have to use @Table annotation. I used the customer name for the customer entity in this example.</p><p><strong>What is the difference between name attributes in Entity and Table?</strong></p><p>@Entity(name = &quot;someThing&quot;) =&gt; This name will be used to identify the domain. This name will only be identified by HQL queries. i.e. name of the domain object.</p><p>@Table(name = &quot;someThing&quot;) =&gt; This name will be used to which table referred by the domain object. i.e. name of the table.</p><p><strong>Id</strong></p><blockquote>Applied to a member of a class to designate that this member will uniquely identify the entity in the database.</blockquote><p>For marking the field property as a primary key of the entity we use @Id annotation.</p><p><strong>SequenceGenerator</strong></p><blockquote>Defines a primary key generator that may be referenced by name when a generator element is specified for the GeneratedValue annotation.</blockquote><p>For generating the primary key based on a sequence, we use @SequenceGenerator annotation. This annotation is not mandatory.</p><p>There are 3 attributes here:</p><ul><li><strong>name (Required): </strong>The name of the sequence we use in our application. This will be used in the @GeneratedValue annotation.</li><li><strong>sequenceName: </strong>The name of the sequence that will be generated in the database.</li><li><strong>allocationSize: </strong>An int value that must match the increment size of the database sequence object.</li></ul><p><strong>GeneratedValue</strong></p><blockquote>Used with parameters alongside @Id to designate how an entity’s unique ID value will be generated.</blockquote><p>There are 2 attributes here:</p><ul><li><strong>strategy</strong>: The strategy for generating the sequence</li><li><strong>generator</strong>: The name of the sequence if you have provided in @<em>SequenceGenerator</em><strong>.</strong></li></ul><p>There are 4 options to generate primary keys:</p><ul><li>AUTO</li><li>IDENTITY</li><li>SEQUENCE</li><li>TABLE</li></ul><p>Read the explanation <a href="https://stackoverflow.com/questions/47676403/spring-generatedvalue-annotation-usage">here</a> if you want to choose the proper one.</p><p><strong>Column</strong></p><blockquote>Allows developers to customize the mapping between Java class fields and database columns.</blockquote><p>This annotation is not mandatory, but for modifying and changing the column attributes is needed.</p><p>There are different attributes for this annotation:</p><ul><li><strong>name</strong>: the name of the database column. If not provided, the default column name is derived from the field name.</li><li><strong>nullable: </strong>Defines whether the column can contain null values. By default, columns are nullable.</li><li><strong>unique: </strong>Indicates whether the column must contain unique values.</li><li><strong>length: </strong>Sets the maximum length of the column for <em>string-based</em> fields.</li><li><strong>precision and scale: </strong>Used for decimal-based fields to specify the precision and scale of the column.</li><li><strong>insertable and updatable: </strong>Control whether the column should be included during INSERT and UPDATE operations.</li><li><strong>columnDefinition: </strong>The SQL fragment that is used when generating the DDL for the column. This is used for more configuration.</li></ul><p>Moving on the next entity:</p><p><strong>Order</strong></p><pre>@Table(name = &quot;order_table&quot;)<br>@Entity(name = &quot;Order&quot;)<br>@NoArgsConstructor<br>@Getter<br>public class Order {<br>    @Id<br>    @SequenceGenerator(<br>            name = &quot;order_sequence&quot;,<br>            sequenceName = &quot;order_sequence&quot;<br>    )<br>    @GeneratedValue(<br>            strategy = GenerationType.SEQUENCE,<br>            generator = &quot;order_sequence&quot;<br>    )<br>    @Column<br>    private Long id;<br><br>    @Column(<br>            nullable = false<br>    )<br>    private int totalPrice;<br><br>    @ManyToOne<br>    @JoinColumn(<br>            name = &quot;customer_id&quot;,<br>            nullable = false,<br>            referencedColumnName = &quot;id&quot;,<br>            foreignKey = @ForeignKey(<br>                    name = &quot;order_customer_fk&quot;<br>            )<br>    )<br>    private Customer customer;<br><br>    @Temporal(TemporalType.TIMESTAMP)<br>    @Column(<br>            nullable = false,<br>            updatable = false,<br>            columnDefinition = &quot;TIMESTAMP WITHOUT TIME ZONE&quot;<br>    )<br>    @CreatedDate<br>    private LocalDateTime createdAt;<br>}</pre><p>Order entity has a Many to One relation with the Customer. We can achieve this relation easily.</p><p><strong>ManyToOne</strong></p><blockquote>Allows you to define Many-to-one relationships between entity classes</blockquote><p>Note that the first word “Many” refers to the entity itself. The word “One” relates to the target entity (here is Customer). So it means many Orders can have a Customer.</p><p><strong>JoinColumn</strong></p><blockquote>Specifies a column for joining an entity association or element collection. If the <em>JoinColumn</em> annotation itself is defaulted, a single join column is assumed and the default values apply.</blockquote><p>For doing the join operation, specifying the actual name of the column, referenced column name, and… we use this annotation.</p><p>There are different attributes for this annotation:</p><ul><li><strong>name: </strong>The name of the foreign key column.</li><li><strong>referencedColumnName: </strong>The name of the column referenced by this foreign key column.</li><li><strong>foreignKey: </strong>The foreign key constraint specification for the join column. This is used only if table generation is in effect.</li></ul><p>Also we have to add a field for this one to many relation in Customer:</p><pre>public class Customer {<br>    ...<br><br>    @OneToMany(<br>            orphanRemoval = true,<br>            mappedBy = &quot;customer&quot;,<br>            cascade = {CascadeType.PERSIST, CascadeType.REMOVE}<br>    )<br>    private List&lt;Order&gt; orders;<br>}</pre><p><strong>OneToMany</strong></p><blockquote>Here it means: one Customer can have multiple Orders.</blockquote><p>So there are three new attributes for OneToMany annotation:</p><ul><li><strong>orphanRemoval</strong>: Used in a one-to-many relationship to specify whether associated entities should be removed from the database when they are no longer referenced by the parent entity (here parent entity is Order).</li><li><strong>mappedBy</strong>: specifies that the order property in the OrderItem entity is the owner of the relationship. Note that the order property is actually “order_id” in the OrderItem entity.</li><li><strong>cascade</strong>: if you don’t know about cascade, in SQL it is used to simultaneously delete or update (or specify any other operation) an entry from both the child and parent table.</li></ul><p>There are different cascade types in spring data JPA:</p><ol><li><strong>PERSIST</strong>: cascade type persist means that save() or persist() operations cascade to related entities.</li><li><strong>MERGE</strong>: cascade type merge means that related entities are merged when the owning entity is merged.</li><li><strong>REFRESH</strong>: cascade type refresh does the same thing for the refresh() operation.</li><li><strong>REMOVE</strong>: cascade type remove removes all related entities associated with this setting when the owning entity is deleted.</li><li><strong>DETACH</strong>: cascade type detach detaches all related entities if a “manual detach” occurs.</li><li><strong>ALL</strong>: cascade type all is shorthand for all of the above cascade operations.</li></ol><p><strong>Temporal</strong></p><blockquote>This annotation must be specified for persistent fields or properties of type java.util.Date and java.util.Calendar. It may only be specified for fields or properties of these types.</blockquote><p>Generally when we declare a Date field in the class and try to store it,<br>it will be stored as <strong>TIMESTAMP</strong> in the database.</p><p>But I used the TIMESTAMP temporal type. The @CreatedDate annotation is not related to spring data JPA. Read more about them here: <a href="https://docs.spring.io/spring-data/jpa/docs/1.7.0.DATAJPA-580-SNAPSHOT/reference/html/auditing.html">https://docs.spring.io/spring-data/jpa/docs/1.7.0.DATAJPA-580-SNAPSHOT/reference/html/auditing.html</a></p><p><strong>OrderItem</strong></p><pre>@Table(name = &quot;order_item&quot;)<br>@Entity(name = &quot;OrderItem&quot;)<br>@Getter<br>@NoArgsConstructor<br>public class OrderItem {<br>    @Id<br>    @SequenceGenerator(<br>            name = &quot;order_item_sequence&quot;,<br>            sequenceName = &quot;order_item_sequence&quot;<br>    )<br>    @GeneratedValue(<br>            strategy = GenerationType.SEQUENCE,<br>            generator = &quot;order_item_sequence&quot;<br>    )<br>    @Column<br>    private Long id;<br><br>    @Column(nullable = false)<br>    private int quantity;<br><br>    @Column(nullable = false)<br>    private int price;<br><br>    @ManyToOne<br>    @JoinColumn(<br>            name = &quot;order_id&quot;,<br>            nullable = false,<br>            referencedColumnName = &quot;id&quot;,<br>            foreignKey = @ForeignKey(<br>                    name = &quot;order_item_order_fk&quot;<br>            )<br>    )<br>    private Order order;<br>}</pre><p>Also, we have to add a field in Order for its OneToMany relation:</p><pre>public class Order{<br>   ...<br><br>   @OneToMany(<br>            orphanRemoval = true,<br>            mappedBy = &quot;order&quot;,<br>            cascade = {CascadeType.PERSIST, CascadeType.REMOVE}<br>    )<br>    private List&lt;OrderItem&gt; orderItems;<br>    <br>    ...<br>}</pre><p>Let’s continue with the next entity.</p><p><strong>Product</strong></p><pre>@Table(name = &quot;product&quot;)<br>@Entity(name = &quot;Product&quot;)<br>@Getter<br>@NoArgsConstructor<br>public class Product {<br>    @Id<br>    @SequenceGenerator(<br>            name = &quot;product_sequence&quot;,<br>            sequenceName = &quot;product_sequence&quot;<br>    )<br>    @GeneratedValue(<br>            strategy = GenerationType.SEQUENCE,<br>            generator = &quot;product_sequence&quot;<br>    )<br>    @Column<br>    private Long id;<br><br>    @Column(nullable = false)<br>    private String name;<br><br>    @Column(nullable = false)<br>    private int price;<br><br>    @Column<br>    private String text;<br><br>    @OneToOne(<br>            mappedBy = &quot;product&quot;,<br>            orphanRemoval = true,<br>            cascade = {CascadeType.PERSIST, CascadeType.REMOVE}<br>    )<br>    private OrderItem orderItem;<br>}</pre><p><strong>OneToOne</strong></p><blockquote>For a One-to-One relationship in JPA, each entity instance is related to a single instance of another entity. It means each row of one entity is referred to as one and only one row of another entity.</blockquote><p>So for defining a one-to-one relation, we have to use this annotation in the entity that holds a foreign key.</p><p>Also we have to add OneToOne with JoinColumn in OrderItem:</p><pre>public class OrderItem {<br>    ...<br><br>    @OneToOne<br>    @JoinColumn(<br>            name = &quot;product_id&quot;,<br>            nullable = false,<br>            referencedColumnName = &quot;id&quot;,<br>            foreignKey = @ForeignKey(<br>                    name = &quot;order_item_product_fk&quot;<br>            )<br>    )<br>    private Product product;<br>}</pre><p>The next entity is:</p><p><strong>Category</strong></p><pre>@Table(name = &quot;category&quot;)<br>@Entity(name = &quot;Category&quot;)<br>@NoArgsConstructor<br>@Getter<br>public class Category {<br>    @Id<br>    @SequenceGenerator(<br>            name = &quot;category_sequence&quot;,<br>            sequenceName = &quot;category_sequence&quot;<br>    )<br>    @GeneratedValue(<br>            strategy = GenerationType.SEQUENCE,<br>            generator = &quot;category_sequence&quot;<br>    )<br>    @Column<br>    private Long id;<br><br>    @Column(nullable = false)<br>    private String name;<br>}</pre><p>Also in the category, there is nothing new. But there is a ManyToMany relationship between Category and Product. How can we achieve that?</p><p>We have to define a middle table for Product and Category here. We named it <strong>ProductCategory.</strong></p><p>In this table, we have a composite key: “product_id” and “category_id”</p><p>To create a composite key in spring data JPA, we use @Embeddable .</p><p><strong>Embeddable</strong></p><blockquote>It is going to tell that this is a Composite Id class and can be embedded into an entity bean.</blockquote><p>This would be our composite key class:</p><p><strong>ProductCategoryId</strong></p><pre>@Embeddable<br>@Getter<br>public class ProductCategoryId implements Serializable {<br><br>    @Column(name = &quot;product_id&quot;)<br>    private Long productId;<br><br>    @Column(name = &quot;category_id&quot;)<br>    private Long categoryId;<br>}</pre><p>We annotate the class using @Embeddable and we have to implement the Serializable class from java.io .</p><p>Now we define our middle table for many to many relationships:</p><p><strong>ProductCategory</strong></p><pre>@Table(name = &quot;product_category&quot;)<br>@Entity(name = &quot;ProductCategory&quot;)<br>@Getter<br>public class ProductCategory {<br><br>    @EmbeddedId<br>    private ProductCategoryId id;<br><br>    @ManyToOne<br>    @MapsId(&quot;productId&quot;)<br>    @JoinColumn(<br>            name = &quot;product_id&quot;,<br>            foreignKey = @ForeignKey(<br>                    name = &quot;product_category_product_id_fk&quot;<br>            )<br>    )<br>    private Product product;<br><br>    @ManyToOne<br>    @MapsId(&quot;categoryId&quot;)<br>    @JoinColumn(<br>            name = &quot;category_id&quot;,<br>            foreignKey = @ForeignKey(<br>                    name = &quot;product_category_category_id_fk&quot;<br>            )<br>    )<br>    private Category category;<br>}</pre><p>To embed the composite key class as an Id, we annotate the class using @EmbeddedId .</p><p><strong>MapsId</strong></p><blockquote>Designates a ManyToOne or OneToOne relationship attribute that provides the mapping for an EmbeddedId primary key, an attribute within an EmbeddedId primary key, or a simple primary key of the parent entity.</blockquote><p>So here for the product field, we said “productId” in MapsId, which tells that the field in the composite key named “productId” is responsible for getting the Product entity.</p><p>Same thing for category entities.</p><h3>Conclusion</h3><p>Congratulations! You have implemented the first part of the table design in Spring Boot using Spring Data JPA.</p><p>In the next part, we are going to talk about repositories and how we can interact with the database.</p><p>Generally, it is better to work along with repositories, but since there are lots of things to talk about in spring data JPA, we first talked about the model and design part.</p><h3>Follow More</h3><ul><li><a href="https://www.codecademy.com/learn/learn-spring/modules/spring-data-and-jpa/cheatsheet">Learn Spring: Spring Data and JPA Cheatsheet | Codecademy</a></li><li><a href="https://howtodoinjava.com/hibernate/hibernate-jpa-cascade-types/">Cascade Types in JPA and Hibernate</a></li><li><a href="https://spring.io/projects/spring-data-jpa">Spring Data JPA</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=89b5af0ad120" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/learn-spring-data-jpa-practically-part-1-89b5af0ad120">Learn Spring Data JPA Practically (Part 1)</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Questions Before You Dive into Software Development Books (+ Recommended Books)]]></title>
            <link>https://levelup.gitconnected.com/questions-before-you-dive-into-software-development-books-recommended-books-d22164bd8938?source=rss-10919b3a8296------2</link>
            <guid isPermaLink="false">https://medium.com/p/d22164bd8938</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[books]]></category>
            <dc:creator><![CDATA[Amirhosein Gharaati]]></dc:creator>
            <pubDate>Thu, 12 Oct 2023 01:43:48 GMT</pubDate>
            <atom:updated>2023-10-12T01:43:48.246Z</atom:updated>
            <content:encoded><![CDATA[<p>There are many books out there in the software development area which are great. But maybe not as great as we want?</p><p>So, there are many considerations for reading books. Reading is not enough! What next? Did I waste my time or what?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qnzeLhWCBypkCPiyLhN5IQ.jpeg" /></figure><h3>Table of Contents</h3><ul><li><a href="#4dbb">Introduction</a></li><li><a href="#fee7">Questions Before Reading a Book</a></li><li><a href="#3be5">Recommend Books</a></li><li><a href="#e602">Conclusion</a></li></ul><h3>Introduction</h3><blockquote>Technology marches . . .</blockquote><p>You can not stop or prevent technology from upgrading or giving new tools and concepts. Nobody can! So all of us are somehow in a race in our life, to compete about how we think and how we do.</p><p>So continuous learning is important. Especially in software development. One of the resources that can help you to increase your knowledge is books.</p><p>There are also some other resources like online courses, but most of the courses don’t deep dive into the thing they are talking about (if you found some, don’t miss them too).</p><p>Making informed decisions about what and how to do a job is so important in software development. You have to know different things and consider some factors to make a good decision. Reading books can significantly impact one’s learning journey.</p><p>Now, what book should we read? Do not be in a hurry, there are some questions that you have to answer for yourself.</p><h3>Questions Before Reading a Book</h3><p>Sometimes, there are many factors in selecting a book to read. Reading a book may take a long time. Time is a huge resource. A valuable one. So you should value the book that you are taking your time for that.</p><h4>What Book Should I Read?</h4><p>If you ask me this question to me, I would say: <strong>“The book that meets your requirement”.</strong></p><p>What is the requirement? The task you are working on. The project you are working on. The career you are working on. The goal you trying for.</p><p>We decided to prioritize the requirements and say which one of them was more important at that moment.</p><h4>Is Reading That Book Enough? Then What?</h4><p>You know, it is important to <strong>apply the knowledge from that book in practical scenarios.</strong></p><blockquote>A man of words, not of deeds, is like a garden full of weeds.</blockquote><p>Ask the question to yourself: <em>Reading this book for what?</em></p><p>Also looking for supplementary resources, seeking mentorship or guidance, or engaging with the community of learners can be helpful.</p><p>The best case to understand the concept of what I have read was to apply that to the project I am working on. You may look for other cases that you like more.</p><h4>Is It Really Worth Reading That Book?</h4><p>Answering this question <strong>depends on your specific learning objectives, current knowledge level, and the book’s content</strong>.</p><p>The book must be relevant to your goal, have good content quality, applicable. There are some other factors that we talk about in the following questions.</p><h4>What Are My Learning Objectives?</h4><p>I think <strong>without defining an objective and a goal for ourselves, reading a book does not help much</strong>. Why not watch a course? Watching a course is more fun and fast.</p><p>I may ask: What specific skills or knowledge do I want to gain from this book? Are there specific challenges or gaps in my knowledge that I hope this book will address? Do I have a timeline for achieving these objectives?</p><p>If you don’t have an objective or goal for your path, there is a good paragraph in the <a href="https://www.amazon.com/Soft-Skills-software-developers-manual/dp/1617292397">Soft Skills</a> book that says:</p><blockquote>You don’t have to be specific when you define a goal. Your big goal has to be specific enough to give you a clear direction. If I want to sail to China, I don’t have to know the exact latitude and longitude of the port I want to get to right away. When I get close to China, I can always get more specific. All I need to know to get started is whether I’m getting closer to China or further from it.</blockquote><h4>What is the Author’s Credibility and Expertise?</h4><p>This factor is also important while reading a book. Because when someone talks about a specific or general topic, he/she may had an experience about it. The more experience someone may have, the more understandable and valuable that experience is.</p><p>Did the author have professional experience? Did anyone recommend his/her books? How much influence the author had in that field?</p><p>I do like Robert Cecil Martin’s books since most of us hear about his books and the influence he had in software development.</p><h4>Are There Reviews or Recommendations?</h4><p>When most websites recommend some specific books, it may seem that the book looks valuable to read. So the number of recommendations is also important.</p><p>You know, <strong>this would be a kind of feedback</strong> that people say: Hey! This book was amazing! It had some impact on me.</p><p>I say I recommend Robert Cecil Martin’s books. Because they had some impact on me (especially when I applied those skills in a real-life project and got more feedback from my mentors).</p><h4>What is the Book’s Publication Date?</h4><p>This question <strong>depends on the field you want to read</strong>. <a href="https://www.amazon.com/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882">Clean Code</a> was published in 2007, but it is still a reference in software development. But for example, if you want to read about MongoDB in 2023, reading a book about it in 2015 may seem not reasonable since MongoDB changed in the last years.</p><p>If I want to look for a specific tool or technology, I check for the publish date, but for a general concept, it doesn’t matter (personal opinion).</p><h3>Recommended Books</h3><p>I like reading some books in my software development path. If you feel like reading a book for a specific area, these may help you.</p><p><a href="https://www.amazon.com/Soft-Skills-software-developers-manual/dp/1617292397"><strong>Soft Skills: The software developer’s life manual</strong></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/372/0*RjsNirf1v_oM2moD.jpg" /></figure><p>If you care about your path, your goal, your financial skills, and let’s say general concepts in soft skills, this book helps.</p><p>This was one of the best books I have ever read in software development.</p><p>Also, this book doesn’t talk about the communication and negotiation ways between your teammates and colleagues. This book talks about general concepts of ourselves which I think is valuable.</p><p><a href="https://www.amazon.com/Pragmatic-Programmer-journey-mastery-Anniversary/dp/0135957052"><strong>The Pragmatic Programmer, 20th Anniversary Edition</strong></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/340/0*8ExJwEOEjZRDt33k.jpg" /></figure><p>This is kind of a classic book for a software development career.</p><p>It talks about general ideas and things a software developer should consider in his/her career. One of the coolest things I understood in this book is:</p><blockquote>When you don’t know why something is working, when it encounteres a problem, you won’t know why it encountered the problem.</blockquote><p><a href="https://www.amazon.com/Clean-Architecture-Craftsmans-Software-Structure/dp/0134494164"><strong>Clean Architecture: A Craftsman’s Guide to Software Structure and Design</strong></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/357/0*qR5MTcTqBtgSnY1j.jpg" /></figure><p>There are some general concepts in design principles in software development. The most popular one I think is SOLID principles.</p><p>But I have to say, I understood the concepts when I got into real work and experienced the problems we may encounter while developing the software.</p><p>Reading this book is not enough. You have to apply the concepts in real life for some time to see what may happen.</p><p><a href="https://www.amazon.com/Clean-Coder-Conduct-Professional-Programmers/dp/0137081073"><strong>The Clean Coder: A Code of Conduct for Professional Programmers</strong></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/341/0*wc39YKWzyqDnoJKl.jpg" /></figure><p>It is not all about coding and design. Negotiation, estimation, testing, and other important skills while being a team are important.</p><p>In this book some examples of discussion between developers and managers are shown, that illustrates in some situations, how really should behave.</p><p>This book is very good if you want to know more about the soft parts of software development.</p><h3>Conclusion</h3><p>Reading software development books is not just good; <strong>it’s essential</strong> for any aspiring or experienced software engineer.</p><p>Some books provide the foundation upon which you can build your expertise and become a more proficient and adaptable software developer.</p><p>So, the next time you consider whether to pick up that software development book, remember that it’s not merely a good idea — it’s a step towards excellence and growth in the world of software engineering.</p><p>Happy good reading :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d22164bd8938" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/questions-before-you-dive-into-software-development-books-recommended-books-d22164bd8938">Questions Before You Dive into Software Development Books (+ Recommended Books)</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>