Why does MSDN recommend including object sender in delegate declarations? - c#

I was reading this page and I noticed how it said this is standard guidelines:
The .NET Framework guidelines indicate that the delegate type used for an event should take two parameters, an "object source" parameter indicating the source of the event, and an "e" parameter that encapsulates any additional information about the event.
I can understand how having an object sender could be useful in some circumstances, but I could see the exact opposite in others. For example,
What if a class handling the event should not have any knowledge about who fired it? Coupling, cohesion, and all of that.
In my case, I already have a reference to the object as a member variable. That is how I subscribe to the event. There will only ever be one instance of it so there's no reason to cast the sender object rather than just using the member variable.
In my program the sender object should not be known at all to the clients. It's hard to explain what I am doing but basically I have a class with an internal constructor within a library that is used by two other classes also within that library. My client classes are subscribing to events from those two classes but the events are originally invoked from this internal class that clients should not have any knowledge of.
It is confusing to clients of the event handler. Libraries should be simple to understand and in my case, there is no reason to ever use the sender variable. None. Then why include it?
That being said, why does Microsoft indicate that event handlers should follow these guidelines? Isn't it not always the best choice?
EDIT: Thanks for the replies everyone. I've decided to go with the majority and use EventHandler<T> for all my events in this library.

You are fighting against the wind, the .NET framework has certain design, rules and guidelines and when using it, if you want to use it correctly, you are supposed to follow those directions.
if you use raw delegates you have all the freedom you want but as stated above if you are declaring a delegate type for an event you should include sender object and EventArgs object as well (base or derived class).
if you break those rules, as I said a moment ago in my answer to your other question: Should I use EventArgs or a simple data type?, you could potentially end up in a situation where your code breaks.
Simplyfying at the maximum, when the framework invokes an OnClick event on a control, the .NET Framework does pass the sender and an EventArgs instance... if the event would not comply, something could break.
if you want full freedom then use simple delegates but not events.

First of all, it's important to note that a guideline is not a law.
All hell (or the programmer equivalent) will not break lose if you don't follow the guidelines.
As such, feel free to change the signature of your events appropriately.
However, it is just as important to know why these guidelines were added to begin with, and one big part of the answer(s) to that question is versioning.
By having the following two parts, and only those two parts:
The source of the event, typed as "generic" as possible (note, event signatures were designed long before proper generics were introduced into the system, so object is as generic as can be from back then)
An object inheriting from EventArgs
then you are designing code that is more resilient to changes.
First of all, since you're not "allowed" to add or remove parameters, all future versions of your event will still have only sender and e.
Secondly, there's a second part to the guideline regarding the e parameter. If you in a new version of your class library decides to change the signature of an event handler by changing the type of the e parameter, you're supposed to make it more specific by descending from your current type, and passing the descendant instead.
The reason for this is that existing code that already handles your current (old) type will still work.
So the entire reasoning behind the guideline is to:
Stay consistent (as others have mentioned)
Design for the future (by making sure code written against version X of your class still works when you release version X+1, without manual changes to that code)
Now, if any of this is not a concern for your case, feel free to not follow the guideline.
In fact, you can make an event out of an Action and it'll work just fine.

Why? People always ask this. In this end, this is just about a
pattern. By having event arguments packaged in a class you get better
versioning semantics. By having a common pattern (sender, e) it is
easily learned as the signature for all events. I think back to how
bad it was with Win32—when data was in WPARAM versus LPARAM, and
so on. The pattern becomes noise and developers just assume that event
handlers have scope to the sender and arguments of the event.
-Chris Anderson, in Framework Design Guidelines: Conventions, Idioms, and Patterns for Reusable .NET Libraries
If you're a .NET developer and you haven't read that book, you're missing out. It gives you a window ;) into the minds of the Microsoft .NET Framework designers, and a lot of best practices (including the reasoning behind them).
(Plus, you can run FxCop to verify that these practices are being followed.)

I think the reason for the pattern is to enforce some consistency. The sender parameter allows re-use of a single handler for multiple publishers (buttons, tables).
To address your points:
1) simply don't use it. That is common and doesn't really hurt any good practice.
2) that's OK, again ignore the sender
3) is in total contradiction of what you said under 2) ...
And for the rest it is the same as 1). You could even consider passing null as sender.
4) "then why include it" - there are other use cases that do require the sender.
But do note this is just a guideline for libraries confirming to the BCL.
Your case sounds more like a specific application (not a library) so feel free to use any parameter scheme you like. The compiler won't complain.

