UVa 101

After a great first experience, we had to go for another taste :)

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?
Well we're using Java so might as well use the power of generics with a List of List of Integers.

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
A new day with a rested mind, let's do this: re-read pile Onto description, think a little bit, code it and we have green.

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


UVa 100

The quest for being a better developer and writing clean code continues with grapes. Grapes?

In portuguese "uva" means grape :D

Sure you do, Borat... sure you do...

Back to session, UVa Online Judge is a site developed by Valladolid University that has hundreds of problems used during programming contests. I've never participated in one during college, as I was too busy with classes projects, so let's see what is all about :)

I've started with 100 - 3 n + 1 problem

The problem is pretty straightforward: we must check if the described algorithm 3 n + 1 will terminate. And then calculate the maximum cycle length between two numbers i and j. 


The solution was not that hard. My main challenge was solving it using TDD. 

I've started to write a test to calculate 22 cycle length.
As it was required to know if a number is odd I've also setup some tests to that auxiliary function. The solution must be submitted in a single line, that reads from standard input writes to standard output. I then proceeded to calculate the maximum cycle length between numbers.

My first submission failed.


NOOOOOOOOO!
After a quick inspection I was not validating if i and j were ordered. A quick new test failing test, change the code to make it green, some small refactorings and voilá. Success!

Yeah you go kid!


Lessons learned:
  • TDD gives a lot of confidence when coding (as expected).
  • TDD demands a lot of discipline (sometimes I only wanted to see if something worked and had to force myself to create a new test).
  • I only found later that we can submit input to check for correct solutions in http://www.udebug.com/UVa/100

Code available at: https://github.com/DiogoTavaresDeAlmeidaRibeiro/UVa100

DIP - Dependency Inversion Principle

And so we reach our final letter and principle. D!








So dip? Where?

Yes, please :)

DIP - Dependency-Inversion Principle

A. High-level modules should not depend on low-level modules. Both should depend on abstractions.


B. Abstractions should not depend upon details. Details should depend upon abstractions.

What?

Confused Jackie Chan is confused

Let's see a diagram:

It looks kind of a waterfall... whew

The high-level layer uses a lower-level layer, which means that Policy layer is sensitive to changes all the way down to Utility layer. P depends on M which depends on U, so P depends on U. Oh no, the dependency is transitive!

 
DIP to the rescue:

Get it now?

Each upper-level layer declares an abstract interface for the services it needs. So, the upper layers do not depend on the lower layers. Instead, lower layers depend on abstract service interfaces declared above. The dependencies are inverted :) Also notice that the interfaces are tied to the servers, not with the clients that implement them.



Yes, Master!

A somewhat naive, yet still very powerful, interpretation of DIP is the simple heuristic "Depend on abstractions":

- No variable should hold a reference to a concrete class
- No class should derive from a concrete class
- No method should override an implemented method of any of its base classes.

In Java this would imply that any line of code that uses the new keyword would violate DIP (even when using Factory Pattern). However depending on a String is very safe because in Java String class is marked final and it won't change. A better way to picture this is to only depend on nonvolatile classes. If a concrete class is not going to change very much, and no other similar derivaties are going to be created, it does very little harm to depend on it.

This inversion of dependency is the hallmark of good OO design. Traditional procedural programming creates a dependency structure in which we depend on the detail. Using DIP we break this structure which leads to more reusable and resilient code :)


And so we reach the end of our first adventure! We're done with all SOLID principles. Let's start to use them eheheh

Which one?

ISP - Interface Segregation Principle

Our principles education continues!

Booo to fat! 




 Booo to pollution! 



Wait what is he talking about?

...and shit

Yeah, interfaces. Some like to have interfaces with an humungous number of methods.


The witches?
However those interfaces should be broken into groups of related methods (to increase cohesion).

Another issue is when we add a method to an interface solely for the benefit of one of its subclasses. This method must be implemented or allowed to default in all derived classes. This may also put in jeopardy LSP, leading to maintenance and reusability problems.

Basically, separate clients means separate interfaces. As simple as that :)


ISP - Interface-segregation principle

Clients should not be forced to depend on methods they do not use.

A vehicle interface could contain all kinds of methods: engine related, gear related, steering, radio, etc.
Fat bastard!
By separate them in different interfaces we'll have a simpler system.
Ah, getting better :)

Also, when clients are forced to depend on methods they don't use, those clients are subject to changes on those methods. This results in an inadvertent coupling between all the clients!
So we should break "fat" classes into many client-specific interfaces: the fat class can then inherit all it needs. Other clients may inherit just from the ones they will effectively use.