4

Is it OK to have a nested class raise an event and for the parent class that subscribes to that event subsequently raise another event, which it's parent class has subscribed to - thus passing the original event up the class hierarchy?

It may be easy to explain like this...

We have...

Class A
Class B
Class C

Operation...

  1. Class C raises an event
  2. Class B subscribes to that event, on notification it raises another event
  3. Class A subscribes to Class B event, on notification it does something

So the original event occurred in Class C and Class A is dealing with it.

Using this method means I require event handlers in the middle class (Class B) whose only function is to pass along the notification - this seems a little smelly to me.

1
  • I suppose by Nested Class you mean composition of objects where object of C is member of B and object of B is member of A. Because I dont see any point of creating actual nesting of classes for raising events Apr 4, 2016 at 12:16

3 Answers 3

4

Yes, it is OK and it is a good way of hiding the details of your inner events as well as having one class to connect your event listeners to, instead of several one. It does not mean that having multiple events in multiple classes is bad - far from it - just that it helps in increasing the comprehension of your code if all events related to a particular business domain are in the same "place", although the real inner work is done in "child" classes.

There even is a name for it: event bubbling. You may be interested in reading the MSDN article on that subject.

1

First: I agree it's OK. But if you find yourself doing it a lot you may want to use an event bus instead.

1

An alternative would be to return IObservable instead of making events. This would allow B to have a single method that simply delegates to the inner C instead of needing to have its own event and hook up an event handler to the inner C.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.