Guidelines such as this allow for predictability on the part of the consumer of the event. It also allows for handling of additional scenarios you may never have considered when you created the event, especially if your library is used by third party developers.
It allows the method handling the event to always have the correct object instance at hand as well as basic information regarding why the event was fired.

It's just good practice, but you'll be fine as long as you don't need to know about the object that fired the event or any other info related to the object. I for one always include it since you never know when you'll need it.
My suggestion is to stick with it, it does not hurt at all.

There would have been nothing wrong, semantically, with having event handlers that are interested in where events came from use a derivative of EventArgs which included such a field. Indeed, there are many situations where that would be cleaner than passing Sender as a separate parameter (e.g. if a keyboard-shortcut processor needs to fire a Click handler for a button, the event shouldn't really be considered to have been raised by the button, but rather raised on the button's behalf). Unfortunately, incorporating that information within an EventArgs-derived type would make it necessary to create a new instance of an EventArgs-derived type every time an event is raised, even if it could otherwise use EventArgs.Empty. Using a separate parameter to pass the information eliminates the need to have every event create a new object instance in that common case.
Although it might have been possible to have handlers that care about where an event came from use a parameter for that, and have those that don't care about it omit the parameter, that would have required that any helper methods and classes which assist with handling event subscriptions would need to have versions for events which did or did not include the parameter. Having all events take two parameters, one of which is of type Object and one of which is of a type derived from EventArgs makes it possible for one helper method or class to be capable of handling all events.

Related

How do I get an instance of IVsExpansionClient in VSPackage?

Documentation for extending Visual Studio is virtually nonexistent, and I managed to assemble a few lines of functioning code hacked together from a dozen or more obscure sources around the interwebs before crashing into a brick wall.
All I need to do is subscribe to an event that is fired after a snippet is inserted. Sounds easy enough, or so I thought. Almost immediately into my research I stumbled upon the following morsel:
IVsExpansionClient.OnAfterInsertion
That describes perfectly my intention, so this MUST be the answer! After looking around my SDK assemblies for longer than I would like to admit, I finally ended up yanking the assembly (Microsoft.VisualStudio.TextManager.Interop.8.0.dll) out of my GAC so that I could reference it explicitly in my solution.
Now that I have access to the interface, I just need to figure out how to get an instance of it.
IVsExpansionManager
Ah HA! That MUST somehow provide me with a mechanism for obtaining an instance of IVsExpansionClient, right? Well, not exactly. At least not in a way that I can see. I have stitched together the following code:
IVsExpansionManager expansionManager = null; IVsTextManager2
textManager =
(IVsTextManager2)Package.GetGlobalService(typeof(SVsTextManager)); int
manager = textManager.GetExpansionManager(out expansionManager);
Which gives me a IVsExpansionManager COM object, but that is about as far as I can get.
I have taken notice of another potential provider:
IVsExpansionEvents
I thought perhaps like solution events, document events, window events or text events, I might be able to invoke DTE to hook these events, but they appear to be absent.
There are methods that accept IVsExpansionClient as a parameter such as:
IVsExpansion.InsertNamedExpansion
So there simply must be a way to fetch an instance of this object, right? I suppose it's possible to create my own class that implements the IVsExpansionClient interface, but I wouldn't know where to begin with implementing the interface members, and I still wouldn't know how to instantiate it in a meaningful way within my package.
I am grateful to anyone who can point me in a different direction, or provide a working sample that I can adapt for my needs. Thanks for taking the time to read through this, I appreciate your time.
EDIT: I want to receive a notification that a snippet has been inserted into the active document window. Ideally, I would like the snippet itself to be included in the delegate event args, as I have some processing to do on the inserted snippet...and it would be cumbersome to process the entire document, or try to identify the recently inserted snippet without context.
Maybe you want to explain what you actually want to achieve. The documentation of the IVsExpansionClient interface states:
Notes to implementers
This interface is implemented by a VSPackage that supports insertion of code snippets.
I don´t see why one would like to consume an instance of it, because it´s an interface allowing the package to receive notifications/callbacks, if something related to code-snippets is going to happen (it provides nohting else than callback functions).
It states furthermore...
Notes to Callers
This interface is instantiated and passed to the InvokeInsertionUI method in the IVsExpansionManager interface. This interface is also instantiated and passed to the methods in the IVsExpansion interface.

