Effective C # Principle 35: Select overriding functions instead of using event handles

Source: Internet
Author: User
Tags error handling

A lot. NET class provides two different ways to control the events of some systems. That is, either add an event handle, or override the base class's virtual function. Why do you offer two ways to do the same thing? In fact, it's very simple, because of the different circumstances to invoke the method. Inside a derived class, you should always rewrite the virtual function. For your users, you should limit them to using only handles to respond to events on unrelated objects.

For example you have a very good Windows application that responds to events under the mouse point. In your form class, you can choose to rewrite the onmousedown () method:

public class MyForm : Form
{
 // Other code elided.
 protected override void OnMouseDown(
   MouseEventArgs e )
 {
  try {
   HandleMouseDown( e );
  } catch ( Exception e1 )
  {
   // add specific error handling here.
  }
  // *almost always* call base class to let
  // other event handlers process message.
  // Users of your class expect it.
   base.OnMouseDown( e );
 }
}

Or you can add an event handle:

public class MyForm : Form
{
 // Other code elided.
 public MyForm( )
 {
   this.MouseDown += new
   MouseEventHandler( this.MouseDownHandler );
 }
 private void MouseDownHandler( object sender,
  MouseEventArgs e )
  {
  try {
   HandleMouseDown( e );
  } catch ( Exception e1 )
  {
   // add specific error handling here.
  }
 }
}

Some of the previous methods are better, and if a handle throws an exception on the chain of events, the other handles are not invoked again (see Principle 21). Some "sick" code blocks the handle on the system call event. By overriding a protected virtual function, your control handle executes first. A virtual function on a base class has the responsibility to invoke all the added handles on the detailed event. This means that if you want the handle on the event to be invoked (and this is what you want to accomplish most), you must call the base class. In some rare classes, you want to replace the default event behavior in the base class so that the handle on the event is not executed. You do not guarantee that the event handle will be invoked because some "sick" event handles may throw some exceptions, but you can guarantee that the behavior of your derived class is correct.

Using overloads is more efficient than adding event handles. I have told you in principle 22 that the System.Windows.Forms.Control class is a sophisticated use of appointment mechanisms to store event handles, and then map the appropriate handles to detailed events. This event mechanism takes more processor time because it must detect the event to see if it has an event handle added to it. If it does, it must iterate over the entire call list. Each method in the method list must be invoked. Decide which event handles are there and run the iterations for them, which takes more execution time than just calling a virtual function.

If this is not enough to make you decide to use overloads, then look at the list of principles at the beginning. Which one is clearer? If you overload a virtual function, when you maintain the form, only one function is checked and modified. The event mechanism has two places to maintain: one is the event handle and the other is the function on the event handle. Any one of them may fail. A function is simpler.

OK, I've given you all the reasons why you need to use overloads instead of event handles. NET Framework designer must add an event to someone, right? Of course it is. Just one of the things we have left, they're too busy to write code that nobody uses. Overrides are provided only for derived classes, and other classes must use the event mechanism. For example, you often add a button to click on an event to a form. The event is triggered by a button, but the form object handles the event. You can definitely define a user's button in this class, and rewrite the click handle, but it takes too much code to just handle an event. In any case, the problem is to give your own class: The button you define yourself or you must communicate with the form when you click it. It is clear that events should be used to deal with. So, in the end, you just create a new class to send events to the form: in fact, we can create this class without sending an event to the form can complete the callback, but the author is accustomed to say what good just blindly deny others. But anyway, overriding a button to overload a function is really not a very good value. )。 Adding a handle directly to a form event is much simpler than the previous method. That's why. NET Framework designers put events at the front of the form.

Another reason to use an event is that the event is handled at run time. Use events for greater scalability. You can add more than one handle to an event, depending on the actual environment of the program. Suppose you write a drawing program, depending on the state of the program, you should draw a line under the mouse, or it is to select an object. When the user switches the function mode, you can toggle the event handle. Different classes have different event handles, and the events that are handled depend on the state of the application.

Finally, for events, you can hang multiple event handles onto the same event. Or imagine the same drawing program, you might hook up multiple event handles on the MouseDown event. The first may be to complete the detailed functionality, and the second may be to update the status bar or update some of the different commands that can be accessed. Different behaviors can respond on the same event.

Overloading is the best method when you have a derived class with only one function to handle an event. This is easier to maintain and will be more accurate and more efficient in the future. Instead, you should reserve events for other users. Therefore, we should choose to override the implementation of the base class rather than add an event handle.

Back to the Tutorial directory

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.