Tap That Assignment With Java
Want to learn more about how to instantiate an object that will populate its state? Check out this post where we look at using built-in method, tap, to combat this problem.
Join the DZone community and get the full member experience.
Join For FreeWhen working with mutable objects, I often instantiate an object and subsequently call mutator methods to populate its state. I find this both boring and smelly.
Consider the following (admittedly contrived) unit test:
@Test
public void primary_org_is_most_precise() {
Set<Org> orgs = new HashSet<>();
Org org1 = new Org();
org1.setCode("1200");
orgs.add(org1);
Org org2 = new Org();
org2.setCode("1234");
orgs.add(org2);
Org org3 = new Org();
org2.setCode("1230");
orgs.add(org3);
Employee subject = new Employee();
subject.setOrgs(orgs);
Org expectedPrimaryOrg = new Org();
expectedPrimaryOrg.setCode("1234");
assertThat(subject.getPrimaryOrg()).isEqualTo(expectedPrimaryOrg);
}
While it's relatively straightforward, it is still hampered by smells:
- The method scope is polluted with unnecessary objects. The ephemeral
orgs
,org1
,org2
, andorg3
variables, are only necessary for the setup of theEmployee
instance, which is the subject of the test. - Since object instantiation and mutation are done in independent operations, I am forced to give these objects names. Furthermore, the single method scope requires me to name all objects uniquely.
- The number of similarly named variables sharing the sole scope puts me at risk of making a silly mistake. Such mistakes can be hard to spot. Did you notice the mistake in my example code?
- Overall, the test reads poorly. I must wade through a dozen lines of setup code to glean the important pieces. The ratio of setup code to assertion code seems out of balance, too.
There are ways to alleviate these issues — at least in part. I could separate the setup logic into its own dedicated method, but that introduces two methods with a 1:1 coupling per test case. The collection factory methods introduced in Java 9 could benefit, but only with the creation of the Set<Org>
. I could add an Org(String code)
convenience constructor and perhaps a setOrgs(Org... orgs)
convenience method on Employee
, but this won't scale well for more complex object graphs.
Ultimately and generally speaking, I would like to consolidate instantiation and mutation concerns whenever I assign a variable reference and have these concerns isolated in their own scope.
Is there a solution?
"Tap" to the Rescue
A number of languages offer built-in methods that offer a solution to this very problem. In Kotlin, it's called "apply;" in Ruby and Groovy, it's called "tap."
Regardless of the name, the method takes as an argument with some lambda/closure/code block that can interact with the object, the method it was invoked on, and ultimately, return that object.
Here's an example of how the test method could be re-written with Groovy's tap method:
@Test
void primary_org_is_most_precise() {
def subject = new Employee().tap {
orgs = new HashSet<Org>().tap {
add(new Org().tap {
code = '1200'
})
add(new Org().tap {
code = '1234'
})
add(new Org().tap {
code = '1230'
})
}
}
assert subject.primaryOrg == new Org().tap { code = '1234' }
}
Granted, there are alternatives to tap
that could be used here instead, but the point is that the tap
method resolves the aforementioned smells with my original code.
- It creates distinct scopes for each
Org
instance and the Set. - In doing so, it eliminates the requirement to give each instance a unique name.
- Since the objects are not in the same scope, I avoid mistakes related to naming. There's no way for me to accidentally set the
code
property of the secondOrg
instance twice, like I did in my original Java method. - Because all setup logic is contained with a sub-scope of the test method's scope, I'm better able to visually distinguish setup code from assertion code.
Mimicking Tap in Java
Although not as elegant as Groovy, a tap
-like method can be created in Java fairly easily:
public static <T> T tap(T object, Consumer<T> consumer) {
consumer.accept(object);
return object;
}
The primary differences between this Java method and Groovy's are:
- It's a static method versus an (extension) instance method on
java.lang.Object
. - The Java method passes the object as an argument to the consumer, whereas the Groovy method will simply delegate to the object
tap
was invoked on. Because Java'sConsumer
needs an argument, I'm forced to name it, but at least the name is associated with its own scope.
Usage Examples
Let's look at some examples for using our new tap
method. Here is the original test method re-written so that the employee assignment is tapped:
@Test
public void primary_org_is_most_precise() {
Employee subject = tap(new Employee(), employee -> {
employee.setOrgs(tap(new HashSet<>(), orgs -> {
orgs.add(tap(new Org(), org -> org.setCode("1200")));
orgs.add(tap(new Org(), org -> org.setCode("1234")));
orgs.add(tap(new Org(), org -> org.setCode("1230")));
}));
});
assertThat(subject.getPrimaryOrg()).isEqualTo(tap(new Org(), org -> org.setCode("1234")));
}
Overall, I consider this a better method than the original.
The tap
method is also nice for dealing with the annoying java.util.Date
API:
Date date = tap(Calendar.getInstance(), cal -> {
cal.set(Calendar.YEAR, 2021);
cal.set(Calendar.DAY_OF_MONTH, 9);
cal.set(Calendar.MONTH, 1);
cal.set(Calendar.HOUR_OF_DAY, 20);
cal.set(Calendar.MINUTE, 3);
}).getTime();
I've also discovered tap
to be useful for simply isolating concerns within a unit test method. For example, consider an integration test for adding a user via a RESTful interface. There are three REST calls to make:
- A GET to ensure the user does not exist before attempting to create it.
- The PUT to add the user.
- Another GET to make sure the user was added.
Each of these three HTTP requests can be done within its own tap
call to isolate objects related to the response and its payload.
Opinions expressed by DZone contributors are their own.
Comments