Factory Pattern: Replacing the Conditional Statement with Lambda Expressions

The “Factory Pattern” falls under the creational design patterns and is one of the widely used in Java applications. Similar to the other patterns, this pattern helps us write organized and clean code.

But, for me, the conditional statement in the “Factory Pattern” presents a possible breach of the clean code principles especially as the number of conditions increases.

In this post, I will be sharing a technique of replacing the conditional statement with a map of lambda calls in Java.

Definition

It is not the purpose of this post to explain what is the “Factory Pattern” or how it works in details. Thus, I am referring to famous book “Design Patterns: Elements of Reusable Object-Oriented Software” to quote the pattern’s intent:

Intent:
Define and interface for creating an object, but let the subclasses decide which class to instantiate. Factory method lets class defer instantiation to subclasses.

Use Case

For this post, I am assuming that we have an interface “Car,” 4 sub-classes (DieselCar, ElectricalCar, HybridCar, and PetrolCar) and one Factory class “CarFactory.” The diagram for those classes would be as follows:

Traditional Implementation

The traditional implementation of this pattern requires us to have either an if-else or a switch statement in the method CarFactory.getCar().

So, we end up with one of the below implementations:

The IF-ELSE Block

public class CarFactoryIfStatement {

private CarFactoryIfStatement() {
}

static Car getCar(String type, String brand) {
if (type.equals("Diesel")) {
return new DieselCar(brand);
} else if (type.equals("Electrical")) {
return new ElectricalCar(brand);
} else if (type.equals("Hybrid")) {
return new HybridCar(brand);
} else if (type.equals("Petrol")) {
return new PetrolCar(brand);
}
throw new UnsupportedOperationException();
}
}

The Switch Block

public class CarFactorySwitchStatement {

private CarFactorySwitchStatement() {
}

static Car getCar(String type, String brand) {
switch (type) {
case "Diesel":
return new DieselCar(brand);
case "Electrical":
return new ElectricalCar(brand);
case "Hybrid":
return new HybridCar(brand);
case "Petrol":
return new PetrolCar(brand);
default:
throw new UnsupportedOperationException();
}
}
}

The above code snippets might not look very bad, but, as we add more care types the code will become messy, and sonar will complain!

So, what can we do about this code?

Lambda to the Rescue

As a replacement, I will be using a HashMap where the Key is of type String, and the Value is an interface “CarCreator.”

First, we write the interface CarCreator that has only a single method ‘initialize‘ that takes a String and return the Car instance (as shown below):

private interface CarCreator {
Car initialize(String brand);
}

Second, we initialize our map ‘CAR_FACTORY_MAP.’ Our value in this map is a lambda expression that initializes the correct Car instance corresponding to the key.

private static final Map<String, CarCreator> CAR_FACTORY_MAP = ImmutableMap.of(
"Diesel", brand -> new DieselCar(brand),
"Electrical", brand -> new ElectricalCar(brand),
"Hybrid", brand -> new HybridCar(brand),
"Petrol", brand -> new PetrolCar(brand)
);

Note: I am using the Guava library from Google to ease the initialization of the map.

Finally, we implement the method ‘CarFactory.getCar.‘ Instead of the huge bulk of the code we wrote previously with If-Else and Switch blocks; we will call the initialize method of the ‘CarCreator‘ interface.

static Car getCar(String type, String brand) {
if (CAR_FACTORY_MAP.containsKey(type)) {
return CAR_FACTORY_MAP.get(type).initialize(brand);
}
throw new UnsupportedOperationException();
}

Following those three steps, the code of the ‘CarFactory‘ class would look something like this:

public class CarFactory {
private CarFactory() {
}
private static final Map<String, CarCreator> CAR_FACTORY_MAP = ImmutableMap.of(
"Diesel", brand -> new DieselCar(brand),
"Electrical", brand -> new ElectricalCar(brand),
"Hybrid", brand -> new HybridCar(brand),
"Petrol", brand -> new PetrolCar(brand)
);

static Car getCar(String type, String brand) {
if (CAR_FACTORY_MAP.containsKey(type)) {
return CAR_FACTORY_MAP.get(type).initialize(brand);
}
throw new UnsupportedOperationException();
}

private interface CarCreator {
Car initialize(String brand);
}
}

Note: I have uploaded the full code to a repository on my Github account.

References

  1. Design Patterns: Elements of Reusable Object-Oriented Software
  2. Tutorials Point – Factory Pattern
  3. [Featured Image] Pixabay – Wheel Valve Heating Line Turn
  4. Source Code on Github

Mars Rover – Refactoring Kata

On several occasions, I have used the Mars Rover challenge to train developers on the TDD principles. This time, I am using it as a refactoring Kata!

On my GitHub repository, I submitted the initial code that covers all the cases except the edge ones. But, the code I’ve written is in bad shape.

How to solve this Kata?

To solve this kata, you have two tasks to do. Firstly, you need to refactor the code and ensure it follows the clean code principles. Secondly, you need to write code that covers the edge cases for the Mars Rover.

Note: Before proceeding, make sure to fork the repository to your own Github account.

Task 1: Code Refactoring

  1. Start by writing unit tests to cover all the cases of this challenge. This is an important step to ensure that the refactoring doesn’t break your code. In total, you should write around 12 unit tests to have good coverage of the code.
  2. Now it’s time to refactor the existing code. While doing that:
    1. Think of the design patterns that might help improve the code
    2. Apply some of the S.O.L.I.D principles to have clean classes and methods

Task 2: Missing Features

There is a missing feature with my code. Currently, the rover can move out of the plateau if given the wrong commands. It’s your task to write the code that handles this case. The rover’s position should not be modified if the next spot is outside the plateau.

