C#: is calling an event handler explicitly really “a good thing to do”?

后端 未结 6 1140
死守一世寂寞
死守一世寂寞 2020-12-06 05:39

This question is related to C#, but may be applicable to other languages as well. I have a reservation against using code such as the following:

using System         


        
6条回答
  •  爱一瞬间的悲伤
    2020-12-06 06:07

    The short answer is that why would you simulate a button click by calling the handler directly? If you want to wire both methods up to the same event, you would just wire it up. Event handlers are multicast delegates, which means you can add more than one of them. Wiring up an event more than once is totally acceptable.

        myTimer.Tick += myTimer_Tick;
        myTimer.Tick += myButton_Click;
    
        myButton.Click += myButton_Click;
    

    Whether or not this is a WTF is an engineering call that we can't make from a short code snippet. However, based on your comments, it smells like a WTF. Forms or any UI should never handle business logic. They need to be business-logic-aware to some degree (as in validation) but they don't encapsulate / enforce the logic themselves.

    Going further, following some simple practices as basic refactorings and using a layered (n-tier) approach to software will take you a long way, and you will realise along the way that the code you presented smells bad.

    Eventually you'll come across some high-level patterns like MVC (model-view-controller) and MVP (model-view-presenter) which go a step beyond the simple layering. If you follow them you get a good separation of concerns.

    I agree with the accepted answer, but jumping right into 'Use MVC', here's some code that doesn't illustrate MVC, without explaining why is a little cargo-cult for me.

提交回复
热议问题