Objective C # principle 35: rewrite a function instead of using an event handle)

Source: Internet
Author: User

Negative tive C # principle 35: rewrite the function instead of using the event handle
Item 35: prefer overrides to event handlers

Many. Net classes provide two different methods to control system events. That is, either add an event handle or rewrite the virtual function of the base class. Why do we need to provide two methods to accomplish the same thing? In fact, it is very simple, that is, the methods to be called under different circumstances. In a derived class, you should always rewrite the virtual function. For your users, you should restrict them to only use handles to respond to events on unrelated objects.

For example, you have a very good Windows application.Program. In your form class, you can choose to override 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 CT 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.
}
}
}

The preceding methods are better. If an exception is thrown by a handle on the event chain, other handles will not be called (see Principle 21 ). Some "pathological"CodeWill prevent the system from calling the handle on the event. By Rewriting protected virtual functions, your control handle will be executed first. The virtual function on the base class has the responsibility to call all the added handles on the detailed event. That is to say, if you want the handle on the event to be called (and this is what you want to do 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 handles on the event will not be executed. You do not guarantee that all event handles will be called, because some "pathological" event handles may cause some exceptions, but you can ensure that the behavior of your derived class is correct.

Using overload is more efficient than adding event handles. I have already told you in Principle 22 that system. windows. forms. the control class uses the appointment mechanism to store event handles and maps appropriate handles to detailed events. This kind of event mechanism takes more processing time, because it must detect the event and check whether it has an event handle added to it. If yes, it must iterate the entire called linked list. Each method in the method linked list must be called. Determine which event handles are there and perform runtime iteration on them, which takes more time to execute than to call only one virtual function.

If this is not enough for you to decide to use overload, then let's look at the linked list at the beginning of this principle. Which one is clearer? If you reload a virtual function, when you maintain this form, only one function needs to be checked and modified. The event mechanism should be maintained in two aspects: one is the event handle, and the other is the function on the event handle. Any one may fail. A function is simpler.

OK. I have provided all the reasons for using the overload instead of the event handle .. Net Framework designers must add events to someone, right? Of course. The only thing you have left is that they are too busy to write code that nobody uses. Override is only provided for the derived class. Other classes must use the event mechanism. For example, you often add a button click event to a form. An event is triggered by a button, but an event is processed by a form object. You can define a user button in this class and overwrite the click handle. However, it takes too much code to process only one event. In any case, the problem is given to your own class: the button you define must communicate with the form when you click it. Obviously, events should be used for processing. Therefore, in the end, you just created a new class to send events to the form (in fact, we can create this class to complete the callback without sending events to the form, just as the author is used to saying anything better, he simply denies others. But in any case, rewriting a button to reload the function is really not very valuable .). Compared with the previous method, it is much easier to add a handle directly to a form event. This is why the designers of the. NET Framework put the event at the top of the form.

Another reason for using the event is that the event is handled at runtime. Use events have greater scalability. You can add multiple handles to an event, depending on the actual environment of the program. Suppose you have written a drawing program. Based on the state of the program, you should draw a line when you click it, or this is to select an object. When switching the function mode, you can switch the event handle. Different classes have different event handles, and the events to be processed depend on the state of the application.

Finally, you can mount multiple event handles to the same event. Imagine the same drawing program. You may have attached multiple event handles to the mousedown event. The first may be to complete the detailed functions, and the second may be to update the status bar or update some different accessible commands. Different behaviors can respond to the same event.

If you have only one function in a derived class to process an event, overloading is the best method. This is easier to maintain and will be more accurate and efficient in the future. The event should be retained for other users. Therefore, we should choose to override the implementation of the base class instead of adding the event handle.
======================================

Item 35: prefer overrides to event handlers
Invalid. net classes provide two different ways to handle events from the system. you can attach an event handler, or you can override a virtual function in the base class. why provide two ways of doing the same thing? Because different situations call for different methods, that's why. Inside Derived classes, you shoshould always override the virtual function. Limit your use of the Event Handlers to responding to events in unrelated objects.

You write a nifty windows application that needs to respond to mouse down events. In your form class, you can choose to override 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 CT it.
Base. onmousedown (E );
}
}

 

Or, you cocould attach an event handler:

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.
}
}
}

 

the first method is preferred. if an event handler throws an exception, no other handlers in the chain for that event are called (see item 21 ). some other ill-formed code prevents the system from calling your event handler. by overriding the protected virtual function, your handler gets called first. the base class version of the virtual function is responsible for calling any event handlers attached to the specified event. that means that if you want the Event Handlers called (and you almost always do), you must call the base class. in some rare cases, you will want to replace the default behavior instead of calling the base class version so that none of the Event Handlers gets called. you can't guarantee that all the event handlers will be called because some ill-formed Event Handler might throw an exception, but you can guarantee that your derived class's behavior is correct.

using the override is more efficient than attaching the event handler. I showed you in item 22 how the system. windows. forms. control class uses a sophisticated collection mechanisms to store event handlers and map the appropriate handler to a special event. the event-handling mechanic takes more work for the processor because it must examine the event to see if any event handlers have been attached. if so, it must iterate the entire invocation list. each method in the event invocation list must be called. determining whether there are event handlers and iterating each at runtime takes more execution time than invoking one virtual function.

if that's not enough for you, examine the first listing in this item again. Which is clearer? Overriding a virtual function has one function to examine and modify if you need to maintain the form. the event mechanic has two points to maintain: The event handler function and the code that wires up the event. either of these cocould be the point of failure. one function is simpler.

Okay, I 've been giving all these reasons to use the overrides and not use the Event Handlers. the. NET Framework designers must have added events for a reason, right? Of course they did. like the rest of us, they're too busy to write code nobody uses. the overrides are for derived classes. every other class must use the event mechanic. for example, you often add a button click handler in a form. the event is generated by the button, but the form object handles the event. you cocould define a Custom button and override the click handler in that class, but that's way too much work to handle one event. it only moves the problem to your own class anyway: somehow, your Custom button must communicate to the form that the button was clicked. the obvious way to handle that is to create an event. so, in the end, you have created a new class to send an event to the form class. it wocould be simpler to just attach the form's event handler to the form in the first place. that's why. net Framework designers put those events in the forms in the first place.

Another reason for the event mechanic is that events are wired up at runtime. you have more flexibility using events. you can wire up different event handlers, depending on the circumstances of the program. suppose that you write a drawing program. depending on the state of the program, a mouse down might start drawing a line, or it might select an object. when the user switches modes, you can switch event handlers. different classes, with different event handlers, handle the event depending on the state of the application.

Finally, with events, you can hook up multiple event handlers to the same event. imagine the same drawing program again. you might have multiple Event Handlers hooked up on the mousedown event. the first wocould perform the special action. the second might update the status bar or update the accessibility of different commands. multiple actions can take place in response to the same event.

When you have one function that handles one event in a derived class, the override is the better approach. it is easier to maintain, more likely to be correct over time, and more efficient. reserve the Event Handlers for other uses. prefer overriding the base class implementation to attaching an event handler.
 

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.