Skip to content

Tip #9: Mockito

Mockito is arguably the most popular of the second generation Java mocking frameworks. Its fluent interface and the way it does away with an explicit expectation phase by verifying directly on the expected interactions with the collaborators of the subject under test gives it an edge over earlier frameworks like JMock and Easymock .

Here’s a test from the GOOS book, written using JMock:

Continue reading ›

Tip #8: Precondition methods

When implementing design by contract and defensive programming a recurrent messy pattern is the validation of arguments passed into methods and constructors as well as object state. This is an example taken from the implementation of java.io.File (in jdk 6):

Continue reading ›

Refactoring #3 Doug Lea’s Concurrency Example

Concurrent code is intrinsically difficult to understand for well known reasons. Unfortunately this is compounded by the obscure coding style in which is often seen written. An example of this can be seen in Java Concurrency in Practice. In chapter 6, for instance he explains how to exploit parallelism in a class that renders both images and text in a html page. In the first version, the downloading of images is done asynchronously using the executor framework. Here’s the original version (imports and delegate methods’ implementations left out throughout for readability):

Continue reading ›

Refactoring #2: Michid’s Scala vs Java Example

A blog entry has been making the rounds on the Internet for a while trying to debunk the myth that Scala is more complex than Java, using an example of partitioning a list and printing the result. The example leans heavily on the contrast between Java’s verbosity and Scala’s terseness.

In this refactoring I want to show that Java’s reputation for verbosity stems partly from its critics’ lack of familiarity with its libraries and terser idioms. Here’s the original version:

Continue reading ›

Tip #7: JUnit Theories

JUnit’s org.junit.experimental.theories package contains a few annotations that you can use to make your parametrised tests neater. This is an example of a test from JFreeChart (after a partial refactoring, see Tip #6) that could benefit from being parametrised:

Continue reading ›

Refactoring #1: Bob Martin’s Clean Code, p.29

In Bob Martin’s Clean Code, a refactoring is presented in page 29 (written by Tim Ottinger) for a utility that prints an amount-specific message. For instance, when invoked like this:

Continue reading ›

Tip #6: Hamcrest

Hamcrest is a library that you can use to make your tests more fluent. This is a not-so-fluent test  picked from the Swing chart library JFreeChart:

Continue reading ›

Tip #5: String.format()

You can use String.format() to make string building neater.This is a snippet taken from javax.swing.JComponent:

  protected String paramString() {
        String preferredSizeString = (isPreferredSizeSet() ?
				      getPreferredSize().toString() : "");
        String minimumSizeString = (isMinimumSizeSet() ?
				    getMinimumSize().toString() : "");
        String maximumSizeString = (isMaximumSizeSet() ?
				    getMaximumSize().toString() : "");
        String borderString = (border != null ?
			       border.toString() : "");

        return super.paramString() +
        ",alignmentX=" + alignmentX +
        ",alignmentY=" + alignmentY +
        ",border=" + borderString +
	",flags=" + flags +             // should beef this up a bit
        ",maximumSize=" + maximumSizeString +
        ",minimumSize=" + minimumSizeString +
        ",preferredSize=" + preferredSizeString;
    }

Continue reading ›

Tip #4: Underscores In Method Names

Sometimes method names in tests end up having many words. Here’s an example taken from a test in Fitnesse, the acceptance test framework by Bob Martin:

	@Test
	public void processTestResultsShouldBuildUpCurrentResultAndFinalSummary() throws Exception

Whilst this verbosity is necessary if tests are to be a project’s executable documentation, readability may be improved if you use underscores instead of camel case:

	@Test
	public void process_test_results_should_build_up_current_result_and_final_summary() throws Exception

Thanks to Bert for suggesting this.

Tip #3: Static Factory Methods For Collections

Code that creates new objects is messy in general, but a specially verbose case is the construction of generic collections. Here’s an example taken from javax.script.ScriptEngineManager in jdk 6:

	private void init(final ClassLoader loader)
	{
		globalScope = new SimpleBindings();
		engineSpis = new HashSet<ScriptEngineFactory>();
		nameAssociations = new HashMap<String, ScriptEngineFactory>();
		extensionAssociations = new HashMap<String, ScriptEngineFactory>();
		mimeTypeAssociations = new HashMap<String, ScriptEngineFactory>();
		AccessController.doPrivileged(new PrivilegedAction<Object>()
		{
			public Object run()
			{
				initEngines(loader);
				return null;
			}

		});
	}

Continue reading ›

Tip #2: Bracket Fading

You can manipulate your IDE’s syntax highlighting settings to reduce the amount of syntax noise in your code, especially important if you are making extensive use of nested functions and method chaining. Here’s a piece of code (taken from the GOOS book) without:

and now with bracket fading:

Continue reading ›

Tip #1: Fluency Methods

One simple technique to make your code better express intent is to use fluency methods, methods that have no side effect and whose sole purpose is to act as syntactic sugar. Here’s an example of a method taken from Freeman & Pryce’s  Growing Software Oriented Software:

	public void adjudicateIfReady(final ThirdParty thirdParty, final Issue issue)
	{
		if (firstParty.isReady())
		{
			organization.adjudicateBetween(firstParty, thirdParty, issue);
		}
		else
		{
			thirdParty.adjourn();
		}
	}

And now with fluency methods:

Continue reading ›