Will EJB 3.1 Kill Java Interfaces? 📎
Java Interface are used in following scenarios:
- You want to swap several implementations, or hide them behind an interface. (Strategy pattern, or even API-SPI)
- You want to mock out existing functionality (its technically related to 1. but the intention is different)
- You want to use JDK's dynamic proxy (the "lightweight" AOP).
In EJB 3.1 with the "no-interface view" interfaces are optional - you can get rid off interfaces entirely.
Mocking works just perfectly with frameworks like mockito - interfaces are no more necessary for mocking. You can easily provide mocks for (non-final) classes and change their behavior for test purposes.
@Stateless
public class Service {
public int getNumber(){
return 1;
}
}
//...
import com.abien.business.nointerface.control.Service; import org.junit.Test; import static org.junit.Assert.*; import static org.mockito.Mockito.*; public class ServiceFacadeTest { @Test public void twoIsFalse(){ Service service = mock(Service.class); when(service.getNumber()).thenReturn(2); //...
}
}
Also interceptors (similar to dynamic proxies) do not require interfaces either. You can easily decorate EJB 3.1 without having any interfaces.
The only thing, which cannot be achieved without having an interface is swapping different implementations without recompiling the client. But exactly this (item 1.) was very rare in my past projects. In vast majority of all cases you will only have exactly one implementation of an interface. You could, of course, provide an interface in advance and hope that it will pay-off in future, but it seems to be unlikely.
With EJB 3.1 interfaces became the artifact again, for what they were actually aimed: a typesafe facade for hiding multiple implementations. You should only use interfaces EJB 3.1, in case you actually have multiple implementations for one interface.
You can check-out the whole project with source code from: http://kenai.com/projects/javaee-patterns/ [NoInterfaceViewEJBUnitTest]. Tested with Netbeans 6.7 and Glassfish v3 Preview.
[I described in the book "Real World Java EE Patterns" Interceptors, Dependency Injection etc. more deeply]