Hello, world!

Let's look at the all-familiar Hello World application, written in Java:
Main.java

public class Main {
    public static void main(String[] args) {
        System.out.println("Hello, world!");
    }
}
We know it works properly when it prints out:
Hello, world!
In its lifetime, this piece of code may be extended and rewritten so many times that we may not be even sure it still works as intended. How do we then make sure it still works? Do we say it works if it spits out:
Hello, World!
In case your tired, rheumy eyes missed it, the output slightly differs from the original because 'w' is now in uppercase.
Computers are very good at doing repetitive and boring activities that may otherwise make human eyes glaze over. Let's put them to task in ensuring that our code works.
Main.java

public class Main {
    public static void main(String[] args) {
        System.out.println(getHelloString());
    }
}
Hello.java

public class Hello {
    public static String getHelloWorldString() {
        return "Hello, world!";
    }
}
We've refactored our code to take out the string and put it in a separate object. It looks like unnecessary code bloat but it now allows us to test our code. Let's create a test case for this:
HelloTest.java

@Test
public void testGetHelloWorldString() {
    System.out.println("getHelloWorldString");
    String expResult = "Hello, world!";
    String result = Hello.getHelloWorldString();
    assertEquals(expResult, result);
}

Now, we can tear down, rebuild or mutilate our code and still be sure to know that it works!

Share