An XP Interview

While reading the book “Extreme Programming Explained,” I came across an interview with Brad Jensen a Senior Vice President of Airline Products Development at Sabre Airline Solutions. During the interview, Brad explained how he applied XP within his company and some of the difficulties he faced.

In this blog, I will be sharing my takeaways from this interview; because I thought it is worth sharing with others especially those willing to apply XP.

XPExplained

The Interview

Brad explained that he was able to apply XP in his company that consisted of 300 employees, 240 of which are developers, 25 in management and 35 in testing. His primary purpose was to bring 13 products into one organization with one architecture and one UI.

They started by giving a one-week training for each of the 13 groups then followed by coaching when they started applying XP. But, he advises on doing the training for one team at a time (making sure each time that the team got the concept of XP)

My Takeaways

  • How he made it work
    • XP was a perfect fit for Java projects with a motivated team
    • Testing and refactoring of C++ legacy code were very hard due to the complex design and lack of refactoring tools. Thus, XP had to be applied in a waterfall-ish way for such projects. Which meant:
      • more design and requirement gathering up-front
      • formal testing phase before deploying
    • Using XP decreased the number of defects to zero in some Java projects. For the C++ legacy, the defects dropped to a ratio of one to two per thousand lines of code
    • They noticed a 40% increase in productivity
    • It wasn’t easy to adopt XP! At first, only a third buy-in whereas the rest either are skeptical or just wait and see. Eventually, 80-90% buy-in, 10-20% use XP grudgingly and 3-5% never buy-in
    • If programmers don’t pair or insist on owning code have the courage to fire them
  • On-site Customers
    • A project manager should represent all of his customers
    • Having on-site customers is the most valuable part of XP because it gives you the ability to manage properly the scope and visibility on whether you are going to make it or not.
    • Without careful watching, on-site customers can cause the most problems as scope management can turn into scope creep
  • Advice for Executives
    • Plan by feature
    • Plan release once a quarter
    • Plan fixed-iterations more frequently
    • Have customers sit with the team
    • Put team in one open space

Give It a Try

In my team, we’ve been using this methodology for a while now, and it is working perfectly for us. We maintain clean code with test coverage up to 85%. We also managed to tune it to fit our needs, for example doing remote pair programming (you can check some of Philippe’s posts for more insights on the way we work.)

The importance of this interview is that it provided a real example of applying XP not only theories. Thus, it might encourage leaders to give XP a try!

I highly advise you to read this book. If you are new to XP, this book will give you insights on what this methodology is, why is it important and how to adopt it within your team. If you are already an XP developer, this book is your reference to know whether you are applying it correctly or not.

” You will only value XP when you give it a try!”

 

Using H2 In-Memory to test your DAL

How should we test the Data Access Layer code?

Many developers ask that question. Similar to the other layers of your system, it should be fully tested to prevent unexpected and random behavior in production. There are many ways to achieve that, among of which are mocks or in-memory database.

The problem with mocks is that instead of testing the validity of your SQL queries (syntax and execution), you will only be testing the validity of the system’s flow. On the other hand, using the in-memory database will validate both! That is why I prefer it over mocking. But, you should keep in mind that the SQL syntax might differ from one database engine to another.

In this blog, I will be giving an example of using “H2 In-Memory” in unit tests. The code of this example is available on my GitHub account.

H2 In-Memory in Action

So, let us see H2 in action 🙂

For the sake of this blog, I will assume we want to test three SQL operations on the table “Members” having the following model:

MEMBERS
ID      | NAME        |
INTEGER | VARCHAR(64) |

The SQL operations to be covered in this blog are:

  1. Create Table
  2. Insert (batch of prepared statements)
  3. Select *

Code Explanation

The example will be based on five files (pom.xml, Member.java, SqlRepository.java, H2Repository.java and H2MembersRepositoryTest). In this section, I will give a brief explanation of each file.

Pom.xml (Maven Dependencies):

First, let us modify our pom file (as shown below) to make our project depend on two projects:

  1. com.h2database: Using this dependency, Maven will take care of downloading the h2 jar file we will be referencing in our tests.
  2. Junit: a unit testing framework for Java
<dependencies>
    <dependency>
        <groupId>com.h2database</groupId>
        <artifactId>h2</artifactId>
        <version>1.4.191</version>
    </dependency>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.11</version>
    </dependency>
