Multi-value option handler in args4j

If you are building a command-line app and you want to pass multiple values in a single option, there is a built-it support for that in args4j.

The only thing you have to do is to extend org.kohsuke.args4j.spi.DelimitedOptionHandler, passing the delimiter ("," in the example below) and the single-value option handler (IntOptionHandler).

public class MultiIntOptionHandler extends DelimitedOptionHandler<Integer> {
    public MultiIntOptionHandler(CmdLineParser parser, OptionDef option, Setter<? super Integer> setter) {
        super(parser, option, setter, ",", new IntOptionHandler(parser, option, setter));
    }
}

The usage is straightforward:

@Option(name = "-e", aliases = "--elapse", usage = "elapses in", handler = MultiIntOptionHandler.class)
private List<Integer> elapsesIn = new ArrayList<>();

Reasons to wrap a primitive type as a value object

One of common code smells is Primitive Obsession:

using primitive objects to represent domain ideas
(c2 wiki)

We refactor this smell by introducing Value Objects.

A Value Object represents a domain concept whose identity is made up of all its parts. For example, an instance FullName("Marcin", "Gryszko") of FullName(first, last) cannot be distinguished from another instance FullName("Marcin", "Gryszko"). On the hand, a (DDD) Entity has an identity composed of a single or multiple attributes. Entities are created and its existence continues as time passes. Person(SomePersonalNumberGivenAtBirth("ABC123456"), FullName("Marcin", "Gryszko") refers to the same human being, even if I change my first or last name.

Value Objects can wrap single or multiple attributes. Usually, nobody is sniffy about a Value Object with at least two attributes. It’s common sense to encapsulate cohesive attributes into a new type. But what with a single attribute? Why is it worth to invest some time to write additional code? These are my arguments I bring forward to my fellow developers.

Documentation

The same concept is repeated across many domain classes. It’s also quite important in your domain. So you lift it to a type. You give it a well understandable name. Now it’s clear that AccountId means something special in the system.

Validation

You don’t allow to sneak invalid values into your domain. Everything can be a String. But if you have an EmailAddress, you can roughly verify if the address is syntactically correct1 . Or if the HourOfDay describes a day fraction used on the planet Earth.

Format and unit of measure independence

Is this id a string or a number? Who cares! Let’s hide this information in an Id type. Is long distance in meters or in kilometres? long distanceInKm is much better. However, when we want suddenly make some calculation in inches? Wouldn’t be better that a Distance instance could hide the storage unit and have a couple of creation and conversion method (with distances in various units)?

[1] Instead to try to come up with a perfect, RFC 2822 compliant regular expression, just send a verification email. You already know that if you solve a problem with a regex, you already have two problems.

Serve JSONP in Dyson

Dyson is a great fake JSON server written in JavaScript/Node.JS.

In my current pet project, I have a fake Strava API server. Strava REST API allows you to use JSONP to overcome cross-domain restrictions. You have to add a callback parameter to the query string.

To simulate it with Dyson, you have to override the render method of the Express middleware in the endpoint definition. In my solution, depending on the existence of the callback parameter, I return either raw JSON response or I wrap it with the provided callback:

Reformat Java code in IntelliJ according to Uncle Bob’s stepdown rule

Reformat Java code in IntelliJ according to Uncle Bob’s stepdown rule

When organizing methods inside a class, I use Uncle Bob’s stepdown rule (page 37 of the Clean Code book, Episode 3, Functions of the Clean Coders series).

What does the rule say? The code should read like a top-down narrative. Start with high-level, abstract paragraphs. Then dive into details. Translating it into the world of functions: public go first, below you put private functions (used by the public functions), then private functions called from private functions, and so on.

Until recently, I was reordering methods manually, until I discovered that IntelliJ can do this work for you (with some limitations, as we are going to see soon).

This formatting is not enabled by default. To turn it on, go to Preferences, then Editor/Code Style/Java. In the Arrangement tab, check Keep dependent methods together and select breadth-first order or depth-first order.

Configure Java code arrangment

How does it work? Let’s reformat this class:

public class StepdownRule {
    private void nestedPrivateMethod() {}

    private void secondPrivateMethod() {}

    private void firstPrivateMethod() {
        nestedPrivateMethod();
    }

    public void publicMethod() {
        firstPrivateMethod();
        secondPrivateMethod();
    }
}

Show Reformat File Dialog (alt-shift-cmd-L on Mac), mark Rearrange code and let the IDE do the work for you:

stepdown_rule_reformat

Breadth-first

public class StepdownRule {
    public void publicMethod() {
        firstPrivateMethod();
        secondPrivateMethod();
    }

    private void firstPrivateMethod() {
        nestedPrivateMethod();
    }

    private void secondPrivateMethod() {}

    private void nestedPrivateMethod() {}
}

Depth-first

public class StepdownRule {
    public void publicMethod() {
        firstPrivateMethod();
        secondPrivateMethod();
    }

    private void secondPrivateMethod() {}

    private void firstPrivateMethod() {
        nestedPrivateMethod();
    }

    private void nestedPrivateMethod() {}
}

In both orderings, public method goes first. Fine.

Breadth-first puts then both first-level private methods, placing them in the same order as they are called from the public method. Then go second-level private methods.

Depth-first algorithm doesn’t take into account the call order. It favors private methods without nesting. Then it puts private methods calling other private methods.

I’d expect that depth-first ordering should reorder everything perfectly according to the stepdown rule. However, there is an issue – private methods of the same call level hierarchy remain unordered. Breadth-first takes the call order into account, but the stepdown rule is not 100% followed. Choose the lesser evil.

Featured image by Donncha Ó Caoimh.

Listen to your tests – a real example

Listen to your tests – a real example

When reading about TDD you find often sentences like “listen to your tests” or “tests give you feedback about design”. How does it look in practice?

A couple of days ago I interviewed a prospective frontend developer. He submitted the coding assignment and during the on-site interview we kindly asked him to add a new feature to the solution.

The exercise is fairly uncomplicated. You have to display a list of hotels. When a hotel is clicked, its details appear next to the list. The feature to implement was search. Quite simple too – type a text in the box and restrict the list of hotels to the matching ones.

First unit test attempt was like this:

var view = new SearchView();

view.fill('Sunny Palms');

// assert what ???

I was in the navigator role and asked my partner:

“How are you going to check the expected outcome? There is a lot of work to do: we have to access the DOM, extract displayed hotels and verify their names if they match the search pattern.”

I would take us much time to get to a failing test (red lamp in TDD). The test was telling us that we were not on the right way. The component under development probably would have too many responsibilities.

I proposed a different solution. There was already implemented an event bus. The idea was to raise an event and let other component worry about how to handle the search.

The test was quite simple

var eventBus = new EventBus(),
  term;
eventBus.subscribe('search', function (event, data) {
    term = data;
});

view.fill('Sunny Palms');

expect(term).toEqual('Sunny Palms');

We had a failing test. We got to green very quickly – the implementation of the fill method was straightforward.

I wanted to share this story because when I was starting with TDD, the advice “listen to your tests” seemed very awkward. Where do I have to put my ear? Do the tests whisper you that you are wrong? Do they send Morse code? During the programming session I described, it was not a crystal-clear sound. It was a desperate cry for a better design.

Credits to Ky for the “Listen” licensed under CC BY 2.0.