<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Pawel Pawlak</title>
    <description>The latest articles on DEV Community by Pawel Pawlak (@developersmill).</description>
    <link>https://dev.to/developersmill</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F853801%2F3db1cc6a-b6e5-4d08-9c05-5455ec2f41d2.jpeg</url>
      <title>DEV Community: Pawel Pawlak</title>
      <link>https://dev.to/developersmill</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/developersmill"/>
    <language>en</language>
    <item>
      <title>Kata challenge – Mumbling</title>
      <dc:creator>Pawel Pawlak</dc:creator>
      <pubDate>Sun, 02 Feb 2025 17:22:59 +0000</pubDate>
      <link>https://dev.to/developersmill/kata-challenge-mumbling-e2f</link>
      <guid>https://dev.to/developersmill/kata-challenge-mumbling-e2f</guid>
      <description>&lt;p&gt;From time to time I try to do challenge myself with some Kata exercise. I found them very helpful in improving my development skills, codding efficiency, and most important algorithmic thinking.&lt;/p&gt;

&lt;p&gt;They reinforce best practices and quick thinking. IMHO regular practice builds some kind of memory patterns and techniques, making coding faster and more intuitive.&lt;/p&gt;

&lt;p&gt;All my challenges I find in the codewars.com page – I highly recommend this page.&lt;/p&gt;

&lt;p&gt;This challenge does not need actually much of the introduction, let the examples show what I mean:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;for this “RqaEzty”, we should get this one: “R-Qq-Aaa-Eeee-Zzzzz-Tttttt-Yyyyyyy”.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;for “RqaEzty”, we should get this one: “R-Qq-Aaa-Eeee-Zzzzz-Tttttt-Yyyyyyy”&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;for “cwAt”, we should get this one: “C-Ww-Aaa-Tttt”&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;and so on…&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;So as the title says… mumbling.&lt;/p&gt;

&lt;p&gt;FYI the parameter of test method is a string which includes only letters from a..z and A..Z.&lt;/p&gt;

&lt;p&gt;Here is my solution:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class Accumul {

    public static String accum(final String text) {
        if (text == null) {
            throw new IllegalArgumentException();
        }
        return IntStream.range(0, text.length())
                .mapToObj(i -&amp;gt; singleCharToWord(text.charAt(i), i))
                .collect(Collectors.joining("-"));
    }

    private static String singleCharToWord(final Character charAt, final int index) {
        return charAt.toString().toUpperCase() + IntStream.range(1, index + 1)
                .mapToObj(i -&amp;gt; String.valueOf(charAt).toLowerCase())
                .collect(Collectors.joining());
    }

}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;and here are some simple tests for that&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class AccumulTest {

    @Test
    public void testWhenGivenNullAsInput() {
        assertThrows(IllegalArgumentException.class, () -&amp;gt; {
            Accumul.accum(null);
        });
    }

    @Test
    public void test() {
        assertEquals("", Accumul.accum(""));
        assertEquals("A", Accumul.accum("a"));
        assertEquals("A-Bb", Accumul.accum("ab"));
        assertEquals("Z-Pp-Ggg-Llll-Nnnnn-Rrrrrr-Xxxxxxx-Qqqqqqqq-Eeeeeeeee-Nnnnnnnnnn-Uuuuuuuuuuu", Accumul.accum("ZpglnRxqenU"));
        assertEquals("N-Yy-Fff-Ffff-Sssss-Gggggg-Eeeeeee-Yyyyyyyy-Yyyyyyyyy-Llllllllll-Bbbbbbbbbbb", Accumul.accum("NyffsGeyylB"));
        assertEquals("M-Jj-Ttt-Kkkk-Uuuuu-Bbbbbb-Ooooooo-Vvvvvvvv-Qqqqqqqqq-Rrrrrrrrrr-Uuuuuuuuuuu", Accumul.accum("MjtkuBovqrU"));
        assertEquals("E-Vv-Iii-Dddd-Jjjjj-Uuuuuu-Nnnnnnn-Oooooooo-Kkkkkkkkk-Mmmmmmmmmm-Mmmmmmmmmmm", Accumul.accum("EvidjUnokmM"));
        assertEquals("H-Bb-Iii-Dddd-Eeeee-Vvvvvv-Bbbbbbb-Xxxxxxxx-Nnnnnnnnn-Cccccccccc-Ccccccccccc", Accumul.accum("HbideVbxncC"));
    }

}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;That would be all, thanks for your time, and till the next time :)&lt;/p&gt;

</description>
      <category>kata</category>
      <category>java</category>
      <category>challenge</category>
    </item>
    <item>
      <title>Sorting in Java – how to, and how not to do it anymore</title>
      <dc:creator>Pawel Pawlak</dc:creator>
      <pubDate>Sun, 21 Jan 2024 15:49:06 +0000</pubDate>
      <link>https://dev.to/developersmill/sorting-in-java-how-to-and-how-not-to-do-it-anymore-59bp</link>
      <guid>https://dev.to/developersmill/sorting-in-java-how-to-and-how-not-to-do-it-anymore-59bp</guid>
      <description>&lt;p&gt;Comments and articles about sorting in java are plenty over the internet, this one will be so called a summary of the examples I have seen in my developers carrier. It will not cover all the basics, but will try to show you some of the possibilities, from the one that I would try to avoid currently, to the ones that I prefer to use now.&lt;/p&gt;