Finally…

This kata is relatively easy, but, I think it is a good first step into the world of code refactoring and writing tests for existing code.

Looking forward to your feedback…

References & Links

Tutorial: How to configure maven surefire plugin work with JUnit 5

Recently, I had a task to migrate the unit tests in our project from ‘JUnit 4’ to ‘JUnit 5’. As many developers, I researched a bit to learn about the major differences between the two versions and drafted a plan for smooth migration.

From the first look, I thought my only job was refactoring the tests and probably some helper classes. But, I was wrong! I ran into a configuration issue with the maven-surefire-plugin configuration.

In this post, I will be sharing the encountered issue and its fix. Note that I will not cover the detailed steps of how to migrate from ‘JUnit 4’ to ‘JUnit 5’.

Tests run: 0!

We, as many other developers, use the maven-surefire-plugin to run our tests during the test phase of maven’s build lifecycle. We rely heavily on this plugin because it fails the build when one of the tests is broken!

With JUnit4, everything was working perfectly! But after the migration, the plugin was always reporting that not tests are run:

'Tests run: 0, Failures: 0, Errors: 0, Skipped: 0 ...'!

Calculator Class

For the purpose of this blog, let us assume we want to build a Calculator. For now, we only have the ‘add‘ method implemented as shown below.

Calculator.java

public final class Calculator {
    public static int add(int firstNumber, int secondNumber) {
        return firstNumber + secondNumber;
    }
}

JUnit 4 Code

junit4

I will start with the ‘JUnit 4’ version of the code.

pom.xml

We need to depend on the junit artifacts and add the plugin for the surefire. Here is the required pom file:

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>2.19.1</version>
        </plugin>
    </plugins>
</build>

<dependencies>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
        <scope>test</scope>
    </dependency>
</dependencies>

CalculatorTest.java

In the test class, we have one test that asserts our method is doing the correct addition.

import org.junit.Assert;
import org.junit.Test;

public class CalculatorTest {
    @Test
    public void
    our_calculator_should_add_2_numbers() {
        Assert.assertEquals(5, Calculator.add(2, 3));
    }
}

Build Output

Now, if we try to run ‘mvn clean install‘ on the above pom file we get the below output:

-------------------------------------------------------
T E S T S
-------------------------------------------------------
Running CalculatorTest
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.037 sec - in CalculatorTest

Results :

Tests run: 1, Failures: 0, Errors: 0, Skipped: 0

****
[INFO] --------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] --------------------------------------------------

Everything works perfectly!

JUnit 5 Code

junit5

It’s time to migrate our code to ‘JUnit 5’!

pom.xml

The first step is changing our dependencies in the pom file.

Some significant changes were applied to the ‘Junit 5’ dependency metadata. The framework functionalities have been split into several artifacts:

  • junit-jupiter-api
  • junit-jupiter-engine
  • junit-platform-suite-api
  • junit-jupiter-params
  • junit-platform-surefire-provider

For this simple example, it is enough to depend on ‘junit-jupiter-engine‘ & ‘junit-platform-surefire-provider‘.

So, our pom becomes:

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>2.19.1</version>
        </plugin>
    </plugins>
</build>

<dependencies>
    <dependency>
        <groupId>org.junit.jupiter</groupId>
        <artifactId>junit-jupiter-engine</artifactId>
        <version>5.0.0</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.junit.platform</groupId>
        <artifactId>junit-platform-surefire-provider</artifactId>
        <version>1.0.0</version>
     </dependency>
</dependencies>

P.S. Check ‘JUnit 5 User Guide‘ if you are interested in more details on the ‘JUnit 5’ artifacts

CalculatorTest.java

A good portion of the code in tests has to be changed to migrate to ‘JUnit 5’. Again, I am not going to cover those changes in this blog.

For the simple test we have written before, we need to change two things:

  1. Change the import statements
  2. Change the assertion call
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

public class CalculatorTest {
    @Test
    public void
    our_calculator_should_add_2_numbers() {
        Assertions.assertEquals(5, Calculator.add(2, 3));
    }
}

Build Output

Although the ‘mvn clean install‘ command is still returning a ‘BUILD SUCCESS‘ message, it is actually not running any tests which make the whole build process suspicious.

This is our issue!

-------------------------------------------------------
T E S T S
-------------------------------------------------------
Running CalculatorTest
Tests run: 0, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.001 sec - in CalculatorTest

Results :

Tests run: 0, Failures: 0, Errors: 0, Skipped: 0

****
[INFO] ------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------

The Fix

The fix of this problem is simple, need to modify the build section in our pom to add the 2 dependencies to the ‘maven-surefire-plugin‘  plugin section as shown below.

By doing so, we forced the maven-surefire-plugin to use the latest JUnit artifacts and thus run the JUnit 5 tests.

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>2.19.1</version>
            <dependencies>
                <dependency>
                    <groupId>org.junit.platform</groupId>
                    <artifactId>junit-platform-surefire-provider</artifactId>
                    <version>1.0.0</version>
                </dependency>
                <dependency>
                    <groupId>org.junit.jupiter</groupId>
                    <artifactId>junit-jupiter-engine</artifactId>
                    <version>5.0.0</version>
                </dependency>
            </dependencies>
        </plugin>
    </plugins>
</build>

Running ‘mvn clean install‘ will return the correct output now:

-------------------------------------------------------
T E S T S
-------------------------------------------------------
Running CalculatorTest
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.044 sec - in CalculatorTest

Results :

Tests run: 1, Failures: 0, Errors: 0, Skipped: 0

****
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------

 

I hope this blog post would save you some time when migrating to ‘JUnit 5’!

Good luck 🙂