0

Modify the sender's state in events (aside from being a mutable object), is this considered bad practice?

All event examples I've found are very simple and only do something like Console.WriteLine("event!")

Simple code:

public void HandleEvent(object sender, EventArgs args)
{
    ClassA a = (ClassA)sender;

    a.doSomething(this.makeSomething());
}
Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
Jonwd
  • 635
  • 10
  • 24
  • 1
    I think it's ok in many cases. Imagine that the event was something like "I'm ready for more data!". You'd kind of expect to mutate the caller for events like that. – Matthew Watson May 18 '13 at 10:31

2 Answers2

2

It's not bad practice as such, you need to be careful though. For instance would it be relevant if dosomething was called from the eventhandler, or directly.

Or because you can't rely on when the eventhandler gets triggered, you are asynchronous, so you can't assume dosomething has been executed before you call dosomethingelse.

E.g dosomething should change state to 2 only if it's 1. If it's not 1 or already 2 more logic is required.

If you start disappearing into that hole, might be better to queue a request to do a dosomething, and then have an engine which deals with the current state and the request queue.

So have a think about how dosomething to a relates to any other methods you call on a. If it's self contained, you are ok, if dependencies start proliferating, than it's bad idea as opposed to a bad practice.

Tony Hopkinson
  • 20,172
  • 3
  • 31
  • 39
1

I would not consider it bad practice, as far as you do not make assumptions about the order followed by the runtime to call the event handlers registered with your events. In fact, being that order not guaranteed, you should not rely on that to change the state of your objects, including the sender one.

Community
  • 1
  • 1
Efran Cobisi
  • 6,138
  • 22
  • 22