Home > Articles > Programming > Java

  • Print
  • + Share This
Like this article? We recommend

Saving Time with a Quick Peek

One thing is for certain: We’ll never ship a GUI or even release it to the QA group without doing some level of manual testing on it. We want to automate as much of this testing as possible, certainly, but some sort of visual inspection will always be needed. Also, since we’re not going to be writing automated tests for layout, we’ll want to bring up the user interface windows from time to time to ensure that they’re aesthetically pleasing.

When building GUIs in the past, I’ve resorted to the following cycle in order to get the layout right:

  1. Make a small code change.
  2. Compile.
  3. Execute the application.
  4. Navigate to the screen I’m changing.
  5. Visually inspect the screen to see if it looks right.

For complex layouts (GridBagLayout, anyone?), I might repeat this cycle half a dozen, a dozen, or even more times.

If we instead take the care to design our views correctly, they’ll contain no hooks to the rest of your system. Therefore, we can write simple driver code to show the view as a standalone entity. To support our need for occasional visual inspection, we’ll build our driver code using the good old tried-and-true technique of writing a main method in the Swing class itself. The main method will create an instance of the view and display it onscreen.

This main method should be pretty simple. For the HoldEm application itself, it’s one line of code:

public static void main(String[] args) {
  new HoldEm().show();

If you run this code, you should see an empty frame window with the correct title and proper dimensions. When you close the window, the application should terminate.

Speaking of main methods, if you ever have more than one such line of code in your main method, you’re probably doing something wrong. It’s possible to write a unit test against main, since you can call it like any other method. But my goal is instead to always get the main method to the point where it cannot break—with one line that should never need to change.

I’m sure some of you have excuses for making main longer. You may need code to parse command-line arguments coming in through args. Tragically, I often find this cumbersome code bloating the main method. But there’s no reason you can’t extract such code to its own set of static methods that are unit-tested. (It’s also repetitive code that probably belongs in a completely separate utility class.) Avoid having black holes like main, or like Swing classes, in which programmers stuff untested code just because it’s convenient.

  • + Share This
  • 🔖 Save To Your Account