views:

172

answers:

4

I would like to have your opinion as to the pros and cons of using delegates instead of virtual functions aud subclassing?

A: 

Here is my take.

  1. Its not object oriented programming anymore. It's the old way of doing things.

Hm. That's all I have.

Daniel A. White
New does not necessarily mean better. Just sayin'
Mehrdad Afshari
+1  A: 

It very muych depends whether you're aiming for the object oriented or functional style really.

  • Object oriented => inheritance and overriding of methods
  • Functional => passing delegates to method

Usually it's best to pick one or the other, but sometimes it doesn't hurt to mix. I generally try to stick to the OO approach, since that is the main heritage of C#.

However, in certain circumstances, passing lambda epxressions to functions removes a lot of the boilerplate code. Indeed, in the extreme case, the alternative to creating a method that takes a delegate/lambda expression could be overriding the base class a dozen or so times with minor changes. Saying this, if the behaviour you want to customise is fairly fixed, than subclassing is usually the better choice.

Noldorin
Could delegate also aid testing perhaps, since it won't be necessary to extract an interface or subclass to isolate a method ?
Andrei Tanasescu
@Andrei: Yes, it could quite possibly make testing more straightforward, though I wouldn't base your design decision on it... Very much depends on the context - you usually don't want to be creating new derived classes for testing though.
Noldorin
A: 

Vague question, so you get a vague answer:

Use virtual methods and subclassing to represent a model. Use delegates to implement a mechanism.

See my answer to

http://stackoverflow.com/questions/2020381/when-to-use-callbacks-instead-of-events-in-c

for additional thoughts in this vein.

Eric Lippert
+1  A: 

I think the delegate issue is a red herring: this is really about the strategy pattern versus the template pattern.

"Favor composition over inheritance" is excellent advice, so the strategy pattern is the better default technique (whether you use objects or delegates to do your dirty work), mainly because it provides superior decoupling.

I only use subclassing (the template pattern) when there's a suitable inheritance relationship (per the Liskov Substitution Principle), the algorithm I'm varying needs access to the protected methods of the base class and I want a high degree of cohesion.

Jeff Sternal