Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Yet Another Reason Why Java Needs Closures

DZone's Guide to

Yet Another Reason Why Java Needs Closures

· Java Zone ·
Free Resource

Verify, standardize, and correct the Big 4 + more– name, email, phone and global addresses – try our Data Quality APIs now at Melissa Developer Portal!

Ever try to unit test code with static method calls? That's right. You know how this feels.

 

class  Untestable{
public void doSomething(){
...
if ( Util.openSocketAndThenGoToFileSystem() )
...
}
}
Unit testing doSomething is often impossible because unit tests simply don't do things like talk to networks or file systems. It's even more "fun" when someone puts code like this in a constructor - that way you can't even instantiate an instance of Untestable outside the production environment.

This is particularly painful in Java (as it stands today) for two reasons. First, there are no open classes. Sure, there is conditional compilation or cglib but at the end of the day, it's never going to be as easy as it is in JavaScript, Python, etc.

Second, it calls a static method. If you haven't read Steve Yegge's post on this matter, verbs are second class citizens in Java. Because each verb must be escorted by a noun at all times, methods cannot be stubbed out or mocked. This limitation has profound side effects on the maintainability (and profitability) of every large Java code base.

Enter Closures ...


We can refactor the Untestable class to a Testable class.
class Testable{

private final { => boolean } collaborator;

Testable({ => boolean } collaborator){
this.collaborator = collaborator;
}

public void doSomething(){
...
if ( collaborator.invoke() )
...
}
}
By declaring a closure instance variable we can use Dependency Injection to exercise the functionality of Testable without doing something expensive. This is a lot easier than retrofitting an interface or inner class. Our test methods now look like this:

public void testDoSomething(){
Testable testable = new Testable({ => true });
testable.doSomething();
assertTrue(true, testable.someSideEffect());
}



Neal Gafter tells me the chances of closures making it into the next version of Java is getting smaller and smaller. I'm keeping my fingers crossed, time will tell. Keep up the good work Neal.

From http://notdennisbyrne.blogspot.com/

Developers! Quickly and easily gain access to the tools and information you need! Explore, test and combine our data quality APIs at Melissa Developer Portal – home to tools that save time and boost revenue. Our APIs verify, standardize, and correct the Big 4 + more – name, email, phone and global addresses – to ensure accurate delivery, prevent blacklisting and identify risks in real-time.

Topics:

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}