-1

Events are compiler implementation for observer pattern. And also I think it is not very logical to add some contracts for design pattern implementation in an interface. so it seems that adding events in interface might be bad practice. Is it right?

mehdi.loa
  • 579
  • 1
  • 5
  • 23
  • http://stackoverflow.com/questions/1745990/practical-use-of-interface-events – Habib May 17 '13 at 05:10
  • Events have many usages, but I think it forces the classes the implement some specific design pattern, and I don't know is it right? – mehdi.loa May 17 '13 at 05:18
  • Why shouldn't you "force" a design pattern in your interface if it's a great fit for your use case? – jgauffin May 17 '13 at 06:30

3 Answers3

4

Sure, some kinds of objects are just "eventful." What comes to mind is things like viewmodels in MVVM. It's important that they implement an event which lets the view know when things have changed so that the view can be updated. (See INotifyPropertyChanged.)

Lots of other things need to be able to raise events too, like socket listeners. One could imagine an interface that generalized listeners, the main member of which is an event for a new connection, and possibly an event for new data arriving as well.

More broadly, just because something is suggested by a design pattern is no reason not to define it in an interface. In fact, many would take it as an invitation to do so. My advice is to do what makes the most sense, whether it fits a design pattern or not.

Eric Mickelsen
  • 10,309
  • 2
  • 30
  • 41
2

I think that having events in the interface completely makes sense.

If you have a service that exposes in its contract a way for client to be notified, why not?

What is the alternative? Defining the callback interface and registering it with the service? This is a canonical implementation of observer from GoF book, and you don't seem to have problems with pushing that specific pattern implementation to the user (mind you, it is always important what you expose to the user, not to the implementation - implementation will not write itself).

Zdeslav Vojkovic
  • 14,391
  • 32
  • 45
2

Events aren't a compiler implementation of the Observer pattern, but rather a language and framework implementation of the pattern. As such, it's a first-class member of the .NET framework and the C# language. That's why I wouldn't worry about using them in interfaces - they're too much of a part of the language to hide.

The same can be said of Properties. They're a design pattern as well, hiding getter/mutator methods behind a straightforward semantic. But we still use them in interfaces.

Don't fear the abstraction. Good patterns get used, so they sink into the infrastructure and become transparent. That's a good thing.

Avner Shahar-Kashtan
  • 14,492
  • 3
  • 37
  • 63