Good practices on events...

  • Thread starter Thread starter Iulian Ionescu
  • Start date Start date
I

Iulian Ionescu

Here is how I typically define this:

protected virtual OnSomePropertyChanged(EventArgs e)
{
if (this.SomePropertyChanged!=null)
{
this.SomePropertyChanged(this, new EventArgs());
}
}

public int SomeProperty
{
get {return this.someField;}
set {
if (this.someField!=value)
{
this.someField = value;
this.OnSomePropertyChanged(new EventArgs());
}
}

public event EventHandler SomePropertyChanged;

This being said, I would like to ask a few questions
about good practices regarding this:
1) Is it always necesary to have an event for each public
property even if it is very less likely to be listened by
anyone? For example: BorderStyleChanged. There is almost
no reason for anybody to listen to this and do something
about it...
2) If the change of the property requires additional
actions (like the invalidation of some areas or childred,
some layout recalculations, and so on), where should
these action be put: in the OnSomeProperty change method,
before or after the raise of the event? Or in the
property's set method?
I see some pros and cons: putting it in the On... allows
the inheritor to completely override all actions that
happen due to the property being changed. However, to
assure that the control (if it's a control) is properly
redrawn perhaps the call to Invalidate should be in the
set method?

This is it, if anybody has some good practices regarding
this I would be happy to hear...
Thank you,
Iulian
 
These are good questions to keep in mind, but ones that should probably be
resolved on a property by property basis. This seems more like a question
about good API design. For what it's worth, if you are designing an API for
internal use within your organization, I'd follow XP programming practices
and only do the work (i.e. expose the events) you actually need. On the
other hand, if you are designing an API that you will be selling (like a
control that you will be selling to developers), of course you'll want to
expose much more and try to anticipate your customer's needs. Personally,
I've been frustrated by both extremes. When a control has 200 properties
and events, it's sometime a bit of an overload (although by attributing them
properly you can make sure they're organized nicely in the property
browser). Of course, it's a disqualifier when the control doesn't expose
the properties I need.

Tom Clement
Apptero, Inc.
 
Iulian,
Rather then:
this.SomePropertyChanged(this, new EventArgs());

I would recommend:
this.SomePropertyChanged(this, EventArgs.Empty);

As it prevents an empty object from being created repeatedly.

My OnEvent normally only raise the event, if I have pre or post processing I
do it before I call OnEvent. As OnEvent can be overridden and the derived
class may choose not to call base.OnEvent. However it really depends on how
you want the behavior of your class defined.

Hope this helps
Jay
 
Back
Top