Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
What are some real world places that call for delegates? I'm curious what situations or patterns are present where this method is the best solution. No code required.
As stated in "Learning C# 3.0: Master the fundamentals of C# 3.0"
General Scenario: When a head of state dies, the President of the United States typically does not have time to attend the funeral
personally. Instead, he dispatches a delegate. Often this delegate is
the Vice President, but sometimes the VP is unavailable and the
President must send someone else, such as the Secretary of State or
even the First Lady. He does not want to “hardwire” his delegated
authority to a single person; he might delegate this responsibility to
anyone who is able to execute the correct international protocol.
The President defines in advance what responsibility will be delegated
(attend the funeral), what parameters will be passed (condolences,
kind words), and what value he hopes to get back (good will). He then
assigns a particular person to that delegated responsibility at
“runtime” as the course of his presidency progresses.
In programming Scenario: You are often faced with situations where you need to execute a particular action, but you don’t know in
advance which method, or even which object, you’ll want to call upon
to execute it.
For Example: A button might not know which object or objects need to be notified. Rather than wiring the button to a particular
object, you will connect the button to a delegate and then resolve
that delegate to a particular method when the program executes.
A delegate is a named type that defines a particular kind of method. Just as a class definition lays out all the members for the given kind of object it defines, the delegate lays out the method signature for the kind of method it defines.
Based on this statement, a delegate is a function pointer and it defines what that function looks like.
A great example for a real world application of a delegate is the Predicate. In the example from the link, you will notice that Array.Find takes the array to search and then a predicate to handle the criteria of what to find. In this case it passes a method ProductGT10 which matches the Predicate signature.
One common use of delegates for generic Lists are via Action delegates (or its anonymous equivalent) to create a one-line foreach operation:
myList.Foreach( i => i.DoSomething());
I also find the Predicate delegate quite useful in searching or pruning a List:
myList.FindAll( i => i.Name == "Bob");
myList.RemoveAll( i => i.Name == "Bob");
I know you said no code required, but I find it easier to express its usefulness via code. :)
Binding Events to Event Handlers is usually your first introduction to delegates...You might not even know you were using them because the delegate is wrapped up in the EventHandler class.
I had the same question as you and went to this site for an answer.
Apparently, I didn't understood it better even though I skimmed through the examples on this thread.
I found a great use for delegates now that I read: http://www.c-sharpcorner.com/UploadFile/thiagu304/passdata05172006234318PM/passdata.aspx
This might seem more obvious for new users because Forms is much more complicated to pass values than ASP.NET websites with POST/GET (QueryString) ..
Basically you define a delegate which takes "TextBox text" as parameters.
// Form1
// Class Property Definition
public delegate void delPassData(TextBox text);
// Click Handler
private void btnSend_Click(object sender, System.EventArgs e)
{
Form2 frm= new Form2();
delPassData del=new delPassData(frm.funData);
del(this.textBox1);
frm.Show();
}
// SUMMARY: Define delegate, instantiate new Form2 class, assign funData() function to delegate, pass in your textBox to the delegate. Show the form.
// Form2
public void passData(TextBox txtForm1)
{
label1.Text = txtForm1.Text;
}
// SUMMARY: Simply take TextBox txtForm1 as parameters (as defined in your delegate) and assign label text to textBox's text.
I hope this enlightens some use on delegates :) ..
If you're interested in seeing how the Delegate pattern is used in real-world code, look no further than Cocoa on Mac OS X. Cocoa is Apple's preferred UI toolkit for programming under Mac OS X, and is coded in Objective C. It's designed so that each UI component is intended to be extended via delegation rather than subclassing or other means.
For more information, I recommend checking out what Apple has to say about delegates here.
I had a project which used win32 Python.
Due to various reasons, some modules used odbc.py to access the DB, and other modules - pyodbc.py.
There was a problem when a function needed to be used by both kinds of modules. It had an connection object passed to it as an argument, but then it had to know whether to use dbi.dbiDate or datetime to represent times.
This was because odbc.py expected, as values in SQL statements, dates as dbi.dbiDate whereas pyodbc.py expected datetime values.
One further complication was that the connection objects created by odbc.py and pyodbc.py did not allow one to set additional fields.
My solution was to wrap the connection objects returned by odbc.odbc(...) and pyodbc.pyodbc(...) by a delegate class, which contains the desired time representation function as the value of an extra field, and which delegates all other field requests to the original connection object.
A quick google search came up with this http://en.wikipedia.org/wiki/Delegation_pattern . Basically, anytime that you use an object that forwards it's calls to another object then you are delegating.
Related
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
Say I have a class in a programming language:
class name {
variable_name = 1;
method_name(x) {
// return something
}
}
foo = new name();
print(foo.method_name(foo.variable_name));
How correct is the following? Can we make it more correct?
If I want to talk about a specific instance of a method (foo.method_name), would I say 'the method_name-method of the object foo'? Or something else? Or does talking about the instance of a variable of method make no sense?
If I want to talk about a general object of any name, and refer to its method_name-method or variable, what would I say? Would I say 'the method_name-method/variable_name-variable of the class name?' or something else?
Thank you for your time.
Kind regards,
Marius
Talking about a specific instance of a method doesn't really make any sense as you say. Usually we talk about instances of classes - objects - and their methods. Thus one would normally talk about something like "calling method_name on foo" or simply foo dot method_name.
That's a fine way of saying it. In my experience it doesn't really matter all that much in day to day communication as the method really does the same thing anyways, just with different values in it's scope. It's what it does that really matters (e.g. accelerate() or toString()). Perhaps the most important part when talking about methods, variables etc. is communicating clearly if they happen to be static - i.e. not belonging to any given instances. In day to day speak I wouldn't make any effort to differentiate very clearly between "then we can just call accelerate on our car instance" and "the car class has a method named accelerate" (it's given that this is a non-static method) - I might however specify that "our car class has a static method to help us calculate acceleration.
In a nutshell:
Classes: (which may be instantiated to objects)
can have -
(non-static / instance) members
- public
- methods
- properties
- private
- methods
- properties
(static / class) members
- public
- methods
- properties
- private
- methods
- properties
However, methods have/can also be called messages, selectors, or behaviours (depending on the language in question, and in particular contexts.) It's occasionally considered incorrect to call them functions, however no one in their right mind should take you to task over such things. (notably the appearance of the keyword function in ECMAScript shows its level of acceptability. As a rule of thumb, the language domain would always define correctness, otherwise generally the term is fine/understandable but can lead to ambiguity.) Similarly properties are variously called, fields, attributes or variables.
An alternative name for non-static methods or properties is to call them instance methods or properties. While static methods / properties may be referred to as class methods / properties. By the way, ommitting the non-static qualifier, is usual and implicit.
As a general guideline, refer to the language under use to determine the correct terms, as they are specific to the various language cultures.
The assumption in writing this, is that there's no need to outline the scope/access differences of these class members. If that's required, I'd be happy to add a note.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How does a delegate work in objective-C?
Hello Community,
I have been trying to understand the concept of delegates in Objective-C. I tried following up the documentation, however I am looking for some really easy example to get familiarized as of how to send messages between delegates and if I want to create a custom delegate, how may I go further with that?
Hope someone could make me better understand this concept.
The basic concept of delegates is to delegate important decisions or information to some other object instance.
In most frameworks you use subclassing and override methods in order to hook into the application flow. It works but the drawbacks are many, for example:
You can not change the decision maker without a complete new subclass.
Without multiple inheritance you can only make decisions for one object (yourself).
There are four reasons why an object might want to call upon a delegate, and each of these four uses a keyword in the delegate method name to signal this. It's a naming convention only, but you should follow the pattern if you want to be a good citizen.
Ask if something should happen. For example: gestureRecognizer:shouldReceiveTouch:
Before something unavoidable is going to happen. For example: applicationWillTerminate:.
After something has occured. For example: accelerometer:didAccelerate:
And to retrieve data, this is more a data source than a delegate, but the line between the two are fuzzy. The name do not contain a defined name, but should contain the named piece of data that is requested. For example: tableView:targetIndexPathForMoveFromRowAtIndexPath:toProposedIndexPath:
As a general rule the first argument to any delegate method should be the named object instance requesting delegation.
Check here:How do I create delegates in Objective-C?
Or: http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/CocoaFundamentals/CommunicatingWithObjects/CommunicateWithObjects.html#//apple_ref/doc/uid/TP40002974-CH7-SW18
My first post here (anywhere for that matter!), re. Cocoa/Obj-C (I'm NOT up to speed on either, please be patient!). I hope I haven't missed the answer already, I did try to find it.
I'm an old-school procedural dog (haven't done any programming since the mid 80's, so I probably just can't even learn new tricks), but OOP has my head spinning! My question is:
is there any means at all to
"discover/find/identify" an instance
of an object of a known class, given
that some OTHER unknown process
instantiated it?
eg. somthing that would accomplish this scenario:
(id) anObj = [someTarget getMostRecentInstanceOf:[aKnownClass class]];
for that matter, "getAnyInstance" or "getAllInstances" might do the trick too.
Background: I'm trying to write a plugin for a commercial application, so much of the heavy lifting is being done by the app, behind the scenes.
I have the SDK & header files, I know what class the object is, and what method I need to call (it has only instance methods), I just can't identify the object for targetting.
I've spent untold hours and days going over Apples documentation, tutorials and lots of example/sample code on the web (including here at Stack Overflow), and come up empty. Seems that everything requires a known target object to work, and I just don't have one.
Since I may not be expressing my problem as clearly as needed, I've put up a web page, with diagram & working sample pages to illustrate:
http://www.nulltime.com/svtest/index.html
Any help or guidance will be appreciated! Thanks.
I have the SDK & header files, I know what class the object is, and what method I need to call (it has only instance methods), I just can't identify the object for targetting.
If this is a publicly declared class with publicly declared instance methods (i.e., you have the header for the class and it has instance methods in it), there is probably a way in this application's API to get an instance of the class. Either you are meant to create one yourself, or the application has one (or more) and provides a way to get it (or them). Look at both the header for the class in question and the other headers.
I initially said “there must be a way…”, but I changed it, because there is an alternative reason why the header would have instance methods: The application developer does not intend those instance methods for plug-in use (and didn't mark them appropriately), or did not mean to include that header in the application/SDK (they included it by accident). You may want to ask the application developer for guidance.
If it is not a publicly declared class or its instance methods are not publicly declared, then the application does not support you working with instances of the class. Doing so is a breach of the API contract—not a legal contract, but the expectations that the application has of its plug-ins. If you breach the API contract, you will cause unexpected behavior, either now (not necessarily on your own machine/in your own tests) or in the future.
If the class's public declaration contains only class methods, then perhaps what you're after is not an instance at all—you're supposed to send those messages to the class itself.
This is not possible without having you register each instance in a dictionary as it is created. I.e., override some common factory method at a higher level which does this bookkeeping work. This will fall down when you use delegates that you may not control though, keep that in mind.
I do question the need to even do this at all, but I don't know your problem as well as I perhaps would need to, to recommend a different, more apt way of accomplishing the actual task at hand.
Just as a corollary to the above; I did look at the runtime to see if there was anything that I actually forgot about, but there is not. So my above statement with regards to you requiring to do that bookkeeping yourself, still holds I'm afraid.
Edit:
Based on your diagram (my apologies, just noticed the link after I posted this answer); I would suggest that if you control the classes that are being returned to you, just add a property to them. I.e., add a "name" property that you can set and keep unique. Then just pass the message to each instance, checking whether or not that object is the one you want. It's not particularly clever or anything like that, but it should work for your purposes.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
If I'm writing a class, when do I make a method private, versus protected? In other words, how I can know in advance that a client programmer would never ever need to override a method? In a case where it's something that has external considerations, like a database connection?
public and protected methods form the 'interface' to your object, public for developers using (delegating to) your class, and protected for developers wishing to extend the functionality of your object by subclassing it.
Note that it's not necessary to provide protected methods, even if your class will be subclassed.
Both public and protected interfaces need careful thought, especially if this is an API to be used by developers outside your control, since changes to the interface can break programs that make assumptions about how the existing interface works.
private methods are purely for the the author of the object, and may be refactored, changed and deleted at will.
I would go for private by default, and if you find you need to expose more methods, have a careful think about how they will be used - especially if they are virtual–what happens if they are replaced completely with an arbitrary alternative function by another developer–will your class still work? Then design some appropriate protected which are useful for developers subclassing your object (if necessary), rather than exposing existing functions.
In other words, how I can know in
advance that a client programmer would
never ever need to override a method?
You cannot. And you don't need to. It is not your job to anticipate IF a developer might want to override a method, let alone how. Just assume he wants to and enable him to do so without having to touch your code. And for this reason, do not declare methods private if you don't have to.
If a developer feels he needs to adjust some functionality of your classes, he can pick from a number of structural and behavioral patterns to do so, e.g. Decorators, Adapters or by subclassing. Using these patterns is good, because it encapsulates the changes into the developer's own class and leaves your own code untouched. By declaring methods private, you make sure the developer will monkey with your class. And that is bad.
A perfect example is Zend Framework's DB adapter. They discourage the use of persistent connections and their adapters provide no mean to this end. But what if you'd want to have this nonetheless and the adapter method was marked private (it isn't, but what if)? Since there is no way to overwrite the method, you would (yes, you would) change the adapter code right within it's class or you'd copy & paste the code into your own adapter class, effectively duplicating 99% of the class just to change a single function call. Whenever there is an update to this adapter, you either would lose your changes or you wouldn't get it (in case you c&p'd). Had it been marked protected (as it is), you could just have written a pConnectAdapter subclass.
Moreover, when subclassing, you are effectively saying subClass is a parentClass. Thus, you can expect the derived class to have the same functionality as the parentClass. If there is functionality in the parentClass that should not be available in the subClass, then disabling it conceptually belongs to the subClass.
This is why I find it much better practise to default all methods and properties to protected visibility and only mark those methods (not properties though) supposed to allow interaction with my class from another class or script as public, but only a few things private. This way, I give the developer the choice of using my class as I intended it to be used and the option to tweak it. And if he breaks something in the process, it is very likely his fault then, not mine.
Update: since I wrote this four years ago I have come to the conclusion that defaulting things to protected instead of private often leads to suboptimal subclasses. This is because people will start to use whatever you provided as protected. This in turn means you have to consider all these methods as API and may not change them at will. As such, it's better to carefully consider what extensions points you want to provide and keep the everything else private. See http://fabien.potencier.org/article/47/pragmatism-over-theory-protected-vs-private for a similar view.
I typically will start at the lowest level. If you're unsure make it private. Then as needed you can make things protected or public.
The idea being it is not a breaking change to go from private to protected but it could be a breaking change to go the other way.
Don't think of the private/protected/public thing as if a programmer would ever "need" a method. Think of it as if you want to allow them access to it.
If you think they should be allowed to change the DB Connection String then make it public.
I always make all methods private as default. This is to keep the interface clean and easy to maintain.
It is much harder to change or hide an already visible method than to make a private method more visible. At least if you need to be compatible with existing client code.
In other words, how I can know in
advance that a client programmer would
never ever need to override a method?
If you don't know assume they will need to. If that's fine by you (ie, if you think they should be able to) then use protected; otherwise use private.
Private members are used to encapsulate the inner workings of your class. Use them to hold data that only you want to be able to access. For example, let's say you have a field called _name and a getter/setter named GetName()/SetName(name). Maybe you want to do some syntax checking on name before you allow the SetName to succeed, else you throw an exception. By making _name private, you ensure that this syntax checking will occur before any changes to name can occur (unless you yourself change _name in your own class, in your own code). By making it protected, you're saying to any potential future inheritor of your class, "go ahead and monkey with my field."
In general, protected is used sparingly and only in specialized cases. For example, you might have a protected constructor that exposes some additional construction functionality to child classes.
I typically just make everything private and refactor when I need to call it from a base class.
Except when I feel lazy and do everything protected that isn't definitely dangerous.
I had a bunch of objects which were responsible for their own construction (get properties from network message, then build). By construction I mean setting frame sizes, colours, that sort of thing, not literal object construction.
The code got really bloated and messy when I started adding conditions to control the building algorithm, so I decided to separate the algorithm to into a "Builder" class, which essentially gets the properties of the object, works out what needs to be done and then applies the changes to the object.
The advantage to having the builder algorithm separate is that I can wrap/decorate it, or override it completely. The object itself doesn't need to worry about how it is built, it just creates a builder and 'decorates' the builder with extra the functionality that it needs to get the job done.
I am quite happy with this approach except for one thing... Because my Builder does not inherit from the object itself (object is large and I want run-time customisation), I have to expose a lot of internal properties of the object.
It's like employing a builder to rebuild your house. He isn't a house himself but he needs access to the internal details, he can't do anything by looking through the windows. I don't want to open my house up to everyone, just the builder.
I know objects are supposed to look after themselves, and in an ideal world my object (house) would build itself, but I am refactoring the build portion of this object only, and I need a way to apply building algorithms dynamically, and I hate opening up my objects with getters and setters just for the sake of the Builder.
I should mention I'm working in Obj-C++ so lack friend classes or internal classes. If the explanation was too abstract I'd be happy to clarify with something a little more concrete. Mostly just looking for ideas or advice about what to do in this kind of situation.
Cheers folks,
Sam
EDIT: is it a good approach to declare a
interface House(StuffTheBuilderNeedsAccessTo)
category inside Builder.h ? That way I suppose I could declare the properties the builder needs and put synthesizers inside House.mm. Nobody would have access to the properties unless they included the Builder header....
That's all I can think of!
I would suggest using Factory pattern to build the object.
You can search for "Factory" on SO and you'll a get a no. of questions related to it.
Also see the Builder pattern.
You might want to consider using a delegate. Add a delegate method (and a protocol for the supported methods) to your class. The objects of the Builder class can be used as delegates.
The delegate can implement methods like calculateFrameSize (which returns a frame size) etc. The returned value of the delegate can be stored as an ivar. This way the implementation details of your class remain hidden. You are just outsourcing part the logic.
There is in fact a design pattern called, suitable enough, Builder which does tries to solve the problem with creating different configurations for a certain class. Check that out. Maybe it can give you some ideas?
But the underlying problem is still there; the builder needs to have access to the properties of the object it is building.
I don't know Obj-C++, so I don't know if this is possible, but this sounds like a problem for Categories. Expose only the necessary methods to your house in the declaration of the house itself, create a category that contains all the private methods you want to keep hidden.
What about the other way around, using multiple inheritance, so your class is also a Builder? That would mean that the bulk of the algorithms could be in the base class, and be extended to fit the neads of you specific House. It is not very beautiful, but it should let you abstract most of the functionality.