Benefits of using delegates?

I am looking to implement an Observer pattern in VB.NET or C # or some other first-class .NET language. I heard that delegates can be used for this, but they cannot understand why they will be preferable to older interfaces implemented on observers. In this way,

  • Why should I use delegates instead of defining my own interfaces and passing references to objects that implement them?
  • Why can I avoid using delegates and go with good ol-mod interfaces?
+7
design-patterns delegates
Nov 19 '08 at 18:08
source share
14 answers

When you can directly call a method, you do not need a delegate.

A delegate is useful when the code that calls the method does not know / does not care about which method it calls - for example, you can call a long-term task and pass it to the delegate of the callback method so that the task can use to send notifications about its status.

Here is an example of (very stupid) code:

enum TaskStatus { Started, StillProcessing, Finished } delegate void CallbackDelegate(Task t, TaskStatus status); class Task { public void Start(CallbackDelegate callback) { callback(this, TaskStatus.Started); // calculate PI to 1 billion digits for (...) { callback(this, TaskStatus.StillProcessing); } callback(this, TaskStatus.Finished); } } class Program { static void Main(string[] args) { Task t = new Task(); t.Start(new CallbackDelegate(MyCallbackMethod)); } static void MyCallbackMethod(Task t, TaskStatus status) { Console.WriteLine("The task status is {0}", status); } } 

As you can see, the Task class does not know and does not care about this - in this case, the delegate must use a method that prints the status of the task to the console. This method could also send status over a network connection to another computer. Etc.

+27
Jun 28 '10 at 17:25
source share

You are O / S and I am an application. I want to tell you to name one of my methods when you discover that something is happening. To do this, I pass you a delegate to my method, which I want to call you. I myself do not call this method, because I want you to call it when you find something. You do not call my method directly because you do not know (at compile time) that the method exists (I was not even written when you were created); instead, you call any method specified by the delegate that you receive at runtime.

+22
Jun 28 '10 at 17:25
source share

Well, technically, you don't need to use delegates (except when using event handlers , then this is necessary). You can do without them. Indeed, this is another tool in the tool box.

The first thing that comes to mind about their use is Inversion Of Control . Each time you want to control how a function behaves externally, the easiest way to do this is to put a delegate as a parameter and execute its delegate.

+9
Jun 28 '10 at 17:24
source share

You do not think as a programmer.

Question: why do you call the function directly when you could call the delegate ?

The famous aphorism of David Wheeler goes: All problems in computer science can be solved at a different level Indirect.

I'm a little upset. Obviously, you will be calling functions directly most of the time, especially in a module. But delegates are useful when a function needs to be called in a context where the contained object is inaccessible (or relevant), such as event callbacks.

+6
Jun 28 '10 at 17:28
source share

There are two places where you could use delegates in the Observer pattern. Since I'm not sure which one you are referring to, I will try to answer both.

First, the use of delegates in the subject instead of the IObservers list. This approach seems a lot cleaner when handling multicast, since you basically have

 private delegate void UpdateHandler(string message); private UpdateHandler Update; public void Register(IObserver observer) { Update+=observer.Update; } public void Unregister(IObserver observer) { Update-=observer.Update; } public void Notify(string message) { Update(message); } 

instead

