views:

203

answers:

7

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.

+12  A: 

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.

Reed Copsey
+1 for `abstract` on required methods.
Fredrik Mörk
IMO, Abstract FTW.
Yoopergeek
Abstract doesn't fit, but the "a functional but a notifcation" is a good point +1
Dario
Hrm. Given that this probably makes no sense without an implementation of "Render" and "Move", abstract seems like a perfect fit. Init() may not be abstract (some implementations may be able to ignore this), but it seems like EVERY usage case needs to know how to move and render for this to make sense...
Reed Copsey
Well, since the library has certain graphics/math capabilities, it might be even be useful without render/move just to protocol numerical computations ;) But I get the point^^
Dario
Well, that was why I put the "if" in my answer ;) If the class is useful without this, then virtual makes the most sense. However, given that there are multiple use scenarios, you may want to consider breaking this into more than one class (ie: the form handles rendering, with a separate class(s) for numerical simulation, used by the form).
Reed Copsey
+3  A: 

There's another option, borrowed from Functional programming: expose the extension points as properties of type Func or Action, and have your experiments provide delegates thusly.

For example, in your simulation runner, you'd have:

public class SimulationForm
{
    public Action Init { get; set; }
    public Action<Graphics> Render { get; set; }
    public Action<double> Move { get; set; }

    //...
}

And in your simulation you'd have:

public class Simulation1
{
    private SimulationForm form;

    public void Simulation1()
    {
        form = new SimulationForm();
        form.Init = Init;
        form.Render = Render;
        form.Move = Move;
    }

    private void Init()
    {
        // Do Init code here
    }

    private void Render(Graphics g)
    {
        // Do Rendering code here
    }

    private void Move(double dt)
    {
        // Do Move code here
    }
}

Edit: For a very silly example of exactly this technique that I used in some private-facing code (for a private play-around project), check out my delegate-powered-collection blog post.

Erik Forbes
+1 for a novel idea. I'm unsure if it's the "best" approach.
ScottS
I don't know if it is the best approach either - I just wanted to point out yet another alternative.
Erik Forbes
@Erik: Prefacing my comment with "I've used this strategy for some particular problems in the past:" remember that this is not one of the most common ways people think of to extend programs, which can lead to some confusion in how an API is intended to be used. It's important to weigh the advantages of this against the chance that other developers will have to spend time trying to understand it. :)
280Z28
That's very true. I usually don't use this technique in an API that I expect others to consume, so I tend not to come up against that issue, and if I do (when I think this pattern is the best for this problem) I document it heavily.
Erik Forbes
+4  A: 

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.

winSharp93
+7  A: 

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.

LBushkin
+2  A: 

neither.

you should consume a class that implements an interface which defines the functions you require.

Hellfrost
+1  A: 

Why is interface not a choice for this?

epitka
A: 

Use a virtual method to allow a specialization of the base class - the inner details.

Conceptually, you can use events to represent the 'output' of a class, apart from return methods.

kyoryu