</dependencies>

Member.java:

This class represents a Member record. It consists of a factory method that returns an instance of the Member class and two getter methods to return the values of the Id and Name fields.

package dal;

import java.util.Objects;

public final class Member {
    private final int id;
    private final String name;

    private Member(int id, String name) {
        this.id = id;
        this.name = name;
    }

    public static Member aMember(int id, String name) {
        return new Member(id, name);
    }

    public int id() {
        return id;
    }

    public String name() {
        return name;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Member member = (Member) o;
        return id == member.id &&
                Objects.equals(name, member.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(id, name);
    }
}

SqlRepository.java

In this class, we establish a connection to our database. What is important in this class is that we pass the connection string as a parameter to the constructor thus making our code unbounded to any specific database engine (MySql, H2, Sybase, Oracle, etc.). This will make writing our tests much easier!

The class consists of:

  1. Constructor: initializes an instance of SQL Connection using the connection string passed as parameter
  2. Three public methods:
    1. createTable: executes an update query to create the”MEMBERS” table.
    2. allMemebers: executes a select query and returns the found records in a list of Members.
    3. insertMembers: takes a list of “Member” as a parameter and inserts the values into the “MEMBERS” table.
package dal;

import dal.Member;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class SqlRepository {

    protected final Connection connection;
    private static final String CREATE_MEMBERS = "CREATE TABLE MEMBERS(ID INTEGER, NAME VARCHAR(64))";
    private static final String SELECT_MEMBERS = "SELECT * FROM MEMBERS";
    private static final String INSERT_MEMBERS = "INSERT INTO MEMBERS(ID, NAME) VALUES(?, ?)";

    public SqlRepository(String connectionString) throws SQLException {
        connection = DriverManager.getConnection(connectionString);
    }

    public boolean createTable() throws SQLException {
        Statement createStatement = connection.createStatement();
        return createStatement.execute(CREATE_MEMBERS);
    }

    public List<Member> allMembers() throws SQLException {
        List<Member> allMembers = new ArrayList<>();
        Statement selectStatement = connection.createStatement();
        ResultSet membersResultSet = selectStatement.executeQuery(SELECT_MEMBERS);
        while (membersResultSet.next()) {
            allMembers.add(Member.aMember(membersResultSet.getInt(1), membersResultSet.getString(2)));
        }
        return allMembers;
    }

    public void insertMembers(List<Member> members) throws SQLException {
        final PreparedStatement insertMembers = connection.prepareStatement(INSERT_MEMBERS);
        members.forEach(member -> insertMember(member, insertMembers));
        insertMembers.executeBatch();
    }

    private void insertMember(Member member, PreparedStatement insertMembers) {
        try {
            insertMembers.setInt(1, member.id());
            insertMembers.setString(2, member.name());
            insertMembers.addBatch();
        } catch (SQLException e) {
            throw new UnsupportedOperationException(e.getMessage());
        }
    }
}

H2Repository.java

I added this class under “Test Sources Root” because it is only used by the tests.

As you notice, it extends the SqlRepository class implemented previously. Thus, we don’t have a lot to implement here. The only method added is a new method “closeConnection” that drops all the existing tables from the database.

You might wonder why would we need that since we are using an In-Memory database. That might be true for this simple example, but it will be a necessity when running multiple tests classes. That is because, in Java, all the tests are run in the same JVM which means that the H2 instance initialized in the first test will be shared with the next test classes. This approach might lead to an unexpected behavior when using the same tables in the different test classes.

package dal;

import java.sql.SQLException;

public final class H2Repository extends SqlRepository {
    public H2Repository(String connectionString) throws SQLException {
        super(connectionString);
    }

    public void closeConnection() throws SQLException {
        connection.createStatement().execute("DROP ALL OBJECTS");
    }
}

H2MembersRepositoryTest.java

This is the simple test class! Our single test (it_correctly_inserts_members_to_a_database) is invoking the three methods we implemented before (createTable, insertMember and allMembers). If any of those methods is badly written our test would fail.

package dal;

import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import static dal.Member.aMember;
import static org.fest.assertions.Assertions.assertThat;

public class H2MembersRepositoryTest {

