3

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?

1
  • 8
    If you want to sacrifice type safety, why are you using Java? You end up with the worst of both worlds! :)
    – Andres F.
    Commented Mar 27, 2013 at 21:51

6 Answers 6

8

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.

3
  • What do you mean by dealing with type un-safety effectlivey? Would annotations be good enough for you? Checks if the method actually exists during the subscription process?
    – Falcon
    Commented Mar 27, 2013 at 20:52
  • @falcon - If the design limits the possible misuse, possibly by limiting the subscription or firing; possibly by making a 'user space type system' sort of thing, possibly by making the interface so generic that anything is acceptable. Frankly, using events at all is something I've seen fall away from designs in recent years (for good reason). Aggregating them seems like fuel to the fire. Doing it in Java would make me extra sad. At least in C# I can do tricks with generics to validate handlers...
    – Telastyn
    Commented Mar 27, 2013 at 21:06
  • 1
    This is interesting: "Frankly, using events at all is something I've seen fall away from designs in recent years (for good reason)." Can you elaborate on that or provide a link?
    – Falcon
    Commented Mar 27, 2013 at 21:07
7

I think your example does not really compare things at the same level of detail, whereas this would:

  1. stringly typed version:

    public void subscribeTo(Event event) {
         event.substribe(this, "handleEvent");
    }
    public void handleEvent(Object sender, Payload payload) {
        //do something
    }
    
  2. statically typed version:

    public void subscribeTo(Event event) {
        event.substribe(new EventHandler<Payload>() {
            public void eventOccurred(Object sender, Payload payload) {
                //do something
            }
        });
    }
    

So in essence the latter is not critically longer. But as others have pointed out, it is both faster and safer.

If you're really that worried about token count, you shouldn't be using Java to start with ;)

5

You would be sacrificing more than just type safety. Reflection is at least an order of magnitude slower in Java than using strong types.

It's a false dichotomy anyway. It's possible to have a nice programming API without sacrificing type safety. See http://boo.codehaus.org/

3
  • 2
    Agreed on this, but I don't understand how Boo helps here, since it's for the CLI rather than the JVM. Why not just use Scala (or any other JVM capable language except Java) and be done with it?
    – back2dos
    Commented Mar 27, 2013 at 20:56
  • That works for me. The OP did mention Microsoft; Boo is just an example of the possible ways the syntax can be made nicer, while still retaining static typing. Commented Mar 27, 2013 at 23:13
  • Broken link: boo.codehaus.org Commented Sep 30, 2022 at 1:53
3

I actually implemented a strongly-typed event system similar to yours once (in C#). It was horribly over-engineered and horrible to use. By the time I had discovered how horrible it was, it had spread throughout my application like a virus. It took forever to refactor, and it felt good when it was gone.

Would you create empty event classes just for the sake of having a symbol, like Microsoft does it with PRISM in its event aggregator?

Like this?

applicationEvents.Foo.Subscribe(myHandler)

Yes. Definitely yes. Why not? It's way more simple, easy to understand, and type safe to boot. Any new developer would have all the available events in one place and wouldn't have to go searching your source code to figure out what events are available and how to use them.

No sense in sacrificing type safety when you don't have to.

EDIT:

If I seem overly aggressive, I apologize. I don't mean to criticize your design, I am just lamenting my own mistake which I made in the past, and it's very similar to what you're doing. Just be careful not to overcomplicate things.

1

if you have the time now then do it with the type checking. if its code that might last up to December 2013 you will regret method 1 later, unless its a small project and you will be the only one working on it ... no even then if you have the time i would go with the typed.

Why? clearer, less mistakes, more verbose yes but will help keep some bugs at bay and that is a good thing

-1

I am not 100% certain what those two examples are supposed to do, but I guess an alternative would be to use an enum. I imagine the number of allowed strings like "nameOfAMethod" is limited and you could put the anonymous class gory stuff in that enum.

enum Methods {
    NAME_OF_A_METHOD {
        EventHandler get(final Object instance) {
            return new EventHandler<Payload>() {
                public void eventOccurred(Object sender, Payload payload) {
                    //do something with instance
                }
            }
        }
    };

    abstract EventHandler get(Object instance);
}

And your example could become:

EventSystem.getEvent(SomeEvent.class).subscribe(NAME_OF_A_METHOD.get(instance));

Not sure if it is directly applicable to your use case but you get the idea.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.