 public Subject() { observers = new List<IObserver>(); } public void Register(IObserver observer) { observers.Add(observer); } public void Unregister(IObserver observer) { observers.Remove(observer); } public void Notify(string message) { // call update method for every observer foreach (IObserver observer in observers) { observer.Update(message); } } 

If you don’t need to do anything special and require a reference to the entire IObserver object, I would think that delegates would be cleaner.

The second case is using pass delegates instead of IObervers, for example

 public delegate void UpdateHandler(string message); private UpdateHandler Update; public void Register(UpdateHandler observerRoutine) { Update+=observerRoutine; } public void Unregister(UpdateHandler observerRoutine) { Update-=observerRoutine; } public void Notify(string message) { Update(message); } 

However, observers do not need to implement an interface. You could even convey a lambda expression. This change in level of control is largely a difference. Whether it is good or bad is up to you.

+4
Nov 19 '08 at 18:47
source share

A delegate, in fact, passes a reference to a method, not an object ... An interface is a link to a subset of the methods implemented by an object ...

If you need access to several methods of an object in some component of your application, then define an interface representing this subset of object methods and assign and implement this interface for all classes that you may need, go to this component ... Then pass the instances of these classes by this interface, not their concrete class.

If, otoh, in any method or component, all you need is one of several methods that can be in any number of different classes, but they all have the same signature, then you need to use a delegate.

+2
Nov 19 '08 at 18:31
source share

I repeat the answer I gave to this question .

I always liked the metaphor of the Radio Station.

When a radio station wants to transmit something, it just sends it. He does not need to know if anyone is really listening. Your radio can register with the radio station (by tuning using the dial), and all the radio stations (events in our small metaphor) receive the radio, which translates them into sound.

Without this registration mechanism (or event). The radio station would have to contact each radio in turn and ask if it wants to broadcast if your radio says yes, and then immediately sends a signal.

Your code may follow a very similar paradigm, where one class performs an action, but this class may not know or do not want to know who will take care of it or act in this case. Thus, it provides an opportunity for any object to register or unregister to notify that an action has been performed.

+2
Jun 28 '10 at 17:25
source share

Delegates are strong typing for function / method interfaces.

If your language takes the position that there should be strong text input, and that it has first-class functions (both of which are performed by C #), then it would be incompatible to not have delegates.

Consider any method that a delegate accepts. If you didn’t have a delegate, how would you convey something? And how does the caller have any guarantees regarding its type?

+2
Jun 28 '10 at 17:26
source share

I heard some “evangelists of events” talk about this, and say that since the more fragmented the events, the better.

Preferably, the event source should never know about event listeners, and the event listener should never care about who triggered the event. This is not the case today because in the event listener you usually get the original event object.

With that said, delegates are the perfect tool for this job. They allow you to decouple the source of the event and the event observer, because the event source does not need to save a list of all observer objects. It contains only a list of "function pointers" (delegates) of observers. Because of this, I think this is a big advantage over interfaces.

+1
Nov 19 '08 at 18:36
source share

Look at it differently. What advantage does the user interface take advantage of using the standard method supported by the language in both syntax and library?

Of course, there are times when it may have an advantage on an individual order, and in such cases you should use it. In all other cases, use the most affordable canonical solution. This works less, is more intuitive (because this is what users expect), has more support from tools (including IDEs), and most likely the compiler treats them differently, which leads to more efficient code.

Do not reinvent the wheel (unless the current version is broken).

+1
Nov 19 '08 at 18:40
source share

In fact, the delegates had an interesting interview with Sun and Microsoft. While Sun has made a pretty strong stance against delegates, I feel like Microsoft has made an even stronger point for using delegates. Here are the posts:

http://java.sun.com/docs/white/delegates.html

http://msdn.microsoft.com/en-us/vjsharp/bb188664.aspx

I think you will find this interesting reading ...

+1
Jun 28 '10 at 18:27
source share

I think this has more to do with syntactic sugar and the way you organize your code, a good use would be to access a few common context methods that belong to an object or a static class.

this does not mean that you are forced to use them, you can program sth with them and without them, but perhaps their use or not can affect how it is organized, readable and why not cool code will probably bum some lines in your code.

Each example here is good, where you could implement them, as someone said, this is another function in the language that you can play with.

Hello

0
Jun 28 '10 at 7:28
source share

Here is what I can write down as a reason for using a delegate. The following code is written in C #. And follow the comments.

 public delegate string TestDelegate(); protected void Page_Load(object sender, EventArgs e) { TestDelegate TD1 = new TestDelegate(DiaplayMethodD1); TestDelegate TD2 = new TestDelegate(DiaplayMethodD2); TD2 = TD1 + TD2; // Make TD2 as multi-cast delegate lblDisplay.Text = TD1(); // invoke delegate lblAnotherDisplay.Text = TD2(); // Note: Using a delegate allows the programmer to encapsulate a reference // to a method inside a delegate object. Its like the function pointer // in C or C++. } //the Signature has to be same. public string DiaplayMethodD1() { //lblDisplay.Text = "Multi-Cast Delegate on EXECUTION"; // Enable on multi-cast return "This is returned from the first method of delegate explanation"; } // The Method can be static also public static string DiaplayMethodD2() { return " Extra words from second method"; } 

Best regards, Moreover Nandi, Bangladesh

0
Dec 20 '10 at 9:21
source share

Here is an example that might help.

There is an application that uses a large data set. A function is required that allows you to filter data. You can specify 6 different filters.

The immediate thought is to create 6 different methods, each of which returns filtered data. for example

public Data FilterByAge (int age)

public Data FilterBySize (int size)

.... etc.

This is good, but very limited and generates garbage code because it is closed for extension.

It is best to have one filter method and pass information on how the data should be filtered. You can use a delegate here. A delegate is a function that can be applied to data to filter it.

general data filter (action filter)

then the code to use it will be

Filter (data => data.age> 30);

Filter (data => data.size = 19);

Code data => blah blah becomes a delegate. The code becomes much more flexible and remains open.

0
Oct 03 2018-11-11T00:
source share



All Articles