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.
Related
I'm writing a small text-editor like utility for our in-house staff to use to modify a bunch of company specific files. I want design this in such a way we minimize leaky handlers and would like to ask for opinions.
There are different actions done based on the type of file loaded. I have each in a separate class, I instantiate and pass through the active tab's instance of the richtextbox. The implementation then subscribes to the following:
SelectionChanged
TextChanged
Then depending on the type of file, they'll deal with their specific things. I've noticed that some of our internal devs don't unsubscribe from events and things leak. The control hangs around (It's not a MDI app, a panel + tab control + many richtextboxes).
What's a good way of delegating the resposibility of susbcribing to events to these implementations?
Should I write a proxy (which they all subscribe to) and my Richtextbox basically gets that proxy to call it for me when something happens - and I subscribe/unsubscribe as necessary when the tab changes? Are there any established patterns - maybe a Gang of Four? that may be what I should use?
Yes. just create proxy class based on type call respective class methods
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)
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.
Should a class implement an interface always in order to enforce a sort of 'contract' on the class?
When shouldn't a class implement an interface?
Edit: Meaning, when is it worthwhile to have a class implement an interface? Why not have a class just have public members and private members with various accessor/setter functions?
(Note: Not talking about COM)
No, an interface is not always required - the public members of the class already form a contract.
An interface is useful when you want to be able to exchange one class for another when both offer similar functionality. Using an interface allows you to decouple the contract from the specific implementation. However this decoupling is not always necessary or useful.
Many classes in the .NET framework do not implement any interfaces.
Only use an interface when it is needed.
That is: when you want to have different implementations for a certain abstraction.
When, in the future, it seems that it would be better to have an interface for a specific class (because for instance, you want to have another implementation for the same concept), then you can always create the interface from your existing class. (ExtractInterface refactoring)
Interfaces become more necessary when you are doing unit testing, but it all depends on the context of your development. As Mark said, an interface IS the contract and implementing it forces you to adhere to the "rules" of that contract.
If you are trying to enforce the implementation of certain methods, then using an interface is perfect for that.
There are some nice examples here:
http://msdn.microsoft.com/en-us/library/ms173156.aspx
http://msdn.microsoft.com/en-us/library/87d83y5b(VS.80).aspx
An interface, here meaning the code construct and not the design abstraction, supports a basic principle of code design called "loose coupling". There are some more derived principles that tell you HOW code should be loosely coupled, but in the main, loose coupling helps allow changes to code to affect as small an area of the codebase as possible.
Consider, for example, a calculation of some arbitrary complexity. This calculation is used by 6 different classes, and so to avoid duplicating code, the calculation is encapsulated in its own class, Calculator. The 6 classes each contain a reference to a Calculator. Now, say that your customer comes to you and says that in one usage of Calculator, if certain conditions are met, a different calculation should be used instead. You might be tempted to simply put these two rules (usage rule and business rule) and the new calculation algorithm into the Calculator class, but if you do so, then two things will happen; first, you make Calculator aware of some implementation details (how it's used) outside of its scope, that it doesn't need to know and that can change again later. Second, the other 5 classes that use Calculator, which were working just fine as-is, will have to be recompiled since they reference the changed class, and will have to be tested to ensure you didn't break their functionality by changing the one for the 6th class.
The "proper" solution to this is an interface. By defining an interface ICalculator, that exposes the method(s) called by the other classes, you break the concrete dependence of the 6 classes on the specific class Calculator. Now, each of the 6 classes can have a reference to an ICalculator. On 5 of these classes, you provide the same Calculator class they've always had and work just fine with. On the 6th, you provide a special calculator that knows the additional rules. If you had done this from the beginning, you wouldn't have had to touch the other 5 classes to make the change to the 6th.
The basic point is, classes should not have to know the exact nature of other objects they depend on; they should instead only have to know what that object will do for them. By abstracting what the object DOES from what the object IS, multiple objects can do similar things, and the classes that require those things don't have to know the difference.
Loose coupling, along with "high cohesion" (objects should usually be specialists that know how to do a small, very highly-related set of tasks), is the foundation for most of the software design patterns you'll see as you progress into software development theory.
In contrast to a couple of answers, there are design methodologies (e.g. SOLID) that state that you should ALWAYS set up dependencies as abstractions, like an abstract base class or an interface, and NEVER have one class depend upon another concrete class. The logic here is that in commercial software development, the initial set of requirements for an application is very small, but it is a safe assumption, if not a guarantee, that the set of requirements will grow and change. When that happens, the software must grow. Creating even smaller applications according to strict design principles allows extending the software without causing the problems that are a natural consequence of bad design (large classes with lots of code, changes to one class affecting others in unpredictable ways, etc). However, the art of software development, and the time and money constraints of same, are such that you can (and have to) be smart and say "from what I know of the way this system will grow, this is an area that needs to be well-designed to allow adaptation, while this other section will almost surely never change". If those assumptions change, you can go back and refactor areas of code you designed very simply to be more robust before you extend that area. But, you have to be willing and able to go back and change the code after it's first implemented.
This once again comes down to what he means by "interface". There is some ambiguity between the term interface and Interface. When the term Interface is used it means an object that has no method declarations. When the term interface is used it means that you utilize a pre-defined set of functions (whether they be implemented or not) and override them with your logic if necessary. An example would be:
abstract class Animal
class Dog extends Animal
In this instance Animal == interface (or contract) for Dog
interface Measurable
class Cup implements Measurable
In this instance Measurable == Interface for Cup
A class should not implement interface/s unless you want to tell other parts of your program - "This class can do these things (but not specify how exactly it does what it does)".
When would you want to do that?
For example, say you have a game in which you have animals.. And say whenever an animal sees a human it makes it's sound (be it a bark, a roar etc.).
If all animals will implement interface IMakeSound in which there is a method called MakeSound, you will not have to care about what kind of animal it is that should make that sound.. All you'll have to do is to use the "IMakeSound" part of the animal, and call it's method.
I should add that when one reads in a class declaration that it implements a certain interface, it tells him a lot about that class, which is another benefit.
You may not always want an interface. Consider you can accomplish similar tasks with a delegate. In Java I used the Runnable Interface for multithreaded applications. Now that I program in .NET I rely a lot on delegates to accomplish my mulithreaded applications. This article helps explains the need for an Delegate vs an Interface.
When to Use Delegates Instead of Interfaces (C# Programming Guide)
Delegates provide a little more flexibility as in Java I found that any task that I accomplished in C with a function pointer now required incasulation with an an Interface.
Although, there are lots of circumstances for an Interface. Consider IEnumerable, it is designed to allow you to iterate over various collection without needing to understand how the underlying code works. Interfaces are great for when you need need to exchange one class for another but require a similar Interface. ICollection and IList provide a set of similar functionality to accomplish an operation on a collection without worrying about the specifics.
If you would like to better understand Interfaces I suggest you read "Head First Design Patterns".
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.