The long way through Software Craftsmanship

What defines a dependency

Jul 13, 2015 - 1 minute read - Comments - goosjavacodefragmentdependencynotificationgooslistenerobject-stereotype

A friend and I were arguing about this code (fragment):

public void register (final String userName)  {
    try {
        registeredUsers.add(new User(userName));
    } catch (AlreadyRegisteredUserException e) {
        resultListener.alreadyRegistered(userName);
    }
}

I would have said that resultListener is a dependency as, first, it was injected by the constructor, second, it is necessary for the execution (negative case).

He suggested that:

  • being injected through the constructor is usually what happens with dependencies, but does not make it one (i.e., something can be injected by the constructor and not be a dependency)
  • what defines a dependency is related to the business: if this behavior is mandatory for the business, then it is a dependency.

As a conclusion, resultListener would be a notification, as business does not require it.

On a later commit, we decided to inject it to registeredUsers (fragment)

public void add (User user, final RegistryResultListener resultListener) {
    if(contains(user)) {
        resultListener.alreadyRegistered(user.name());
        return;
    }

    users.add(user);
    resultListener.successfullyRegistered(user.name());
}

Note: for cases when no one needs to be informed about the users being registered or not, a null-object pattern will suffice, as there is no check for null reference in the parameter resultListener.

Note: more information on object stereotypes can be found here

Object Peer Stereotypes Faster site generation for Octopress 2