How can the c# .net event construct best be represented in a UML class diagram?

I am designing an entity/component system where the problem of intra-entity communication is addressed by an event message system. components are broken into two parts, one in the entity and a sort of "entity proxy" in a subsystem, kept in sync through an observer type system. I am attempting an implementation with events and delegates.
I am trying to model the structure of my application's event/messaging system and I am having trouble with the delegates. The way it is now is a diagram(attached) showing the delegate, eventArgs, and entities in the system, however the nature of their relationships is only being represented as generic associations. I also have a second diagram showing the system's interfaces. I need to show the events that are raised in these objects, as this where most of the complexity in the system is.
I know I need dynamic collaboration and timing diagrams as well, but I am trying to figure out what kind and how many different event support classes I need as well as what the inheritance structure will look like. I want to give myself a choice of message types that I know will work together. I figure then I can choose an EventArgs derivative and a delegate type from these pre-defined types to reuse at dynamic diagramming and component building time.
The main thing I can't figure out is whether to model the event as an attribute or operation. I have been trying to use an association class for the delegate and an OnSomeEvent() type operation with an event stereotype. I don't like this because an event is not an operation. I have protected methods in the code with this On****() naming convention already. The delegate signature, multicast behavior and the observer pattern are not really captured by this approach.
What method are others using to express these complex and tightly coupled classes? The point of the diagrams for me is to both document and more completely understand the interfaces in the system. At this stage in my process I am hoping to freeze the Interfaces and move on to Implementing the components themselves.
I wouldn't include the signaling character in a static class diagram because signaling (it's what events are for) is a dynamic behavior. I would take the event delegates as they are (i.e. with their signatures) and include them as ordinary operations of a class. I think this would match the idea that an object is capable of sending an event quite appropirately and it specifies the kind if the event.
Which signals are going where and who is subscribed to whom should be modeled in a dynamic diagram.
EDIT:
Have you considered adding stereotypes like << event >> or << signal >> to classifying attributes on your class ?
Events and delegates are considered as simple methods when looking to your model from a static point of view. Some tools extend the specification by offering either stereotypes or markers to show your methods as being events/delegates and differentiate them from normal methods.
In the other hand, your events and delegates parameters should be modeled as classes. Events make sense when the time factor is added to your model, in which case you can make use of the UML event and trigger elements (synchronous and asynchronous messaging is supported).
On a side note, UML is a semi formal language, that makes things like event sequencing between two uncorrelated state machines for example not guaranteed although this can be defined by using UML profiles such as MARTE (It has been a long time that I did not have a look at it so things might have changed)

Events versus overridable methods?

Can anyone provide me with general guidelines as to when I should use overridable methods such as "OnMyEvent", and when I should use events such as "MyEvent" in C#?
Are there any general design principles that can define what to use?
The two features are vaguely similar (both are designed to do some form of dynamic dispatch), but are not directly comparable.
Events are to notify other objects that an object has come to some sort of state transition. It is a language feature that embodies the Observer Design Pattern. This can be useful in a lot of cases, but is not always useful or desirable. It is a tool to get specific jobs done.
Virtual functions are used to create Object Oriented Polymorphism. They are a basic building block of nearly every Design Pattern, and a lot of object oriented design.
To try to compare them, I'll assume you're trying to implement some form of observer pattern with either feature. With that restriction in place, there is still no simple rule you can fall back on to decide which you should use. Instead, you'll have to ask yourself questions like:
Who caused it: Will the action that triggers your state transition occur internally, or will it be externally triggered?
If it is triggered internally, you could use an event or a virtual method. If it is triggered externally, you must use a virtual method.
Who cares about it: Should the class that defines the state handle the consequences of the state transition, or should an external class handle it?
If the class that owns the state should handle the transition, then it should be a virtual method. If a separate class should react to the transition, it should be an event.
How many handlers do I need: Do you always need one handler to react to the state transition, or do you need many?
If you need one, then either using a virtual method or an event could be acceptable. If you need many, then it will be much easier to use an event.
Do I know which handler I want at compile time: Do I bind to a single well-known handler, or do I bind to unknown handlers, possibly changing over time?
If you need your handlers to change, you must use events. If you only have a single handler that is known at compile time, you could use a virtual method.
How coupled should my code be: Does your handler code belong to a derived class of your original type, or does it belong somewhere else?
If it belongs in a derived class, you need a virtual method. If it belongs elsewhere, then you need an event.
As you can see, the answers will greatly depend on your specific problem domain and object architecture. Good design isn't something that magically falls into your lap via some check list. You have to think about it, a lot :)
Edit:
It may not be directly applicable to C# events, but it may be useful to take example from existing work. Here is a brief article I just found (while answering a different question) on design alternatives in Java for eventing patterns: http://csis.pace.edu/~bergin/patterns/event.html
Events are great for when you have a "has a" while overrides are a lot better for situations where you have a "is a" relationship
For an example, if you have a base class animal, it is likely the case that each animal will have its own way of moving. however every animal is in some way going to want to move.
Now think of a class person that may 'have' a pet animal. in this case the Person might react to the animal moving but it wouldn't actually handle the animal moving.

