The first program you’re s’posed to write in any new language is Hello World. If you’re doing Test Driven Development (TDD), what does Hello World look like?
The actual printing of the hello world text is the UI, and it’s hard to write unit tests for UIs. So we create a thin veneer of a UI, and put all logic into an engine layer. The engine layer is all unit-testable, and we design that Test First. then when we have the engine done, we slap a quick UI on it and our program’s done.
The “engine” behind Hello World simply produces the string “Hello World”. Then the UI will display the string to the user. So we make a Greeter
class, and it has a single method, greet()
, which returns the string “Hello World!”.
Greeter greeter = new Greeter(); assertEquals("Hello World!", greeter.greet());
We make that test pass by returning the hard-coded string.
public class Greeter { public String greet() { return "Hello World!"; } }
The bar goes green and our engine is done. Now, if we did this right, the “UI” should be a very thin veneer:
public static void main(String[] args) { Greeter greeter = new Greeter(); System.out.println(greeter.greet()); }
And there we have it, TDD Hello World.
Tags: hello world, kata
May 10, 2010 at 2:41 pm |
[…] This post was mentioned on Twitter by Ron Romero. Ron Romero said: I wrote a blog entry on doing Hello World with TDD. http://bit.ly/cnKSml […]
July 7, 2010 at 6:17 am |
I’ve recorded my solution to Hello World. http://www.youtube.com/watch?v=oXYw-ppevA4 I go through the solution in Eclipse, and talk about it as I go.