Are events only used for GUI programming?
How do you handle in normal backend programming when something happens to this other thing?
asynchronous-programmingevent-programmingprogramming-languagestheory
Are events only used for GUI programming?
How do you handle in normal backend programming when something happens to this other thing?
Best Answer
Nope. They're really handy for implementing Observers and making sure that classes are closed to modification.
Let's say we have a method that registers new users.
Then someone decides that an email should be sent. We could do this:
But we've just modified a class that's supposed to be closed to modification. Probably fine for this simple pseudo-code, but likely the way to madness in production code. How long until this method is 30 lines of code that's barely related to the original purpose of creating a new user??
It's much nicer to let the class perform its core functionality and to raise an event telling whoever's listening that a user was registered, and they can take whatever action they need to take (such as send an email).
This keeps our code clean and flexible. One of the often overlooked pieces of OOP is that classes send messages to each other. Events are these messages.