Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Virtual Methods or Events in C#

I'm currently writing a little C# library to simplify implementing little physical simulations/experiments.

The main component is a SimulationForm that runs a timer-loop internally and hides boilerplate-code from the user. The experiment itself will just be defined through three methods:

  1. Init() (Initialize everything)
  2. Render(Graphics g) (Render current simulation state)
  3. Move(double dt) (Move experiment for dt seconds)

I just wondered what is the better choice for letting the user implement these functions:

1) Virtual methods to be overridden by the inheriting form

protected virtual void Init() {} 
...

or

2) Events

public event EventHandler<MoveSimulationEventArgs> Move = ...
...

Edit: Note that the methods should not be abstract anyway. In fact, there are even more and none of them has to be implemented. It's often convenient to leave them out since many simulations don't need them.

The cool thing about this being a "normal form" is that you can write

partial class frmMyExperiment : SimulationForm {
}

and you're perfectly able to interact with the designer and all inherited controls and settings/properties. I don't want to lose this features by having a completely different approach.

like image 742
Dario Avatar asked Dec 16 '09 20:12

Dario


3 Answers

I prefer using virtual methods in this case.

Also, if the methods are required in order to function, you can make your class an abstract class. This is the best in terms of usability, since it causes the compiler to enforce the usage. If the user tries to use your class/Form without implementing the methods, the compiler will complain.

Events would be a bit inappropriate here, since this really isn't something where you want more than a single implementation (events allow multiple subscribers), and it, conceptually, is more of a functional of the object, and less a notification caused by the object.

like image 117
Reed Copsey Avatar answered Sep 22 '22 17:09

Reed Copsey


Interestingly, I've had to make a similar choice in a design I worked on recently. One approach is not strictly superior to another.

In your example, given no additional information, I would probably choose virtual methods - particularly since my intuition leads me to believe you would use inheritance to model different types of experiments, and you don't need the ability to have multiple subscribers (as events allow).

Here are some of my general observations about choosing between these patterns:

Events are great:

  1. when you don't need the caller to return any information, and when you want extensibility without requiring subclassing.
  2. if you want to allow the caller to have multiple subscribers that can listen and respond to the event.
  3. because they naturally arrange themselves into the template method pattern - which helps to avoid introducing the fragile base class problem.

The biggest problem with events is that managing the lifetime of subscribers can get tricky, and you can introduce leaks and even functional defects when subscribers stay subscribed for longer than necessary. The second biggest problem is that allowing multiple subscribers can create a confusing implementation where individual subscribers step on each other - or exhibit order dependencies.

Virtual methods work well:

  1. when you only want inheritors to be able to alter the behavior of a class.
  2. when you need to return information from the call (which event's don't support easily)
  3. when you only want a single subscriber to a particular extension point
  4. when you want derivatives of derivatives to be able to override behavior.

The biggest problem with virtual methods is that you can easily introduce the fragile base class problem into your implementation. Virtual methods are essentially a contract with derived classes that you must document clearly so that inheritors can provide a meaningful implementation.

The second biggest problem with virtual methods, is that it can introduce a deep or broad tree of inheritance just to customize how a behavior of a class is customized in a particular case. This may be ok, but I generally try avoiding inheritance if there isn't a clear is-a relationship in the problem domain.

There is another solution you could consider using: the strategy pattern. Have your class support assignment of an object (or delegate) to define how Render, Init, Move, etc should behave. Your base class can supply default implementations, but allow external consumers to alter the behavior. While similar to event, the advantage is that you can return value to the calling code and you can enforce only a single subscriber.

like image 23
LBushkin Avatar answered Sep 22 '22 17:09

LBushkin


A little help for deciding:

Do you want to notify other (multiple) objects? Then use events.

Do you want to make different implementations possible / use polymorphism? Then use virtual / abstract methods.

In some cases, even combinidng both ways is a good solution.

like image 22
Matthias Avatar answered Sep 18 '22 17:09

Matthias