101 - The Blocks Problem
This seems quite simple: we will model a robot arm which manipulates blocks on a flat table. There are only 4 manipulation commands and quit command.
![]() |
| Awesome |
So where should we start? Well by writing a test, obviously.
![]() |
| Captain Obvious is obvious. |
First let's verify the initialization of a flat table. Hmmm? How to represent our world? Arrays or lists?
![]() |
| Aliens? |
Ok, create a new empty class, test still fails, yada yada yada. And we're green!
What's next? Well the simplest manipulation command is pile Over - just stack a block on top of other :) You know the drill, create a simple test, stack a block on top of another and voilá. But what if the block has already another on top? Create a new test... it fails. Of course, we only implemented the easiest solution. So we must move the all stack. Green. Hurray!
So manipulation number two: pile Onto. We must also move all stack but before we must reset blocks on top of the destination. I don't know why but I started to struggle and stopped for that day.
![]() |
| Slooooooow |
The next commands were fairly easy: move Over - reset blocks above and move to destination, move Onto - reset all blocks above source and destination and finally move block.
All manipulation commands implemented and tested so it's time to receive commands from System.in. As we only have 5 commands plus initialization a simple while(true) cycle will suffice. Well I forgot to create unit tests for this (shame on me). How can we create a test to simulate input from the console?
String input = "";
InputStream inputStream = new ByteArrayInputStream(input.getBytes(StandardCharsets.UTF_8));
First submission failed with compile error: class must be called Main (forgot about it), second submission.... another fail?!
![]() |
| So fluffy |
Damn, what's the issue now? Runtime error. Let's do a complex test.... Run the test. Kaboom! Here it is: concurrent modification exception.When resetting the blocks on top we are iterating and trying to modify the same list. So let's copy the list to avoid this, and... green :)
One more try, submit... Accepted!
Although the solution was accepted, the code is not that clean. Let's see what we can do about it. Let's apply the boy scout rule (yes Master Uncle Bob) and start refactoring! Extract some methods, run tests, green. Remove some duplication, run tests, green. Wow, having tests make it really easy to do this. I know it's expected but seeing it in action was mind blowing!!!
![]() |
| Wooooahh |
Lessons learned:
- As usual even what seems to be a simple problem takes its time.
- TDD gives a load of confidence, specially when refactoring.
- There is always room for improvement.
![]() |
| Learn you must, young grasshopper! |
Code available at: https://github.com/DiogoTavaresDeAlmeidaRibeiro/UVa101








No comments:
Post a Comment