Stéphane Gourichon
Stéphane Gourichon

Reputation: 6981

Why should INotifyPropertyChanged and plain events be mutually exclusive?

MS recommendation

INotifyPropertyChanged Interface on MSDN states :

For change notification to occur in a binding between a bound client and a data source, your bound type should either:

  • Implement the INotifyPropertyChanged interface (preferred).

  • Provide a change event for each property of the bound type.

Do not do both.

The questions revolves around why "do not do both".

Context

I'm writing a program that runs server side. A bunch of classes are meant to be used locally and sent as answer to HTTP clients requests using WCF (no notification to clients). For this purpore, they are generated from a XML schema (like this in a pre-build event: "$(TargetFrameworkSDKToolsDirectory)xsd.exe" "$(ProjectDir)generated\SystemState.xsd" /classes /enableDataBinding /namespace:XXX /o:"$(ProjectDir)generated" .

The /enableDataBinding option comes in handy to have automatic notification (all notification receivers are server-side).

This is really good for some notification receivers (server state change trigger some relevant code). Those aren't even interested in details, just to know that a property change, which makes a very good fit with INotifyPropertyChanged.

But some receivers are specifically interested in one particular property change, which makes a good fit for "plain" MyFooChanged events.

Choice

I have two options:

The second seems much cleaner but violates Microsoft recommendation.

Does MS recommendation have a point here ?

In this context, should I really worry about Microsoft saying "Do not do both" ? Humorous tribute to XKCD below to state the spirit of the question:

XKCD 608 : do not write in this space

I think there's no problem right now, but it may be interesting to discuss reasons why Microsoft states to not do both.

Cheers,

Upvotes: 1

Views: 336

Answers (1)

Jon
Jon

Reputation: 437376

In which context would it be bad to do both ? Windows Forms ? WPF ?

Both support INotifyPropertyChanged and PropertyNameChanged event-based notifications, so it would apply universally when you are data-binding.

What happens if you do both ? Duplicate updates in some controls ?

It's not very easy to answer this question (a definitive answer would take more than just reading the relevant source). Obviously there would be lots of needless duplicate work going on; in read-only scenarios such as this one I wouldn't exactly expect fireworks.

What else?

The main problem as I see it is lack of consistency, which leads to misunderstanding, which leads to bad code.

If there are no special factors into play strongly suggesting to do otherwise, I 'd go with just INotifyPropertyChanged because it's well-known, immediately understood and goes lighter on the event handlers. You can use expression trees to make it strongly typed, too.

Upvotes: 2

Related Questions