10 Pair Programming Best Practices Questions & Answers

A couple of weeks ago, I wrote a guest post on Philippe’s blog where I answered 10 commonly asked questions on the Pair Programming Best Practices. Below is a snippet of the blog, you can read the full article here.

Pair programming is not just sitting together in front of an IDE. Here are battle tested answers to common questions that will make pairing work for you.

Philippe and I are well known to be advocates for Extreme Programming and its practices (well Philippe more than me, but I will share some of the credits 😀). We were asked lately to participate in a Q&A session to share with our experience and recommendations on applying pair programming within a dev team.

Question I: When to do Pair Programming?

All teams do pair programming in one way or another, even if they don’t like to admit it!

Almost all developers have the tendency to ask a colleague for help when stuck on a complex piece of code or a bug, this is a form of pair programming! If we acknowledge that the four eyes principle can help solve complex problems faster, then why don’t we apply it all the time?

Going back to the question, … (continue reading)

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

A good commit message can make a difference!

Some developers have a habit of committing their code without a clear commit message.

I was one of them! Now, I consider that to be a bad habit.

With time I realized that it is hard to remember the intention of an old commit by just looking at the code. It becomes even impossible when reviewing a colleagues’ code.

In this post, I will be sharing a template message I adopted with one of my previous teams.

For simplicity, I will be referring to one of my commits to a fork of the GildedRose-Refactoring-Kata on my GitHub account.

Message Template

Below is the template. As you can see, it is split into four colors. In the next part of the blog, I will break down the message to explain each of its sections separately.

[Issue Tracker #] One-line summary of the commit description 

Why is this change necessary? 
  - Detailed description 1
  - Detailed description 2
  ... 

Section I – ‘[Issue Tracker #]’:

Between the two brackets, I write the issue number corresponding to this commit. The format here varies depending on which issue tracking system I am using (ex: [ProjectName-123] for Jira and [#123] for Github.)

Message so far

[#5] One-line summary of the commit description   

Why is this change necessary? 
   - Detailed description 1 
   - Detailed description 2 
   ... 

Section II – ‘One-line summary of the commit description’:

In the second section, I try to summarize the full commit in just one sentence. Failing to do so means that my commit is doing more than one task and needs to be broken down.

Message so far

[#5] Move the constants out of the GildedRose class

Why is this change necessary? 
   - Detailed description 1 
   - Detailed description 2 
   ... 

Section III – ‘Why is this change necessary’: 

In this line, I try to answer the question ‘Why is this change necessary?’ In most cases, this line is a copy of the ‘Issue Title’.

Message so far

[#5] Move the constants out of the GildedRose class 

In order to, refactor and clean the code of GildedRose
   - Detailed description 1 
   - Detailed description 2 
   ... 

Section IV – ‘Detailed Description’:

Finally, I replace the items of the list in this section with a detailed description of the important technical changes I did in the code. Here I try to think of what I should remember if I was to read this message a couple of months ahead.

The final commit message looks like

[#5] Move the constants out of the GildedRose class 

In order to, refactor and clean the code of GildedRose
   - Make MAX_QUALITY, MIN_QUALITY & MIN_SELL_IN_DATE as local variables ItemVisitor
   - Move AGED_BRIE string to the AgedBrie class
   - Move SULFURAS string to the Sulfuras class
   - Move CONCERT string to the Concert class
   - Adapt the tests accordingly

By just reading this last message, anyone should deduce that firstly, in this commit I only moved some constants from the GildedRose class. And secondly, the commit was part of a larger code refactoring of the GildedRose class.

How is this helpful?

So, why do I consider this to be helpful?

Here are my reasons:

  1. Forces me to code in baby steps and thus have small commits.
  2. By having small commits, it would be easier, later on, to track down bugs.
  3. Makes code review easier and faster
  4. Most SCMs and tracking tools are now integrated, that makes linking commits to an issue seamless. This link has 2 benefits:
    1. By just adding the ‘Issue Number‘ in the message, I can refer to the issue’s details to view all the corresponding commits.
    2. Limits my development to only the features and bugs in the project’s backlog. I won’t be submitting any useless code.
  5. Serves as a documentation for my code. More than once, I referred to those messages when writing a detailed technical report of our product.

Finally…

At first, it was a bit annoying to write this message for each commit. But as we realized its benefits, it became a habit for us!

You don’t have to adopt this exact message, you can come up with any format you think is good for you as long as it is clear and concise.

Enjoy coding 🙂

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 🙂

How to become a better developer!

The fast and constant change in technology made it inevitable for developers to always improve their skills through continuous learning. It is a fact now that developers with outdated skills will be left behind!
Learning isn’t the same for everyone. Some people may learn well by themselves; some may need instruction and example. In the programming world, many resources can meet those particular needs.
And using skills on projects that aren’t all imaginary is key too. Real world projects equal real world experience that translates into adapting more efficient, effective programming language.
What else helps to improve programmers’ skills and help them continue to move into the next wave-whatever that may be? I found this graphic that explains tactics, solutions, and ideas to pursue.
Personally, I have been following some of those for the past couple of years to improve my technical and soft skills!

Click to Enlarge Image

’8

My takeaways from a TDD debate between Cope & Uncle Bob

As a developer, there is a high chance that you had a debate on the value of TDD in building software, especially if you apply it!

I had a lot of those debates!

A couple of months ago, I came across such a debate between Jim Coplien and Robert Martin (Uncle Bob). I found this discussion kind of interesting especially that it involves two leaders in software engineering.

You can watch the debate here:

Takeaways

Here are my takeaways from the discussion:

Three Rules of TDD

Uncle Bob defines the following three rules for applying TDD:

  1. Don’t write a line of production code without having a corresponding failing test
  2. Don’t write too many failing tests without writing production code
  3. Don’t write more production code than is sufficient to pass the currently failing test

Architecture is Important

Jim points out that he has no problem with those rules, his concerns are more architecture related. Jim and Uncle Bob would argue for more than ten minutes to finally reach an agreement on the importance of architecture. The below five points summarizes what they agreed on:

  1. Architecture is very important
  2. It is entirely wrong to assume that the code will assemble itself magically just by writing a lot of tests and doing quick iterations
  3. Design evolves with time and should be assembled one bit at a time
  4. An Object should have properties to give it meaning. At the beginning, those properties should be minimal.
  5. Architecture shouldn’t be created based on speculation

TDD and Professionalism

Probably the only disagreement you can sense from this debate is what defines a professional software engineer. For Uncle Bob, it is irresponsible for a software engineer to deliver a single line of code without writing a unit test for it. Jim, on the other hand, considers ‘Design by Contract’ to be more powerful than TDD.

My Point of View!

Personally, I have been applying TDD since I joined my team three years ago. After experiencing the benefits of this practice, we got to a point where we don’t write or refactor any line of code without having a corresponding unit test!

In addition to that, I had the chance to coach other developers by running coding dojo sessions at work.

All that makes me say that I agree more with Uncle Bob on the topic of professionalism!

References
  1. Coplien and Martin Debate TDD, CDD and Professionalism