    private static final String H2_CONNECTION_STRING = "jdbc:h2:mem:test";
    private static final List<Member> MEMBERS = new ArrayList<>(10);
    private static H2Repository h2Repository;

    @BeforeClass
    public static void
    setup_database() throws SQLException {
        h2Repository = new H2Repository(H2_CONNECTION_STRING);
        initializeMembers();
    }

    @Test
    public void
    it_correctly_inserts_members_to_a_database() throws SQLException {
        h2Repository.createTable();
        h2Repository.insertMembers(MEMBERS);

        assertThat(h2Repository.allMembers()).isEqualTo(MEMBERS);
    }

    private static void initializeMembers() {
        for (int index = 0; index < 10; index++) {
            MEMBERS.add(aMember(index, "Name_" + index));
        }
    }

    @AfterClass
    public static void
    tear_down_database() throws SQLException {
        h2Repository.closeConnection();
    }
}

TearDown

If you can test your DAL, you can test anything! (I just came up with this ;))

Keep the tests going!

References:

  1. H2-Database Engine
  2. H2-Maven
  3. JUnit Maven
  4. GitHub

How to move a git repository to subdirectory of another repository

You might come across a situation when working with Git where you want to move a repository to another repository (i.e., make it a subdirectory of the other` repository) while maintaining its full history.

In this blog, I will be pointing out step by step with an example how to achieve that.

Use Case

Let us assume we have two repositories on git, repoA, and repoB, and we want to make repoB a subdirectory of repoA while maintaining its full history.

To achieve that we will move the content of repoB into a subfolder under repoB and then merge repoA and repoB. 

Bellow is the detailed git process:

  1. The first step is to clone repoA and repoB on your machine
    $ git clone repoA
    $ git clone repoB

    Note: For the purpose of this blog I submitted a README.md file in each of the two repositories on Bitbucket. Below are two snapshots are taken for both repositories:

    RepoA:
    REPO-A-Commits

    RepoB:
    REPO-B-Commits

  2. The second step is to copy the content of repoB to a subfolder. Go to the folder repoB and apply the following steps:
    • create a subfolder repoB
      $ mkdir repoB
    • move everything from the parent repoB to the child repoB (except the .git folder)
    • stage the files (the added folder and deleted file(s)) for a later commit
      $ git stage repoB/
      $ git stage README.md
    • commit and push those changes to git
      $ git commit -am '[REPO-B] Move content to a subfolder'
      $ git push origin master
  3. Go to the folder repoA and do the following:
    • add a remote branch with the content of repoB
      $ git remote add repoBTemp (path_to_repoB)
    • fetch repoBTemp the temp repo we created in the previous step
      $ git fetch repoBTemp
    • merge repoBTemp with repoA
      $ git merge repoBTemp/master
    • delete the remote repoBTemp
      $ git remote rm repoBTemp
    • push the changes to the server

      $ git push origin master

  4. Now we can check our git history to verify that our trick worked as intended. In the right image below you can see that the history of repoB is now part of repoA’s history. In the left image, you can notice that repoB is now a subdirectory of repoA.
  5. You it should be sage to delete the repository repoB

I hope you find this blog helpful!

 

 

One week wearing a Moto 360 and Fitbit – Part Two

In the first part of this blog, I made a comparison between the major three apps associated with Moto 360 and Fitbit. In this part, I am comparing the data collected from those devices and mentioning which one I preferred.

Data comparison

I extracted the data collected from the two devices during this week and displayed a line chart for each dashboard (Number of Steps, Active Minutes, Calories Burnt and Distance Covered). Monday through Thursday, my activity was low because it only included going to work. On Friday and Saturday, it went a bit higher as I was walking around the city. And finally, on Sunday, I deliberately went for a 30 minutes run.

The charts below clearly show that both devices operate differently. In the case of ‘Active Minutes’ and ‘Calories Burnt’, Fitbit reported numbers 30 and 8 percent higher than the Moto360. Whereas for ‘Steps’ and ‘Distance’, Moto360 was higher by 7 and 15 percent respectively.

Here are the charts

Number of Steps

FitnessChartSteps

Active Minutes

FitnessChartActiveMinutes

Calories Burnt

FitnessChartCalories

Distance Covered

FitnessChartDistance

 Conclusion

Obviously, one of those devices is reporting wrong values, or let’s say inaccurate ones! To know which, we need to understand in details each’s mechanism and then benchmark both and compare the results. I partially tried to do that in this blog. I did a simple benchmark by wearing both at the same time, although there might be a more accurate way but that was the easiest being an end user. I also read a lot about how Fitbit works (check this article), but couldn’t find anything on Moto360. That is why I decided not to include any summary of this mechanism in the blog.

I Chose the Moto360

In my opinion, Moto360 has all the functionalities Fitbit has except for three: sports compatibility (I won’t take the risk of playing squash with my Moto360!), sleep monitor and floor counter. On the other hand, since Fitbit HR is mainly an activity tracker, it lacks the major features of Moto360. Being a Smart Watch which means full integration with the apps on your phone. And, a better design, no one can argue that the Moto360 has a better look!

After a couple of months of wearing the Fitbit, it would be very easy to predict what it will be logging by the end of the day. So, unless you are a sports professional (you might then consider a more sophisticated activity tracker), the Fitbit would be more of an extra gadget on your wrist when wearing a SmartWatch at the same time.

For me, choosing between a smart watch that does everything and an activity tracking device was easy!

 

One week wearing a Moto 360 and Fitbit – Part One

In my previous post, I mentioned that I will be wearing the Moto360 (2nd gen) together with the Fitbit HR to make a comparison between the two devices. I did that for one full week, Monday to Sunday. And to have accurate results, I made sure to have both of them on at the same time.

I will divide my feedback and comparison into two blogs. In this part, I will be comparing the major three mobile apps associated with those devices (Google FitMotoBody, and Fitbit). Those apps are used to track, monitor and display the daily, weekly and monthly analysis of your activity.

Moto 360

Google Fit

It is Google’s default fitness tracking app, all the fitness data Google collects from you through any of its devices will be visible through this mobile app or the web interface. The app is installed by default on all Android devices, so whether you like it or not it will be there!

Supported Features:

  1. The default window displays Today’s totals (see image above)
  2. Collects data from the watch using MotoBody
  3. Displays six dashboards (Active Time, Distance, Calories, Steps, Weight and Heart Rate)
  4. You can quickly switch between dashboards
  5. Provides an easy way to manually log activities
  6. Tracks multiple activities (Walking, Running, Biking, Squash, Basketball, etc.)
  7. The activities are broken down to short activities (i.e. short walking intervals)
  8. Short activities are associated with some interesting details such as location, average pace, steps, etc. (left image below).
  9. Some dashboards display multiple activities on the same line chart graph, where each activity is a represented by a color (right image below).
  10. Data is also available on the web

Missing Features:  

  1. Still unstable! It took me many tries to be able to generate the dashboards
  2. It doesn’t display the totals on the top of the weekly dashboard
  3. Sleep and Floors dashboards
  4. The UI can be improved.

MotoBody

On the other hand, MotoBody is the app developed by Motorola for its wear devices. It is essential to have it installed to get the best experience of the Moto360. Unfortunately, I found that it lacks some features.

 

Supported Features:

  1. Fully integrated with the watch (watch screenshots above)
  2. It has dashboards for Active Minutes, Steps, Calories and Running
  3. It has a good UI that makes it a user-friendly app
  4. The default dashboard displays the data for Heart Activity, Steps, and Calories in the same window
  5. Easily swipe between daily and weekly dashboard
  6. The detailed weekly dashboards have two types of charts (line and bar)
  7. Compares the data from current week with the previous one (gray line image below)
  8. The weekly dashboard displays the total and daily average on the top

Missing Features:

  1. Dashboards for Distance, HeartRate, Sleep
  2. It only shows the daily average, so you will not be able to view your hourly activity
  3. It limits the exercises to Steps and Running
  4. There is no web interface.

Fitbit

You can find tens of apps integrated with the Fitbit device. But I think the official one developed by Fitbit is good enough that you won’t need to check any other, at least, I didn’t.

 

Supported :

  1. Its default window is the daily dashboard displaying all information the device collects (Heart Rate, Active Minutes, Steps, Sleep, etc.)
  2. The daily detailed dashboards display your hourly progress
  3. The weekly dashboard shows the total and daily average on the top
  4. Tracks multiple exercises:
    1. Allows users to start manually outdoor activities (run, walk or hike)
    2. Associates exercises with a map, calories, time and average heart rate
    3. Manually log previous exercises
    4. The latest update automatically tracks six types of activities (walk, run, outdoor bike, elliptical, sport and aerobic workout)
  5. Provides helpful and motivating features such as rewarding badges when exceeding a certain limit
  6. Allows you to connect and compares status with Facebook friends
  7. A customizable web interface

Missing Features:

  1. Requires many user actions to move between the dashboards
  2. Although it displays the hourly activities, it doesn’t show short activities like the Google Fit.
  3. Google Fit supports more exercises

Next Blog

In my next blog, I will be comparing the data collected during that week and explaining why I preferred the Moto 360 over the Fitbit.

 

Moto 360 (2nd gen)

Last week, I received a package from Amazon containing my new smart watch (Moto 360 2nd gen). Purchasing a smartwatch was on my mind since Google released the 1st generation of the Moto 360 back in September 2014, but I kept on waiting. Two months ago I started comparing reviews of the available Android wears; the competition was mainly between Huawei Watch and Moto 360 2nd gen. I chose the later for one reason only, the diameter size! I thought the 42mm diameter would be a bit small!

Brown vs. Black

Initially, I wanted to buy the black watch (bezel, case and band) that would have looked like this:

moto360black.png

But I didn’t manage to do that due to unavailability on Amazon-FR, and since I don’t live in the U.S, it becomes harder to have it shipped from the Motorolla website. So I ended up buying the silver watch with a brown leather band (check featured image). Well, it didn’t turn out to be a bad thing after all! The combination of silver and brown color looks elegant and beautiful, plus, you can easily buy and change those bands later.

My Review

I bought the watch because I want to get into the field of Android development (phone & wear), so, I will be leaving my detailed reviews for later blogs after digging into its details.

Moto 360 vs. Fitbit HR

Almost a year ago, I bought the Fitbit HR to track my activity. I used to wear it on my right hand with my Tissot watch on the left, well that looked ridiculous!! 🙂 Now, the Moto 360 will replace both devices. But before taking the Fitbit off, I will be comparing the data collected from both devices since they both has some smart features in common. That will be the content of my next blog!

 

My First Audible Experience

The featured image is a screen shot of the last chapter of “Soft Skills: The software developer’s life manual” on Audible. It was an indication that I had just finished my first audible book!! Honestly, I never thought I would be listening to books; it always sounded weird to me.

It all started a couple of weeks ago when Philippe suggested that I listen to this book in parallel to the other books I am reading (The Power of Full Engagement and Refactoring: Improving the Design of Existing Code). Knowing Philippe, it has to be worth a try if it something he is suggesting 🙂 After our discussion, I directly logged-in to my Amazon account and noticed that I had two free Audible books!! It was a matter of minutes to have both the book and the Audible application downloaded on my phone.

My Feedback

It turned out I was wrong. It was an exciting and enjoyable experience and here is why:

  1. It is more accessible than reading books. Unlike reading a hard copy of book, you can play Audible at almost any time and place (while driving, jogging, onboard a plane, etc.)
  2. It is unlikely to be exhausted to listen. I was on a night flight back home, after spending the first thirty minutes of the flight reading a book I reached a point where I wasn’t able to digest the words anymore. So I switched to my phone and started listening to the book, I was surprised that the remaining two hours of the flight passed quickly. It was then that I noticed that even if you are too tired to read you still can listen and learn.
  3. You can finish books faster. The above two points have a significant role in speeding up the process. I managed to finish this book in 15 days; it might not be a great timing, but it is definitely faster than reading the book.
  4. Audible is a great application. I haven’t explored each and every feature of this tool yet, but I think it is a great one for the following reasons:
    • You can quickly add bookmarks with notes if needed
    • Synchronization between the web and phone applications makes it easy to switch between the two
    • It motivates the listener by rewarding badges and suggesting bragging about it on social media
    • It has an excellent playback system especially when you get interrupted by a phone call or notification
  5. Soft Skills was a good selection. Probably the book I picked to be my first audible experience helped to build this positive feedback. The book itself is excellent, and a must read for all developers. The narrator, as well, being the author added a unique taste by improvising and sharing his personal experience from outside the book.

I highly advise anyone to give Audible a try. Personally, now am looking for the next book to listen to! Any suggestions? 🙂