Java Type Safety – Sacrificing Type Safety for a Nicer Programming Interface in Java

dynamic-typingjavareflectionstatic-typing

When and why would you generally sacrifice typesafety for a nicer programming interface?

Let me give you an example: if you had the choice between two event aggregators, which one would you prefer and why?

Reflective Version:

SomeEvent.subscribe(instance, "nameOfAMethod"); //method called via reflection
SomeEvent.fire(arg1, arg2);  //the firing could actually even be statically typed

Statically typed version:

EventSystem.getEvent(SomeEvent.class).subscribe(new EventHandler<Payload>() {
   public void eventOccurred(Object sender, Payload payload) {
       //event handler code here
   }
});

EventSystem.getEvent(SomeEvent.class).fireEvent(payload);

Please note, that in Java, due to type erasure, you cannot implement a generic interface with different type parameters more than once and need to resort to anonymous or external classes for handlers.

Now the reflective event system has a nicer user interface, but you lose type safety. Which one would you prefer? Would you create empty event classes just for the sake of having a symbol, like Microsoft does it with PRISM in its event aggregator?

Best Answer

When and why would you generally sacrifice typesafety for a nicer programming interface?

Rarely if ever, and then only if the type un-safety was dealt with effectively in another manner.

Verbose/awkward programming interfaces yield a little fewer bugs, and far lower severity bugs than typeless interfaces in the middle of typed languages. Because let's be honest, using string lookups or casting out of Object is its own horrible programming interface - now you have a horrible programming interface and typing issues.

Related Topic