top button
Flag Notify
    Connect to us
      Facebook Login
      Site Registration Why to Join

Facebook Login
Site Registration

Are events only used for GUI programming?

+4 votes
30 views

How do you handle in normal backend programming when something happens to this other thing?

posted Jun 28, 2016 by Shivam Kumar Pandey

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button
What is the context of your query, can you explain in more detail.

1 Answer

0 votes

NO,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.

public void Register(user) {
    db.Save(user);
}
Then someone decides that an email should be sent. We could do this:

public void Register(user) {
    db.Save(user);
    emailClient.Send(new RegistrationEmail(user));
}

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).

public void Register(user) {
    db.Save(user);

    RaiseUserRegisteredEvent(user);
}

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.

answer Jul 1, 2016 by Manikandan J
Contact Us
+91 9880187415
sales@queryhome.net
support@queryhome.net
#280, 3rd floor, 5th Main
6th Sector, HSR Layout
Bangalore-560102
Karnataka INDIA.
QUERY HOME
...