A programming kata is an exercise which helps a programmer hone his skills through practice and repetition.

This article is part of the series Java Tutorial Through Katas.



The article assumes that the reader already has experience with Java, that he is familiar with the basics of unit tests and that he knows how to run them from his favorite IDE (mine is IntelliJ IDEA).

Tests that prove that the solution is correct are displayed below. Recommended way to solve this kata is to use test-driven development approach (write the implementation for the first test, confirm that it passes and move to the next). Once all of the tests pass, the kata can be considered solved. For more information about best practices, please read the Test Driven Development (TDD): Best Practices Using Java Examples.

One possible solution is provided below the tests. Try to solve the kata by yourself first.

Mars Rover

Develop an api that moves a rover around on a grid.

Rules:

You are given the initial starting point (x,y) of a rover and the direction (N,S,E,W) it is facing.

The rover receives a character array of commands.

Implement commands that move the rover forward/backward (f,b).

Implement commands that turn the rover left/right (l,r).

Implement wrapping from one edge of the grid to another. (planets are spheres after all)

Implement obstacle detection before each move to a new square. If a given sequence of commands encounters an obstacle, the rover moves up to the last possible point and reports the obstacle.

Tests

Following is a set of unit tests that can be used to solve this kata in the TDD fashion.

One possible solution is following.

Full source is located in the GitHub repo mars-rover-kata-java. Above code presents only the code of the main class. There are several other classes/objects with their corresponding specification. Besides tests and implementation, repository includes build.gradle that can be used, among other things, to download AssertJ dependencies and run tests. README.md contains short instructions how to set up the project.

What was your solution? Post it as a comment so that we can compare different ways to solve this kata.

Test-Driven Java Development

Test-Driven Java Development book wrote by Alex Garcia and me has been published by Packt Publishing. It was a long, demanding, but very rewarding journey that resulted in a very comprehensive hands-on material for all Java developers interested in learning or improving their TDD skills.

If you liked this article I am sure that you'll find this book very useful. It contains extensive tutorials, guidelines and exercises for all Java developers eager to learn how to successfully apply TDD practices.

You can download a sample or purchase your own copy directly from Packt or Amazon.