2

I have a game with such events as GameOver, GameStart, PlayerWin, etc. I only have one class that is listening on these events, for the purpose of sending these events as TCP json messages to a client (player).

But for every important game function I write, I have to write an event and then call

if(MyEvent != null)
   MyEvent(this, new GameEventArgs("gameover"));

I could as easily avoid writing an event for each important action and instead include the listener as an instantiated class and simply send messages that way.

private GameListener gameListner = new GameListener();

private void GameOver(){
    this.turnTimer.enabled = false;
    this.winner = player; //etc
    gameListener.GameOver(player);
}

class GameListener{
    public void GameOver(Player player){
        JSON json = EncodeJson(GAME_OVER, player);
        SendClientData(json);
    }
}

Is there any reason I should stick to events and delegates?

2

The benefit of events compared to your approach is that more than one or less than one objects can listen to an event. In your case, there could be one and one only game listener.

You may stick with YAGNI and KISS: right now, you have only one object listening to the event, so why bothering?

On the other hand, using events, especially if you consider EventHandler<TEventArgs> generic, is:

  • Very easy to implement,

  • Very common in C# world, so other programmers will probably know how to use your code,

  • Supports from scratch the case when you don't need to listen to the event at all or when multiple listeners exist (for instance, one will send a message over TCP while other will store the new score of the user in the database.)

  • Thanks for the response. Perhaps it will be good future proofing. – tones31 Aug 3 '15 at 22:26
  • I still disagree with the decision to have to check for null before calling, though. It's useless boilerplate. If there are no listeners, MyEvent(someArgs) should do nothing, not throw an exception. – Rob Aug 3 '15 at 23:41
0

The main benefit of using events/delegates is Loose Coupling.

When you code the listener into the event-publisher class you are tightly coupling both classes.

Initially this might not be a bad thing, but if your application needs to grow and be extended then tight coupling can make maintenance difficult.

Delegates/events allow the event-publisher to be completely unaware of the event consumer(s).

Of course, as MainMa has already point out, if your current needs are simple then it's perfectly reasonably to apply KISS and YAGNI and put off switching to events/delegates until they are needed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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