Wednesday, January 11, 2012

Better than null

A rich, delightful post from Joel Neely on an alternative to returning null to signal "not found" or "No": have the caller supply a callback with appropriate methods for condition signaling. In Java:

interface Found {
    void present(final String name);

    void absent(final String name);
}

class Phonebook {
    private final Set<String> names = new HashSet<>;

    void add(final String name) {
        names.add(name);
    }

    void remove(final String name) {
        names.remove(name);
    }

    void find(final String name, final Found found) {
        if (names.contains(name))
            found.present(name);
        else
            found.absent(name);
    }
}

class LookupPhone extends Phone implements Found {
    private final Phonebook phonebook;

    LookupPhone(final Phonebook phonebook) {
        this.phonebook = phonebook;
    }

    @Override
    public void present(final String name) {
        ringUp(name);
    }

    @Override
    public void absent(final String name) {
        complainIsUnknown(name);
    }

    void placeCall(final String name) {
        phonebook.find(name, this);
    }
}

(Keyed directly into the editor: apologies for typos.)

No comments: