views:

63

answers:

4

A subclass needs to know when particular events occur withing its superclass, but there are more than one ways for the superclass to break the news. Here are 2:

  • dispatch an event
  • call an abstract method which the subclass could eventually override

I was wondering if best practices would recommend one of the approaches over the other.

P.S. I was working with ActionScript when I thought of this question.

A: 

OOP is all about objects sending messages to objects. The best way to do it would be defining a method and overriding it.

Of course, you posed a false dichotomy: when you dispatch an event, it's eventually gonna end up calling some method of the class, which may be overriden.

Tordek
+2  A: 

That depends on the nature of the problem you're trying to solve. Does the processing done by the subclass need to be asynchronous? If so, that is an argument in favor of an event-based design. Could things that don't subclass from your class want to know about it? That's another argument in favor of an event-based design. Other than that, it's probably easiest to provide an abstract method that serves as a hook into your logic, because that's what a lot (most, in my experience) of programmers would expect.

Hank Gay
Excellent points! In the context of my question the answer to both questions is no. I guess I'll use the hook approach.
Emanuil
A: 

The abstract method is best. With the event you are introducing unnecessary complexity.

JoelFan
+2  A: 

There is no "best" approach here, both have different semantics which I will outline here.

Overriding Methods:

  • Faster than delegates
  • Force subclasses to override (abstract methods)
  • Only the subclasses method is called, not the parent classes
  • -> Use Method overriding when you want to change the behavior of a class

Events:

  • Register multiple event handlers instead of one
  • Easy asynchronous operations
  • -> Use Events when you want to supplement/extend the behavior of a Class
Johannes Rudolph