Design Perspective: Static Methods vs. Classes

Although this is a fairly common problem, I am struggling with what the best way to approach it (if it needs approached at all in this case).
I have inherited a website (ASP.NET, C#) part of which contains a class full of static methods (it's a very large class, honestly). One method in particular is for sending e-mails. It has every possible parameter I can think of and it works well enough. However, the internals of that particular method are rather cumbersome to manage and understand due to the fact that everything is shoved inside - particularly when most of the parameters aren't used. In addition, it is somewhat difficult to handle errors, again, due to all the parameters for this one method.
Would it make more sense to actually have an EMail class which is instantiated when you want to send an e-mail? This just "feels" more right to me, though I can't full explain why. What are your thoughts on the way to go in this particular case? How about in general?
Thanks.
What you're describing sounds like an example of the aphorism, "You can write FORTRAN in any language."
A massive class full of static methods is often (not always) a sign that somebody just didn't "get" OOP, was stuck in a procedural-programming mindset and was trying to twist the language to do what he wanted.
As a rule of thumb: If any method, static or instance, takes more than about 5 parameters, it's often a sign that the method is trying to do too many things at once, and is a good candidate for refactoring into one or more classes.
Also, if the static methods are not really related, then they should at least be split up into classes that implement related functionality.
I'm actually wondering why you'd have a "send e-mail" method at all, given that the System.Net.Mail namespace handles just about every case, and is configurable via the app.config/web.config file, so you don't need to pass it a server name or port. Is this perchance a "notification" method - something that individual pages are supposed to call out to in order to send one of several "standard" messages based on templates with various values filled in, and certain headers/footers automatically added? If so, there are a number of designs for this type of interaction that are much easier to work with than what you seem to have inherited. (i.e. MailDefinition)
Update: Now having seen your comment that this is being used for exception handling, I think that the most appropriate solution is an actual exception handler. There are a ton of resources on this. For ASP.NET WebForms, I actually took the one Jeff Atwood wrote years ago, ported it to C# and made a few changes (like ignoring 404 errors). There are a number of good links in this previous question.
My preference these days is just to treat exception handling (and subsequent e-mailing of exception reports) as a subset of logging. log4net has an SmtpAppender that's quite capable, and you can configure it to only be used for "fatal" errors (i.e. unhandled exceptions - in your handler, you just make a LogFatal call).
The important thing, which you'll no doubt pick up from the SO link above and any referenced links, is that there are actually two anti-patterns here - the "miscellaneous" static class, and catching exceptions that you don't know how to handle. This is a poor practice in .NET - in most cases you should only catch application-specific exceptions that you can recover from, and let all other exceptions bubble up, installing a global exception handler if necessary.
Here are the Microsoft guidelines for when to use static types, generally.
Some things I would add, personally:
You must use static types to write extension methods.
Static types can make unit testing hard as they are difficult/impossible to mock.
Static types enforce immutability and referentially transparent functions, which can be a good design. So use them for things which are designed to be immutable and have no external dependencies. E.g., System.Math.
Some argue (e.g.) that the Singleton pattern is a bad idea. In any event, it would be wrong to think of static types as Singletons; they're much more broad than that.
This particular case has side-effects (sending e-mails) and doesn't appear to require extension methods. So it doesn't fit into what I would see as the useful case for static types. On the other hand, using an object would allow mocking the e-mail, which would be helpful for a unit test. So I think you're correct to say that a static type is inappropriate here.
Oh my gosh yes.
It sounds like its an old Classic ASP app that was ported.
It violates the single responsibility principle. If you can refactor that class. Use overloading for that function.
That is an example of the Utils anti-pattern.
It is always a good idea to separate those methods according on their responsibility. Creating an Email class is definitely a Good Idea™. It will give you a much nicer interface to use, and it allows you to mock out the Email in tests.
See The Little Manual of API Design, which describes the benefits of classes having minimal constructors and lots of getters/setters over the alternative of using constructor/methods having many parameters.
Since most of the parameters of the methods you mention are not used, a better approach is to use simple constructors that assume reasonable default settings for the internal variables. Having setter methods allows you to then set the few parameters (and only those parameters) that require non-default values.

Java "events" - nothing more than Interfaces. Why pretend it is Events when it is just a normal Interface and classes that implements that interface?

I am mainly developing in .NET C# and I love the Events in C#.
Im now doing som Android stuff and thus must deal with Java. When porting some code from C# to Java I ran into the problem of Events; Java does not have anything that corresponds to C# Events.
So, when reading up on how Java handles "events", the only thing I can conclude is that it doesnt. There is no such thing as "events" in Java. Instead they use normal Interfaces and classes that implement those interfaces.
In Java:
First, you have to first create the Interface
Then, all classes that want to listen to the "event" has to implement that interface.
Then, the class that fires the "event" has to keep a list of all listeners (Array of some sort)
Then, the class that fires the "event" has to have a method so that listeners can add themselves to the Array
And when the firing class decides to "fire the event", it has to iterate through the Array of the listeners, calling the methods.
That is just plain Interface-usage, not Events in my world.
Am I wrong?
No one is "pretending". The Java concepts were implemented long before C# was designed. The events in C# are really the same thing internally; though they are easier for the programmer to use. That is, the C# event variable maintains a list of event subscribing methods and the subscribers can add and remove method references from that list. The event provides a way for the owning class to trigger the event.
What is your definition of "event" anyway? This is a design pattern intended to decouple one system of classes from another. The other classes can subscribe to receive notification of an event in either case (C# or Java), it's just the implementation of that subscription and message trigger that differ.
In C# you must define the event method signature (a delegate). This is what interfaces do.
What C# does add that Java doesn't have is that you can pass references to methods (delegate, though I now understand this may become available in Java 7, at least at the JVM level). Since this does not exist in Java, there must be another means to provide event (an observer design pattern) receiver which must be an object and the best means to define this is through an interface -- yes you could use an abstract class, but that would severely limit the recipient types.
It is indeed just normal interfaces albeit with a naming and implementation "convention" - XXXListener and anonymous inner classes. I think this is fine and works well enough - the core language does not have to be bloated (maybe a little too harsh word for this - I don't want to start a flame war) by the notion of "events".
AFAIK Android draws inspiration for this pattern from Swing.
Note how most languages don't have a language construct for patterns like Singleton, Observer, ... it is not necessary if the patterns can be implemented easily - if it is a little more complicated it can be implemented by libraries, toolkits or frameworks.
JavaBeans is all about "convention over configuration". :-P Events are made by simply having methods that are named addXXXListener, removeXXXListener, and getXXXListeners, where the types involved derive from a listener interface.
In the same way, a property is made by simply having methods named getXXX and setXXX (either can be omitted for read-only or write-only properties).
How does a program locate events and properties? By using java.beans.Introspector, which puts those naming conventions into good use.
Sometimes, simplest is best. :-D
For clarification, the way the Android SDK implements and exposes the concept of an Event is distinct from the Java language. Different toolkits (i.e Swing, SWT) have their own way of doing things.
In Java, events represent all activity that goes on between the user and the application. Java's Abstract Windowing Toolkit (AWT) communicates these actions to the programs using events.

Categories

Resources