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

Public Defender Methods: A Good Idea?

DZone's Guide to

Public Defender Methods: A Good Idea?

· Java Zone
Free Resource

Get the Edge with a Professional Java IDE. 30-day free trial.

While catching up on the latest news from Java 7, I read this article from Baptiste Wicht, which explains a new proposal ( pdf). The proposal itself is fairly straightforward, addressing the problem that once an interface is published, methods cannot be added without breaking the interface. In particular, this proposal would allow the Collections interface to take advantage of closures, a first draft of which is included in JDK7. Baptiste for provides a very clear explanation of the proposal, here is a summary

At the moment, if you need to extend functionality, you can create static methods, much like Collections does with it's reverse method. This has the issue that you cannot override the reverse method for your own collections implementation. And more to the point, wouldn't it be nice to have a reverse() method in the List itself?

The proposal would result in syntax that looks as follows:
public interface List<T> extends Collection<T>
{
public int size();
// The rest of the existing Set methods
extension void reverse() default Collections.<T>reverse;
}

This would mean that you could extend the reverse method yourself if you wish. If you don't want to, the functionality would default to calling another methods (in this case Collections.reverse()).

Is this something you'd want to do? I don't think I'd like to see the addition myself. I prefer simple, unambiguous code. If I break an interface, clients of that interface need to deal with the change. At least it makes it very clear that the contract has changed.

Get the Java IDE that understands code & makes developing enjoyable. Level up your code with IntelliJ IDEA. Download the free trial.

Topics:

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}