&lt;p&gt;For all testing purpose we will use Car class&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package com.developersmill.sorting.interfaceimpl;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public final class Car{
    private final int yearOfProduction;
    private final int horsePower;
    private final String brand;
    private final String model;
    public Car(int yearOfProduction, int horsePower, 
               String brand, String model) {
        this.yearOfProduction = yearOfProduction;
        this.horsePower = horsePower;
        this.brand = brand;
        this.model = model;
    }
    @Override
    public String toString() {
        return "Car{" +
                "yearOfProduction=" + yearOfProduction +
                ", horsePower=" + horsePower +
                ", brand='" + brand + '\'' +
                ", model='" + model + '\'' +
                '}';
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;and this example list:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;final List&amp;lt;Car&amp;gt; cars = Arrays.asList(
                new Car(1989, 60,"Toyota", "Yaris"),
                new Car(2010, 90,"Mazda", "3"),
                new Car(2004, 110,"Toyota", "Corolla"),
                new Car(1999, 150,"BMW", "5"),
                new Car(2010, 60,"Renault", "Clio"),
                new Car(2016, 70,"Renault", "Twingo"),
                new Car(2021, 190,"Skoda", "Superb"));
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  How not to implement sorting this days
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;1. Implementing Comparable interface&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;First solution, and the oldest one I know, is to implement an interface Comparable, and provide the implementation of the compareTo method in the class we want to sort. We are going to do that in the class Car.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public final class Car implements Comparable&amp;lt;Car&amp;gt; {
    ....
    @Override
    public int compareTo(Car car) {
        return yearOfProduction - car.yearOfProduction;
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;To test our solution simply call sort method on the Collections class&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Collections.sort(cars);
cars.forEach(System.out::println);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Result is:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Car{yearOfProduction=1989, horsePower=60, brand='Toyota', model='Yaris'}
Car{yearOfProduction=1999, horsePower=150, brand='BMW', model='5'}
Car{yearOfProduction=2004, horsePower=110, brand='Toyota', model='Corolla'}
Car{yearOfProduction=2010, horsePower=90, brand='Mazda', model='3'}
Car{yearOfProduction=2010, horsePower=60, brand='Renault', model='Clio'}
Car{yearOfProduction=2016, horsePower=70, brand='Renault', model='Twingo'}
Car{yearOfProduction=2021, horsePower=190, brand='Skoda', model='Superb'}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This solution have two main problems:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;it forces to compare only base on one specific field, that can not be changed.&lt;/li&gt;
&lt;li&gt;it requires changes in the class&lt;/li&gt;
&lt;li&gt;it modifies the input object – mutability&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;2. Provide different implementations of comparators with new classes&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Next solution is about providing new classes that implements the Comparator interface each time we want to change the way our data is sorted.&lt;/p&gt;

&lt;p&gt;For example we want to sort once using the year of production and once using the horse power. We have to implement two classes for that:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;static class YearComparator implements Comparator&amp;lt;Car&amp;gt;{
        @Override
        public int compare(Car o1, Car o2) {
            return o1.yearOfProduction - o2.yearOfProduction;
        }
}
static class HorsePowerComparator implements Comparator&amp;lt;Car&amp;gt;{
        @Override
        public int compare(Car o1, Car o2) {
            return o1.horsePower - o2.horsePower;
        }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Each class implements the Comparator class and provides the implementation of the the compare method. Car class interface Comparator is not needed anymore. Now tests our code:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Collections.sort(cars, new YearComparator()); // sort data using the year of production like in the first example
Collections.sort(cars, new HorsePowerComparator()); // new way of sorting
cars.forEach(System.out::println);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;It can also be directly used using the list of cars itself:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;cars.sort(new HorsePowerComparator());
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Result is:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Car{yearOfProduction=1989, horsePower=60, brand='Toyota', model='Yaris'}
Car{yearOfProduction=2010, horsePower=60, brand='Renault', model='Clio'}
Car{yearOfProduction=2016, horsePower=70, brand='Renault', model='Twingo'}
Car{yearOfProduction=2010, horsePower=90, brand='Mazda', model='3'}
Car{yearOfProduction=2004, horsePower=110, brand='Toyota', model='Corolla'}
Car{yearOfProduction=1999, horsePower=150, brand='BMW', model='5'}
Car{yearOfProduction=2021, horsePower=190, brand='Skoda', model='Superb'}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This solution is much better, but still not perfect. Class do not have to implement the interface, so we do not have to change it at all. We only need to provide the implementation of Comparator classes for each case we want to use.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;3. Using Java streams with mutable list&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Next example shows that sorting can be also done quite easily with the use of Java 8 API.&lt;/p&gt;

&lt;p&gt;Our goal again, is to sort the list of cars, by their year of production. To do so we are going to use the sorted method with the Comparator parameter. It can be done in several ways. First one below shows implementation of Comparator inline, in code as a lambda expression.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;List&amp;lt;Car&amp;gt; sorted = new ArrayList&amp;lt;&amp;gt;();
cars.stream().sorted((car1, car2) -&amp;gt; car1.yearOfProduction - car2.yearOfProduction)
             .forEach(car -&amp;gt; sorted.add(car));
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Second example shows use the of already implemented class YearComparator:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;List&amp;lt;Car&amp;gt; sorted = new ArrayList&amp;lt;&amp;gt;();
cars.stream().sorted(new YearComparator())
             .forEach(car -&amp;gt; sorted.add(car));  
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Those two examples looks much more cleaner that the ones shown in the points 1 and 2, but there is one problem in there – mutability! If we decide to switch to concurrent iteration we will be forced to deal with the thread-safety problems.&lt;/p&gt;

&lt;h2&gt;
  
  
  How to correctly implement sorting this days
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;1. Using the Java 8 streams with collect method&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;All examples that were shown in the point 3 in this article can be fixed by using the collect terminal method. Lets change the last example that was using the ‘new YearComparator()‘ comparator:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;List&amp;lt;Car&amp;gt; sorted = cars.stream()
                .sorted(new YearComparator())
                .collect(Collectors.toList());
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This will solve our problems with the concurrent modifications issues, we do not longer modify existing object.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;2. Functional style with Comparator&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Instead of implementing small classes like e.g. YearComparator we can provide its implementation using the functional style of programming introduced in Java 8. This could look like that:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Comparator&amp;lt;Car&amp;gt; years = (car1, car2) -&amp;gt; car1.yearOfProduction - car2.yearOfProduction;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Example of using this comparator looks like that:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;List&amp;lt;Car&amp;gt; sorted = cars.stream().sorted(years)
                .collect(Collectors.toList());
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Final results look like that now:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Car{yearOfProduction=1989, horsePower=60, brand='Toyota', model='Yaris'}
Car{yearOfProduction=1999, horsePower=150, brand='BMW', model='5'}
Car{yearOfProduction=2004, horsePower=110, brand='Toyota', model='Corolla'}
Car{yearOfProduction=2010, horsePower=60, brand='Renault', model='Clio'}
Car{yearOfProduction=2010, horsePower=90, brand='Mazda', model='3'}
Car{yearOfProduction=2016, horsePower=70, brand='Renault', model='Twingo'}
Car{yearOfProduction=2021, horsePower=190, brand='Skoda', model='Superb'}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;3. Functional style with Function and Comparing&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;When Java 8 was introduced Comparator interface was filled with plenty of static methods. One of those is comparing. It allows to use the Function method as a parameter to use its logic, to create new Comparator. Best would be to show it using an example.&lt;/p&gt;

&lt;p&gt;Imagine we have simple Car POJO class, with no Comparable interface implemented. We want again to sort with the year property. We defined our lambda, to say on what parameter we want to perform sorting:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Function&amp;lt;Car, Integer&amp;gt; year = car -&amp;gt; car.yearOfProduction;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Then we use it as simple as that:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;List&amp;lt;Car&amp;gt; sorted = cars.stream()
                .sorted(Comparator.comparing(year))
                .collect(Collectors.toList());
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This will give us the results we want. We can even go a bit further and define second lambda to sort with the use of horse power and combine those two sorting together!&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Function&amp;lt;Car, Integer&amp;gt; horsePower = car -&amp;gt; car.horsePower;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Sorting first with the year and then with the horsepower would look like that:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;List&amp;lt;Car&amp;gt; sorted = cars.stream()        
     .sorted(Comparator.comparing(year)
     .thenComparing(horsePower))
     .collect(Collectors.toList());
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Conclusion&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;There are various way we can sort our data. I myself find using Java 8 API to have most advantages:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;not mutable data – we never change data we are sorting, always create new results.&lt;/li&gt;
&lt;li&gt;not forced to change the class we are sorting (e.g. implementing Comparable interface).&lt;/li&gt;
&lt;li&gt;provide simple and easy to read lambda definitions.&lt;/li&gt;
&lt;li&gt;combine several ways of sorting.&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>cleancode</category>
      <category>java</category>
      <category>sorting</category>
      <category>comparator</category>
    </item>
    <item>
      <title>Remove null check, use the Optional</title>
      <dc:creator>Pawel Pawlak</dc:creator>
      <pubDate>Thu, 21 Jul 2022 16:13:00 +0000</pubDate>
      <link>https://dev.to/developersmill/remove-null-check-use-the-optional-5ej6</link>
      <guid>https://dev.to/developersmill/remove-null-check-use-the-optional-5ej6</guid>
      <description>&lt;p&gt;Defensive programming seems for years like the only way to go. Now, after years of struggling with the null check, we can benefit from the Optional class that was introduced in the Java 8.&lt;/p&gt;

&lt;p&gt;I am going to show you just a simple, teste of Optional, what can be done with it. You can take it much more further.&lt;/p&gt;

&lt;p&gt;In this example we are going to simply display the number of movies that given user has seen/rented in the current month.&lt;/p&gt;

&lt;p&gt;Here are the basic classes:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public final class RentHistory {

  private Integer totalInThisMonth;

  private Integer totalFromTheBeginning;

  public RentHistory() {
  }

  public RentHistory(Integer totalInThisMonth, Integer totalFromTheBeginning) {
    this.totalInThisMonth = totalInThisMonth;
    this.totalFromTheBeginning = totalFromTheBeginning;
  }

  public RentHistory(Integer totalInThisMonth) {
    this.totalInThisMonth = totalInThisMonth;
  }

  public Integer getTotalInCurrentMonth() {
    return totalInThisMonth;
  }

  public Integer getTotalFromTheBeginning() {
    return totalFromTheBeginning;
  }

}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public final class User {

  private RentHistory rentHistory;

  public User() {
  }

  public User(RentHistory rentHistory) {
    this.rentHistory = rentHistory;
  }

  public RentHistory getRentHistory() {
    return rentHistory;
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now what we want is to display to the user the number of movies he has rented in this month. So the code would look like that:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public final class Test {

  public void displayNumberOfMoviesRentInCurrentMonth(User user) {
    System.out.println("Number of movies user has rented in this month is: " + getTotal(user.getRentHistory()));
  }

  private Integer getTotal(RentHistory history) {
    return history.getTotalInCurrentMonth();
  }

  public static void main(String[] args) {
    Test test = new Test();
    test.displayNumberOfMoviesRentInCurrentMonth(new User(new RentHistory(4)));
  }

}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;What user gets is this: &lt;em&gt;Number of movies user has rented is this month is: 4&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Now what happens if we create Rent history with the default constructor, so without the number of movies he has seen in the current month:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public static void main(String[] args) {
    Test test = new Test();
    test.displayNumberOfMoviesRentInCurrentMonth(new User(new RentHistory()));
  }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We got very pretty text that says: Number of movies user has rented is this month is: null&lt;/p&gt;

&lt;p&gt;For sure this is not that we want our user to see in the UI. What can be done about it, maybe this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public void displayNumberOfMoviesRentInCurrentMonth(User user) {
    System.out.println("Number of movies user has rented in this month is: " + getTotal(user.getRentHistory()));
  }

  private Integer getTotal(RentHistory history) {
    return history.getTotalInCurrentMonth() == null ? 0: history.getTotalInCurrentMonth();
  }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This is the standard defensive approach we used to avoid getting null – add condition, check for the null, and perform action. Now with the use of Optional we can do this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public void displayNumberOfMoviesRentInCurrentMonth(User user) {
    Optional&amp;lt;Integer&amp;gt; total = getTotal(user.getRentHistory());
    if (total.isPresent()) {
      System.out.println("Number of movies user has rented in this month is: " + total.get());
    } else {
      System.out.println("User has not rented any movie in the current month");
    }
  }

  private Optional&amp;lt;Integer&amp;gt; getTotal(RentHistory history) {
    return Optional.ofNullable(history.getTotalInCurrentMonth());
  }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You see what it gave us…. yes, exactly nothing! You should never change the use of regular condition to the use of the isPresent! This is not the way Optional should be used for sure. What should have been done is this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public void displayNumberOfMoviesRentInCurrentMonth(User user) {
    System.out.println(getTotal(user.getRentHistory())
        .map(total -&amp;gt; "Number of movies user has rented in this month is: " + total)
        .orElse("User has not rented any movie in the current month"));
  }

  private Optional&amp;lt;Integer&amp;gt; getTotal(RentHistory history) {
    return Optional.ofNullable(history.getTotalInCurrentMonth());
  }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Remember, when you are dealing with nulls an Optional.map is something you should give a try.&lt;/p&gt;

&lt;p&gt;Now lets talk about the other situation. What will happen if we are going to pass a user that does not have a RentHistory at all, lets check.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  public static void main(String[] args) {
    Test test = new Test();
    test.displayNumberOfMoviesRentInCurrentMonth(new User());
  }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;What we are getting now is this: &lt;em&gt;Exception in thread “main” java.lang.NullPointerException at getTotal(Test.java:15)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;What we can do now is something like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  public void displayNumberOfMoviesRentInCurrentMonth(User user) {
    System.out.println(getTotal(user.getRentHistory())
        .map(total -&amp;gt; "Number of movies user has rented in this month is: " + total)
        .orElse("User has not rented any movie in the current month"));
  }

  private Optional&amp;lt;Integer&amp;gt; getTotal(RentHistory history) {
    if (history == null){
      return Optional.empty();
    }
    return Optional.ofNullable(history.getTotalInCurrentMonth());
  }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Is this is the final solution that we really want, adding a null check, again, defensive programming. Nope, we should not leave it like that, we should do some refactor! First of all we are going to change the User class to this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public final class User {

  private RentHistory rentHistory;

  public User() {
  }

  public User(RentHistory rentHistory) {
    this.rentHistory = rentHistory;
  }

  public Optional&amp;lt;RentHistory&amp;gt; getRentHistory() {
    return Optional.ofNullable(rentHistory);
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Instead of returning entities we are going to return an optional of it! Now changes in the Test class.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  public void displayNumberOfMoviesRentInCurrentMonth(User user) {
    System.out.println(getTotal(user.getRentHistory())
        .map(total -&amp;gt; "Number of movies user rent in this month is: " + total)
        .orElse("User has not rent any movie in the current month"));
  }

  private Optional&amp;lt;Integer&amp;gt; getTotal(Optional&amp;lt;RentHistory&amp;gt; history) {
    if (!history.isPresent()){
      return Optional.empty();
    }
    return Optional.ofNullable(history.get().getTotalInCurrentMonth());
  }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F7wmtz8h2ahuk24kydnrr.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F7wmtz8h2ahuk24kydnrr.png" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Optional was not designed to be passed as argument! This is for sure not the way to go. We are going to refactor! InteliJ already tells us that I can make a change and introduce map method, lest do this!&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  public void displayNumberOfMoviesRentInCurrentMonth(User user) {
    System.out.println(getTotal(user.getRentHistory())
        .map(total -&amp;gt; "Number of movies user has rented in this month is: " + total)
        .orElse("User has not rented any movie in the current month"));
  }

  private Optional&amp;lt;Integer&amp;gt; getTotal(Optional&amp;lt;RentHistory&amp;gt; history) {
    return history.map(RentHistory::getTotalInCurrentMonth);
  }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Looks a bit better, but are still passing the Optional as an argument, that is bad! What we are going to do now, is to change the way around. First we are going to use the user, and then if thr user has his RentHistory we are going to use it in the getTotal method. So now code would look like that:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public final class Test {

  public void displayNumberOfMoviesRentInCurrentMonth(User user) {
    System.out.println(user.getRentHistory()
        .map(this::getTotal)
        .map(total -&amp;gt; "Number of movies user has rented in this month is: " + total)
        .orElse("User has not rented any movie in the current month"));
  }

  private Optional&amp;lt;Integer&amp;gt; getTotal(RentHistory history) {
    return Optional.ofNullable(history.getTotalInCurrentMonth());
  }

  public static void main(String[] args) {
    Test test = new Test();
    test.displayNumberOfMoviesRentInCurrentMonth(new User());
  }

}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The above solution is almost perfect! It works well for incorrect input, but when everything is fine like that…&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  public static void main(String[] args) {
    Test test = new Test();
    test.displayNumberOfMoviesRentInCurrentMonth(new User(new RentHistory(6)));
  }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;…it gives the response: _Number of movies user rent is this month is: Optional[6]&lt;br&gt;
_&lt;br&gt;
It is like that because we are wrapping the Optional with the Optional. What has to be done is the use of the flatMap:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public final class Test {

public void displayNumberOfMoviesRentInCurrentMonth(User user) {
    System.out.println(user.getRentHistory()
        .flatMap(this::getTotal)
        .map(total -&amp;gt; "Number of movies user has rented in this month is: " + total)
        .orElse("User has not rented any movie in the current month"));
  }

  private Optional&amp;lt;Integer&amp;gt; getTotal(RentHistory history) {
    return Optional.ofNullable(history.getTotalInCurrentMonth());
  }

  public static void main(String[] args) {
    Test test = new Test();
    test.displayNumberOfMoviesRentInCurrentMonth(new User(new RentHistory(6)));
  }

}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This would be the final approach to this matter. Remember, always when dealing with nulls, try to use Optional. It may be at the beginning not that intuitive to use, but when time comes, you will get more and more used to this kind of approach.&lt;/p&gt;

&lt;p&gt;This is of course just a simple example, simple test case that shows how powerful Optional is. I am not saying that you must always use the Optional in every cases, but for sure you should give it a try!&lt;/p&gt;

&lt;p&gt;You can imagine the use of that for something much more sophisticated and complex, and not just simple text displaying.&lt;/p&gt;

&lt;p&gt;This hole post is based on one of the talk that was given by Mr. Victor Rentea. I highly recommend watch this man in action!&lt;/p&gt;

&lt;p&gt;&lt;a href="https://github.com/paweluz/developersmill/tree/master/optional-null-check" rel="noopener noreferrer"&gt;Here&lt;/a&gt; is the git repository for this simple example.&lt;/p&gt;

</description>
      <category>null</category>
      <category>cleancode</category>
      <category>optional</category>
      <category>nullpointerexception</category>
    </item>
    <item>
      <title>To mock or to stub, that is the question</title>
      <dc:creator>Pawel Pawlak</dc:creator>
      <pubDate>Sat, 09 Jul 2022 14:39:36 +0000</pubDate>
      <link>https://dev.to/developersmill/to-mock-or-to-stub-that-is-the-question-1e95</link>
      <guid>https://dev.to/developersmill/to-mock-or-to-stub-that-is-the-question-1e95</guid>
      <description>&lt;p&gt;This post is going to tell you some basic stuff about testing terminology, with some simple examples. Hope you will find it interesting, especially when there is some misunderstanding going on online between mocks and stubs, so lets dive into it!&lt;/p&gt;

&lt;p&gt;All tests that we are going to talk about are called *&lt;em&gt;test doubles *&lt;/em&gt;– how come ? It is taken from the terminology used in the move/film industry.&lt;/p&gt;

&lt;p&gt;In the movie when any dangerous or potentially risky action is about to be performed by the main actor/character, director is calling the stunt double to take over.&lt;/p&gt;

&lt;p&gt;Basically it means that instead of using real objects (actors), in the testing scenario we are going to use test doubles (not real production data), just to test the logic of given implementation.&lt;/p&gt;

&lt;p&gt;The most important thing to remember is that test doubles are divided in to two main groups:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;mocks&lt;/li&gt;
&lt;li&gt;stubs&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;and you should always know the difference between those those.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Stub&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;We use stub if we want to return specific data for in a given circumstances. In other words we teach this object to return specific value for given input, e.g. when code reaches this place in the algorithm return value of 100. We do not want to use real data, we want to use a test data, that checks the logic of our algorithm.&lt;/p&gt;

&lt;p&gt;Lest have an example that tests if a rented car has reached its maximum limit of allowed distance to be made. This information can be further used for sending some warning info to the customer for example.&lt;/p&gt;

&lt;p&gt;This is our CarSatatistic class&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class CarStatistic {
    private final int tripDistance;
    private final float averageConsumption;
    private final int maxSpeed;
    public CarStatistic(int tripDistance, float averageConsumption, int maxSpeed) {
        this.tripDistance = tripDistance;
        this.averageConsumption = averageConsumption;
        this.maxSpeed = maxSpeed;
    }
    public int getTripDistance() {
        return tripDistance;
    }
    public float getAverageConsumption() {
        return averageConsumption;
    }
    public int getMaxSpeed() {
        return maxSpeed;
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;then a simple validator&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class CarRentValidator {
    private static final int MAX_DISTANCE_ALLOWED = 500;
    public boolean isMaximumDistanceReached(Car car){
        return car.getTripDistance() &amp;gt; MAX_DISTANCE_ALLOWED;
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;and a finally test with a use of a stub:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@ExtendWith(MockitoExtension.class)
public class CarTest {
    @Mock
    private Car car;
    @Test
    public void ifTripDistanceIsOverMaximumValue_thenValidatorShouldReturnTrue(){
        Mockito.when(car.getTripDistance()).thenReturn(600);
        CarRentValidator carRentValidator = new CarRentValidator();
        assertTrue(carRentValidator.isMaximumDistanceReached(car));
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This test tests the validator that should return true if user/driver has reached the maximum number of kilometers.&lt;/p&gt;

&lt;p&gt;Stubs are divided into three groups:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Stubs (the one I have introduced before)&lt;/li&gt;
&lt;li&gt;Fake&lt;/li&gt;
&lt;li&gt;Dummy&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Fake&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Fake objects are often use when using real implementation is not possible usually because of the time that is needed to generate/use real objects, or because of the architecture itself. Fakes often are much more simpler then the real implementation.&lt;/p&gt;

&lt;p&gt;They can be also used in the situations when we actually do not have the production code ready yet, but we want to test some logic.&lt;/p&gt;

&lt;p&gt;Very common practice is to use fakes as the in memory DB. Usually our repository (dao) implements some interfaces, and when we want to test some behaviour, we use our test class implementation, that we call fake.&lt;/p&gt;

&lt;p&gt;Time is one of the most important architecture driver. Running all test in 10 minutes, or running them in 10 seconds can make a very big difference in a project. This is why fakes are some important and are so widely use.&lt;/p&gt;

&lt;p&gt;Class CarService that has a method to find a closest available car in given range called &lt;em&gt;findClosestCar&lt;/em&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public final class CarService {
    private CarRepository carRepository;
    private UserRepository userRepository;
    private Notifier smsNotificationService;
    public CarService(){}
    public CarService(CarRepository carRepository, UserRepository userRepository, Notifier smsNotificationService){
        this.carRepository = carRepository;
        this.userRepository = userRepository;
        this.smsNotificationService = smsNotificationService;
    }
    public Optional&amp;lt;CarStatistic&amp;gt; findClosestCar(float range){
        return carRepository.findClosestCar(range);
    }
    public boolean sentNotificationWhenLimitReached(CarStatistic carStatistic, User user){
        CarRentValidator carRentValidator = new CarRentValidator();
        if (carRentValidator.isMaximumDistanceReached(carStatistic)){
            return this.sendNotification(user);
        }
        return false;
    }
    public boolean sendNotification(User user){
        // smsNotificationService.notify();
        return true;
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;then there is a CarRepository contract,&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public interface CarRepository {
    Optional&amp;lt;Car&amp;gt; findClosestCar(float range);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;and it’s fake implementation&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class FakeCarRepository implements CarRepository {
    @Override
    public Optional&amp;lt;CarStatistic&amp;gt; findClosestCar(float range) {
        if (range &amp;lt; 100) {
            return Optional.of(new CarStatistic(500, 5.5F, 137));
        }
        return Optional.empty();
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;and a test to see if there is available car in given range.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@ExtendWith(MockitoExtension.class)
public class CarStatisticsFakeDummyTest {
    private final UserRepository userDummyRepository = (id) -&amp;gt; Optional.empty();
    private final Notifier notifierDummy = (user) -&amp;gt; {
    };
    private final CarService carService = new CarService(new FakeCarRepository(), userDummyRepository, notifierDummy);
    @Test
    public void whenCarIsInRange_ItIsFound() {
        assertTrue(carService.finClosestCar(90).isPresent());
    }
    @Test
    public void whenCarIsNotInRange_ItIsNotFound() {
        assertFalse(carService.finClosestCar(190).isPresent());
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Dummy&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;We use dummy just to allow code to compile. It is simply something that must be given, e.g. passed as a parameter to a method, so the code runs/compiles without any errors.&lt;/p&gt;

&lt;p&gt;In the CarStatisticsFakeDummyTest class it is e.g. parameter with name userDummyRepository that is passed to the constructor of the CarService. We do not carry about its implementation at all. It simply is, so code compiles.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Mocks&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Mock are used when we want to verify if given action was executed. We are not interested in the result at all, but just whether the given method/function was called. Verification of call can be done starting from the simple single method call, to some advance algorithm checks that uses (calls) several steps (methods) to finish – we can check whether all those steps were executed.&lt;/p&gt;

&lt;p&gt;In the example below we are going to test whether a driver got an SMS that is sent to him only when he reaches the maximum number of kilometers that he is allowed to drive in a rented car.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class CarStatisticsMockTest {
    @Test
    public void whenLimitIsReached_smsNotificationIsSent() {
        CarService carService = new CarService();
        CarStatistic carStatistic = new CarStatistic(600, 7L, 185);
        User user = new User(123, "3442-2333-22331");
        Assertions.assertTrue(carService.sentNotificationWhenLimitReached(carStatistic, user));
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Mocks are divided into two groups:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Mock – the one I have already explained&lt;/li&gt;
&lt;li&gt;Spy&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Spy&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Spy is very similar to the mock, it is actually its extension, because it not only checks whether method was called, but also verify the number of calls of this method. It can be extremely helpful if you are testing, and trying to figure out how many times some method is calling the DB.&lt;/p&gt;

&lt;p&gt;Here is an example of verifying the number of calls for sending sms method.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@ExtendWith(MockitoExtension.class)
public class CarStatisticsSpyTest {

    @Spy
    private CarService carServiceSpy;
    @Test
    public void whenLimitIsReached_smsNotificationIsSentJustOnce() {
        CarStatistics carStatistics = new CarStatistics(600, 7L, 185);
        User user = new User(123, "3442-2333-22331");
        carServiceSpy.sentNotificationWhenLimitReached(carStatistics, user);
        verify(carServiceSpy, times(1)).sendNotification(user);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Stubs vs Mocks&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;In general we use mocks for testing commands – we check if this method was executed, and e.g with what parameters it was called.&lt;/p&gt;

&lt;p&gt;Stubs are much more often used for testing queries – we want to test out search engine for example, if for given input parameters it returns expected values.&lt;/p&gt;

&lt;p&gt;There can be a situations that we want to use mocks for testing queries as well. They can be used e.g. when we want to check the number of calls to the external server, or to the DB. Sometimes the call using external API is quite expensive, and we want to clarify the number of those that are required for given feature, that we are implementing.&lt;/p&gt;

&lt;p&gt;I hope now you wont make mistake when talking about stubs, and mocks.&lt;/p&gt;

&lt;p&gt;Code for this example can be found in &lt;a href="https://github.com/paweluz/developersmill/tree/master/test-doubles"&gt;here&lt;/a&gt;.&lt;/p&gt;

</description>
      <category>stub</category>
      <category>mock</category>
      <category>testing</category>
      <category>testdoubles</category>
    </item>
    <item>
      <title>Passing callback function to the Angular child component</title>
      <dc:creator>Pawel Pawlak</dc:creator>
      <pubDate>Tue, 17 May 2022 14:24:35 +0000</pubDate>
      <link>https://dev.to/developersmill/passing-callback-function-to-the-angular-child-component-20co</link>
      <guid>https://dev.to/developersmill/passing-callback-function-to-the-angular-child-component-20co</guid>
      <description>&lt;p&gt;This example is going to cover the problem that I have been facing recently regarding passing function to the component.&lt;/p&gt;

&lt;p&gt;Lets imagine we got quite a big application that is using e.g. a combobox or table component that provides the list of countries. The component is used in several places in the app.&lt;/p&gt;

&lt;p&gt;Now there comes additional requirements – on one page there is a limitation, that user wants to see by default only his favourites countries.&lt;/p&gt;

&lt;p&gt;So far everything was encapsulated in the component itself, the call to the backend was done in there as well:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

import {Component, OnInit} from '@angular/core';
import {CountryService} from "../services/country.service";
import {Country} from "../model/country";

@Component({
  selector: 'app-country-table',
  templateUrl: './country-table.component.html',
  styleUrls: ['./country-table.component.css']
})
export class CountryTableComponent implements OnInit {

  countries: Country[] = [];

  constructor(private countryService: CountryService) {
  }

  ngOnInit(): void {
    this.countryService.getAllCountries().subscribe(data =&amp;gt; {
      this.countries = data;
      // any other operations
    }, error =&amp;gt; console.log(error));
  }
}


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Now chages can be implementeed in few ways:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;calls to the backed can be done in the parent component that is using the country component, and simply passed it as an input array – I am not saying that this approach is bad, just IMHO country component should do all the magic, and parent should be only responsible of using it with correct parameters.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;there can be additional parameter e.g. useFavourite, and a condition in the country component that will call proper backend request – I would like to keep this component as hermetic as possible. In the future there can be some changes like e.g. show favourites from Europe that users has already visited. That would require adding again some additional parameters. This would not be very nice.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;country component can be extended, to e.g. favourite-country. One method that is used to make a call to the backend in this case would be overwritten. In general I would like to avoid using inheritance, so this I would simply not use, or leave as the last one to use.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;passing the function that is used for making call to the backend – seems reasonable to me.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;After giving it some thoughts, I have decided to go on with the fourth approach – passing the function to the component. One very important thing that I have to take in count, is that already exiting use of the country component should not be changed at all, that means that I should provide a default callback call (get all countries) for the component, that should be always used when there is not one provided as an input.&lt;/p&gt;

&lt;p&gt;First of all I have to provide the input with the default request call. Then I need to change in code the use of hardcoded method to the one given as the input function. In code it looks like that:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

import {Component, OnInit} from '@angular/core';
import {CountryService} from "../services/country.service";
import {Country} from "../model/country";

export class CountryTableComponent implements OnInit {

  countries: Country[] = [];
  @Input() request: () =&amp;gt; Observable&amp;lt;Country[]&amp;gt; = 
this.countryService.getAllCountries;

  constructor(private countryService: CountryService) {
  }

  ngOnInit(): void {
    this.request().subscribe(data =&amp;gt; {
      this.countries = data;
      // any other operations
    }, error =&amp;gt; console.log(error));
  }
}


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;When I refreshed the application in the place where all countries should be used I got… empty page.&lt;/p&gt;

&lt;p&gt;I thought what is wrong? The default function should be used, so I debugged the problem in the browser. I could see a call is made in the country component, so then I checked the service, and boy was I surprised. I added a breakpoint and this is what I saw in the service:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fuklc7y5awj0uzx4rynpa.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fuklc7y5awj0uzx4rynpa.png" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;So the break is in the country service, but ‘this‘ is pointing to the… CountryTableComponent ?&lt;/p&gt;

&lt;p&gt;Somehow the scope was incorrect, and this was my problem. After some analysis and internet search I found a solution for that. You have to use a bing method that (from API):&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;creates a new function that, when called, has its this keyword set to the provided value….&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;I changed the definition of the input property, and now the hole component looks like that: &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

@Component({
  selector: 'app-country-table',
  templateUrl: './country-table.component.html',
  styleUrls: ['./country-table.component.css']
})
export class CountryTableComponent implements OnInit {

  countries: Country[] = [];
  @Input() request: () =&amp;gt; Observable&amp;lt;Country[]&amp;gt; = 
this.countryService.getAllCountries.bind(this.countryService);

  constructor(private countryService: CountryService) {
  }

  ngOnInit(): void {
    this.request().subscribe(data =&amp;gt; {
      this.countries = data;
      // any other operations
    }, error =&amp;gt; console.log(error));
  }
}


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;When I refreshed the app, all countries were displayed correctly.&lt;/p&gt;

&lt;p&gt;When I wanted to show only favourite countries, the use of the component looked like that:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

&amp;lt;app-country-table
  [request]="getRequest"&amp;gt;
&amp;lt;/app-country-table&amp;gt;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;and its definition like that&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

@Component({
  selector: 'app-favourite-countries',
  templateUrl: './favourite-countries.component.html',
  styleUrls: ['./favourite-countries.component.css']
})
export class FavouriteCountriesComponent implements OnInit {

  constructor(public countryService: CountryService) { }

  ngOnInit(): void {
  }

  getRequest():Observable&amp;lt;Country[]&amp;gt;{
    return this.countryService.getFavouritesCountries();
  }
}


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;You can imagine this component being much more complex. I think in the future this kind of implementation should bring some benefits. Hope someone will find it usefull.&lt;/p&gt;

&lt;p&gt;Simple implementation can be found in &lt;a href="https://github.com/paweluz/developersmill/tree/master/angular-pass-callback-function" rel="noopener noreferrer"&gt;here&lt;/a&gt;&lt;/p&gt;




&lt;p&gt;&lt;a href="https://developersmill.com" rel="noopener noreferrer"&gt;https://developersmill.com&lt;/a&gt;&lt;/p&gt;

</description>
      <category>angular</category>
      <category>callback</category>
      <category>function</category>
    </item>
    <item>
      <title>Angular proxy configuration for API calls</title>
      <dc:creator>Pawel Pawlak</dc:creator>
      <pubDate>Mon, 16 May 2022 07:31:55 +0000</pubDate>
      <link>https://dev.to/developersmill/angular-proxy-configuration-for-api-calls-130b</link>
      <guid>https://dev.to/developersmill/angular-proxy-configuration-for-api-calls-130b</guid>
      <description>&lt;p&gt;Problem that I have recently faced when starting new project with the use of Spring Boot and Angular, is correctly accessing/using my backend API for providing data to the client.&lt;/p&gt;

&lt;p&gt;I have develop some very basic CRUD application that simply is responsible for displaying a list of employees.&lt;/p&gt;

&lt;p&gt;The API url for getting list of employees is: &lt;em&gt;&lt;a href="http://localhost:8080/api/v1/employees" rel="noopener noreferrer"&gt;http://localhost:8080/api/v1/employees&lt;/a&gt;&lt;/em&gt; and the response looked like that:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F89pibogts6aa6o75rwnb.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F89pibogts6aa6o75rwnb.png" alt="Image description" width="566" height="443"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Now I wanted to use my API, to deliver data to the client/angular application. I created an employee.service that simply makes a call to the API&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import {Injectable} from '@angular/core';
import {HttpClient} from "@angular/common/http";
import {Observable} from "rxjs";
import {Employee} from "../model/employee";

@Injectable({
  providedIn: 'root'
})
export class EmployeeService {

  private baseURL = "/api/v1/employees"

  constructor(private httpClient: HttpClient) {
  }

  getEmployeesList(): Observable&amp;lt;Employee[]&amp;gt; {
    return this.httpClient.get&amp;lt;Employee[]&amp;gt;(`${this.baseURL}`)
  }

}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;When I refreshed my application I have noticed in the firebug, that there was a call to the API that did not exist. Call was on port 4200, and not on 8080 – my backend port. Here is this error that I got:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F0wda4p60n0bqqmmrq6m9.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F0wda4p60n0bqqmmrq6m9.png" alt="Image description" width="800" height="282"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;I could of course hardcode the full url in my service using &lt;em&gt;localhost:8080&lt;/em&gt;, so it would be:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;private baseURL = "http://localhost:8080/api/v1/employees"

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;but this is for sure not the way to go, especially when you are going to deploy app on production server sooner or later. Nevertheless, just to see what will happen, I changed the url in the service and checked what has happened. I saw well known CORS error&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fu28mscayg66fptlrhtqr.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fu28mscayg66fptlrhtqr.png" alt="Image description" width="800" height="246"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;A correct solution for this problem is to use a proxy!&lt;/p&gt;

&lt;p&gt;You have to create a new file called proxy.config.json file and add appropriate configuration, so angular would make a call to all API endpoints using exactly this configuration. This file in my case looked like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{
  "/api/*": {
    "target": "http://localhost:8080",
    "secure": false,
    "logLevel": "debug"
  }
} 
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;File should be placed in the root folder of angular project. As you can see few things are defined in here:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;/api/* – all calls to this urls, should use ‘target’ url&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;secure: false – we do not use https&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;logLevel: debug – could be very helpful&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Last thing that need to be done is the change in the package.json file, in the ng start definition, it should now include the use of proxy file. It should be done like that:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  "scripts": {
    "ng": "ng",
    "start": "ng serve --proxy-config proxy.config.json",
    "build": "ng build",
    "watch": "ng build --watch --configuration development",
    "test": "ng test"
  },
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now when I run &lt;em&gt;ng start&lt;/em&gt;, all data is finally passed from the backend application to the client&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ffpu8xrfwznp8w2klre7z.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ffpu8xrfwznp8w2klre7z.png" alt="Image description" width="800" height="246"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;And that is all! I hope it will help someone one day&lt;/p&gt;




&lt;p&gt;&lt;a href="https://developersmill.com/" rel="noopener noreferrer"&gt;https://developersmill.com/&lt;/a&gt;&lt;/p&gt;

</description>
      <category>angular</category>
      <category>proxy</category>
      <category>springboot</category>
    </item>
    <item>
      <title>Hibernate criteria with subquery – using MAX projection and subqueries</title>
      <dc:creator>Pawel Pawlak</dc:creator>
      <pubDate>Tue, 03 May 2022 11:05:36 +0000</pubDate>
      <link>https://dev.to/developersmill/hibernate-criteria-with-subquery-using-max-projection-and-subqueries-45ie</link>
      <guid>https://dev.to/developersmill/hibernate-criteria-with-subquery-using-max-projection-and-subqueries-45ie</guid>
      <description>&lt;p&gt;Here is an example how hibernate criteria can be used with subquery. Lets imagine we have an application that is used for presenting to the user in the UI different types of poster templates for different kind of events. You can imagine that a rock concert will be having a bit different poster then a night at the opera. So there are several poster template types like: concert, outdoor, piknik, theatre, church, running, and many many more. User can find them all in the table which shows him the type, creation date, who created/uploaded given image/poster, and a picture thumbnail.&lt;/p&gt;

&lt;p&gt;Data table for this kind of product could look like that:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fnbxlh43ar0xq24yyva5x.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fnbxlh43ar0xq24yyva5x.png" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Simple criteria query that is used for getting all poster templates should look like that&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

List&amp;lt;PosterTemplate&amp;gt; posters = DetachedCriteria.forClass(PosterTemplate.class)
        .addOrder(Order.asc("creationDate"))
        .getExecutableCriteria(entityManager.unwrap(Session.class))
        .list();


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;For now each of this template can be downloaded and overwritten/uploaded by the user.&lt;/p&gt;

&lt;p&gt;Now there comes new change requirements, those are:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;user can upload a new version of given poster type, old one is kept, and store as old version&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;user is provided with the latest version of given temple type&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;user by selecting right click on given template can see its &lt;br&gt;
available versions and select/download it if needed&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;This change requires changing the query, to deliver to the users all template types but with the latest/bigger version numer.&lt;/p&gt;

&lt;p&gt;First of all we add new column VESRION_NUMBER to the db with default value set to 1. Each time user upload new template of given type version number is increased by one.&lt;/p&gt;

&lt;p&gt;Now I figure out first of all a classic way using hql to get those templates. My query looked like that:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

entityManager.createQuery("select pt1 from PosterTemplate pt1 where pt1.versionNumber ="
           + " (select max(pt2.versionNumber) from PosterTemplate pt2 where pt2.type = t1.type) ",
            PosterTemplate.class).getResultList();


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;This query gives me what I wanted. Although I have already a working solution, I was tempted to rewrite it, using the hibernate criteria. I am for sure not an expert in that area, but I wanted to challenge myself and figure a way to have the same results but with the use of the criteria. After some time of thinking I was able to come up with this working solution:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

public List&amp;lt;PosterTemplate&amp;gt; getAllPosterTemplatesWithLatestVersions() {
    DetachedCriteria subCriteria = DetachedCriteria.forClass(PosterTemplate.class, "inner")
        .add(Restrictions.eqProperty("inner.type", "outer.type"))
        .setProjection(Projections.max("inner.versionNumber"));

    return DetachedCriteria.forClass(PosterTemplate.class, "outer")
       .add(Subqueries.propertyEq("outer.versionNumber", subCriteria))
       .getExecutableCriteria(entityManager.unwrap(Session.class)).list();
  }


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;This implementation should give us the same output as the one provided before using the hql.&lt;/p&gt;

&lt;p&gt;Hope it can be useful for someone.&lt;/p&gt;




&lt;p&gt;&lt;a href="https://developersmill.com/" rel="noopener noreferrer"&gt;https://developersmill.com/&lt;/a&gt;&lt;/p&gt;

</description>
      <category>hibernate</category>
      <category>subselect</category>
      <category>criteria</category>
      <category>projection</category>
    </item>
    <item>
      <title>DRY – Don’t repeat yourself</title>
      <dc:creator>Pawel Pawlak</dc:creator>
      <pubDate>Tue, 26 Apr 2022 15:01:35 +0000</pubDate>
      <link>https://dev.to/developersmill/dry-dont-repeat-yourself-4d0k</link>
      <guid>https://dev.to/developersmill/dry-dont-repeat-yourself-4d0k</guid>
      <description>&lt;p&gt;There are many important rules that good developer should follow, one of them is the DRY principle. Is it one of the many so called ‘clean code’ principles that developer should know, understand, and apply in his code. This rule was introduced by Andy Hunt and Dave Thomas in book &lt;strong&gt;The Pragmatic Programmer&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;Basically what it says, is that as a developer we should always try not to have code that is duplicated – it is as easy as that. To be even more precise, we should also think about a duplication not only from the ‘code/line’ perspective, but also (mainly) from the bussines perspective.&lt;/p&gt;

&lt;p&gt;Our goal is to have one single feature/knowledge in just a one single code representation. The easier to understand that is by using an example. Lets imagine we have a web application, some online bookstore. Application allows clients to give their email information in various places, e.g. in:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;user information/data&lt;/li&gt;
&lt;li&gt;newsletter&lt;/li&gt;
&lt;li&gt;if some product is not available, user can leave his email to be notify later on when product is available&lt;/li&gt;
&lt;li&gt;invite a friend and get 5% discount&lt;/li&gt;
&lt;li&gt;etc…&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Before email is save in the application we must validate it. This can be done by so called ‘copy-paste’ design pattern, or by providing a separate single code representation, it may be a class, or a one single method that handles this validation on the client side.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--k5E_ETkW--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/s8r1juvh0rg6rj8fhjde.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--k5E_ETkW--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/s8r1juvh0rg6rj8fhjde.jpg" alt="Image description" width="880" height="495"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;What we gain by not duplicating this code is several places:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;we reduce the cost of developing – if there will be a new requirement to the validation process, we provide our change just in one single place.&lt;/li&gt;
&lt;li&gt;lets imagine someone has reported a bug in the validation process for adding email in the newsletter. We do fix this, but only in that place – that was the ticket created for, right? Now, two weeks later we are getting this same bug reported – what is going on?! We have already fixed that… but not everywhere. Providing single representation of code, allows us to fix the problem just in one place, and it will be applied for all the features where it is used.&lt;/li&gt;
&lt;li&gt;we test it only one time – we test our logic – the validator method/class.&lt;/li&gt;
&lt;li&gt;there is much less probability of making a mistake. If we not ‘copy-paste’ the code, but decide to write our code manually in 10 different places, we often can make a simple mistake, like e.g. typo in regex expression.&lt;/li&gt;
&lt;li&gt;we refactor the code only once – maybe we have decided to include some nice feature of latest frameworks in the validation process, we can do that is just one single place.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Why sometimes we are having problems with following this principle. One reason is the long methods. We all have seen a 500 lines metod, a 2000 lines classes – we all have been there. When you write a new feature, that is similar to something already written, you tell to yourself: ‘Ooo!, those 15 lines of code, that stars in line 834 – I need it as well’. And what do we do – we copy-paste this code and add it to our new feature, and we make even bigger mess. Not only we do not follow the DRY principle, but for sure we do not follow the ‘boy-scout rule’, that is: ‘Always leave the code better than you found it.’&lt;/p&gt;

&lt;p&gt;It is very tempting to do as shown above – simple copy-paste – isn’t it. What we should have done in the example above? Maybe use the ‘extract method pattern’. Just create a new method, add the code that is duplicated in this new method, and simply call it from our new feature, and from the old place.&lt;/p&gt;

&lt;p&gt;But should we always follow the DRY principle. Should we always refactor, and use e.g. ‘Extract method pattern’. IMHO, no. Remember be very caution when using words ‘always’ and ‘never’, there are very dangerous.&lt;/p&gt;

&lt;p&gt;Lets imagine this situation. We have some report generating system, very important to out client. Its requirements were defined few years ago, according to some government specifications and regulations. There are plenty of already printed out papers that are stored in the archive, also many pdf generated stored in some backup hard drives.&lt;/p&gt;

&lt;p&gt;Now your goal is to provide some new way of reporting, that follows some new government regulations. You noticed, that code you wrote, is very similar to the one that old reporting engine is using. You are thinking about doing some refactor, it can be done just by using ‘extract method pattern’, and e.g. provide new method with two arguments. You want to leave the code better than you fond it, right ? Remember, there are thousands of already printed out documents, reports, if you make a mistake in the old reporting system, there could be some serous consequences.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--MifEOWj9--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/u9a02a724dop37db48hh.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--MifEOWj9--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/u9a02a724dop37db48hh.jpg" alt="Image description" width="880" height="587"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;In that example I would vote for duplication. The risk is simply to much, especially if old system does not have any tests written.&lt;/p&gt;

&lt;p&gt;Some duplications are good, some are even a must have in the application. Lets go back a bit to the system I have mentioned before, that is the online bookstore. We were working with the validation of the user email. Is validating this email only on the client side enough? In this case, you should provide a validation both for the client site (the form), and also for the backed side. We duplicate the logic, but it is necessary, as simple as that.&lt;/p&gt;

&lt;p&gt;These days modern IDE can actually show you the duplication of code, so refactoring is so much easier. InteliiJ has this feature, and it works quite nice I must say.&lt;/p&gt;

&lt;p&gt;There is one thing that I often see in code, that can be very problematic in the future. Again, with the example. Imagine we have a web application that uses a ‘create user form’ feature, in three places. All those places looks very similar, those are almost identical forms, some very tiny differences. So what we do, to not duplicate our code – we provide a parent class for our three form classes, so we add everything that is common in the parent class, and stuff that is specific, to child classes.&lt;/p&gt;

&lt;p&gt;Now what is happening in next year, when application grows. We got some new requirements, and now our three very similar classes, are starting to have a bit different behaviour. So what happens now… we are adding the ‘instanceof’ operators in the parent class to say: do this for this child, and that for that child. Please remember: We use inheritance not to add common part in front of the parenthesis (if speaking in the mathematical terminology) but to support polymorphism, and polymorphism is different behaviour for different instances. I will try to cover the dangerous of inheritance in the future posts, but please do not do that.&lt;/p&gt;

&lt;p&gt;Remember that the DRY principle can be applied not just to the code. Think about all the processes that you are dealing in the development/deploying process of the application.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;instead of manual testing, that is repeated every time new feature is implemented, you should think of providing unit test, maybe selenium test, integration test.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;instead of manually uploading a war to the server you should think about the CI , jenkins for example&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;etc…&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;I hope after reading this article you will think twice, before you copy-paste some ‘if statements’ from already existing code.&lt;/p&gt;




&lt;p&gt;&lt;a href="http://www.developersmill.com"&gt;www.developersmill.com&lt;/a&gt;&lt;/p&gt;

</description>
      <category>cleancode</category>
      <category>java</category>
      <category>dry</category>
      <category>solid</category>
    </item>
  </channel>
</rss>
