58

Are events only used for GUI programming?

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

5
  • 6
    By the way, Event Source is a completely orthogonal concept to Event-Programming. The basic concept of Event Sourcing is that you store "events" or "changes" to your system, instead of storing the "state" of your system. For example, you could model your bank account as a) Your Balance (STATE) or b) A series of Transactions (EVENTSOURCE).
    – ArTs
    Jun 20, 2016 at 6:58
  • 4
    Depending on usage, an "event" is usually just some form of callback wrapped with sugar. Callbacks get used everywhere - if you're interested, that's probably a good keyword to start a search with.
    – J...
    Jun 20, 2016 at 11:24
  • 10
    I will also point out that even if you go as low level as a microcontroller, you will find hardware interrupts a useful and debatably essential feature. Great for control systems, or basic IO like a coffee maker. These hardware interrupts are really not essentially different from events.
    – Dan
    Jun 20, 2016 at 18:14
  • Nope! Practical example: Nodejs events Jun 21, 2016 at 5:54
  • 2
    Are you on Windows? Check out the Event Viewer. Have fun.
    – Marc.2377
    Jun 21, 2016 at 6:29

8 Answers 8

106

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.

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.

9
  • 37
    I read this and think of our "create booking" code and I cry for a while and long for a better place :'(
    – sara
    Jun 20, 2016 at 9:14
  • 2
    +1, great answer. Just a tangential question (this bothered me a bit): is there a special reason for you to have started your method names (Register, Save and Send) with capital letters? Of course this is doesn't affect the usefulness of this answer, though.
    – Pedro A
    Jun 20, 2016 at 10:55
  • 14
    @Hamsteriffic I'm mostly a C# dev and that's the generally accepted convention. No other reason.
    – RubberDuck
    Jun 20, 2016 at 11:27
  • 6
    @Hamsterifficas an addition, what you call lowerCase but contain an uppercase in the middle is often called camelCase, because it's got humps in the middle. That distinguish it from snake_case, where lowercase words are separated by underscores, which is familiar to python and most shell languages, to name a few.
    – Aaron
    Jun 20, 2016 at 13:10
  • 5
    Events are one type of these messages, I would say. Method calls are supposed to be considered message passing, as well.
    – jpmc26
    Jun 20, 2016 at 22:29
53

Nope.

A classic example of events being used in non-GUI logic are database triggers.

Triggers are code that gets executed when a given event happen (INSERT,DELETE, etc). Seems like an event to me.

This is the Wikipedia definition of event:

In computing, an event is an action or occurrence recognized by software that may be handled by the software. Computer events can be generated or triggered by the system, by the user or in other ways. Typically, events are handled synchronously with the program flow, that is, the software may have one or more dedicated places where events are handled, frequently an event loop. A source of events includes the user, who may interact with the software by way of, for example, keystrokes on the keyboard. Another source is a hardware device such as a timer. Software can also trigger its own set of events into the event loop, e.g. to communicate the completion of a task. Software that changes its behavior in response to events is said to be event-driven, often with the goal of being interactive.

Not all events are user-generated. Some are generated by a timer like a crontab of by a database INSERT like I mentioned before.

The definition also states than some programs or systems are "event-driven, often with the goal of being interactive", from which one can derive that the purpose or usefulness of events are not solely, but rather often, to provide interactivity (like GUIs although not necessarily GUIs, since CLI programs can also be interactive).

2
  • 2
    I always think of this when I hear about database triggers: thecodelesscode.com/case/42
    – Almo
    Jun 21, 2016 at 20:44
  • As an ex DBA now developer I cringe every time I hear people talk about using triggers without considering the wider DB performance. Jun 22, 2016 at 8:14
27

Event-based programming is actually also used for highly performant server programming.

At a typical server workload, much of the time processing a result actually comes from I/O. For example, pulling data off a (7200 RPM) hard disk drive can take up to 8.3 ms. For a modern GHz processor, that would equate to ~1 million clock cycles. If a CPU were to wait for the data each time (doing nothing), we would lose a LOT of clock cycles.

Traditional programming techniques get around this by introducing multiple threads. The CPU tries to run hundreds of threads concurrently. However, the problem which this model is that, each time a CPU switches thread, it requires hundreds of clock cycles to context switch. A context switch is when the CPU copies the thread-local memory into the CPU's registers and also stores the old thread's register/state into RAM.

Additionally each thread must use up a certain amount of memory for storing its state.

Today, there has been a push for servers which has a single thread, that runs in a loop. Then pieces of work are pushed onto a message pump, which acts as a queue for the single thread (much like on a UI thread). Instead of waiting for work to finish, the CPU sets a callback event, for things like hard disk drive access. Which reduces context switching.

The best example of such a server is Node.js, which has been shown to be able to handle 1 million concurrent connections with modest hardware, while a Java/Tomcat server would struggle at a few thousand.

9
  • 2
    "Modest hardware" is a little misleading. You'll need 8GB+ for Node, in addition to whatever the OS uses. And if you have that much memory, Tomcat can easily handle a few thousand connections. Granted, there is a big difference, but it's not 1000x. Jun 20, 2016 at 18:58
  • @PaulDraper no it cannot. And no it does not. You need 8GB + for just the stack for 8000 threads. That is the big difference.
    – ArTs
    Jun 20, 2016 at 19:02
  • 3
    @PaulDraper besides 8GB is very modest by server standards. I've worked on machines with 128GB of ram and those aren't even fully loaded. The ram sticks cost more than your whole machine.
    – ArTs
    Jun 20, 2016 at 19:07
  • it depends what your stack size is. Oracle/OpenJDK defaults to 1MB on most platforms for 64-bit, and 512K for 32-bit. If you just take the defaults, you'd be correct. But defaults isn't how you get to 1M Node connections ;) Anyway, 128K is plenty; you can get away with even less. That'd be 1GB of stack space for 8000 threads. Jun 20, 2016 at 19:07
  • 6
    You're mistaken. Even with default stack size, you only need 8 GiB of virtual memory. The memory is committed on the fly as needed. Typically, you only need a single page per stack, unless you're actually using the extra memory. And in practice, most threads in such a system only have those (usually) 64-kiB stacks. Virtual memory usage is a big deal on 32-bit OS, but not so much on 64-bit. You run into other limits much sooner - like TCP port exhaustion, for example :) And where do you think those "pseudo-stacks" of node are stored? That's right, on the heap.
    – Luaan
    Jun 21, 2016 at 7:47
10

Events are also heavily used in network programming (e.g. Nginx) to avoid expensive busy-wait loops and instead provide a clean interface to know exactly when a certain operation is available(I/O, urgent data etc). This is also a solution to the C10k problem.

The basic idea is to provide the OS a set of sockets (i.e. network connections) to monitor for events, all of them or just some you're particularly interested in (data available for reading, for instance); when such activity is detected by the operating system on one of the sockets in the list, you will get a notification of the event you were looking for by the API, which you'll then have to sort out where it comes from and act accordingly.

Now, this is a low-level and abstract view, furthermore tricky to get to scale well. However there's plenty of higher level frameworks that deal with that in a even cross-platform fashion: Twisted for Python, Boost.Asio for C++ or libevent for C come to my mind.

2
  • +1 "expensive busy-wait loops": in other words, it is useful in any parallel processes that involve some inactivity (waiting), as well as syncing between such processes (messages or events). As much of the real world works.
    – frIT
    Jun 22, 2016 at 12:12
  • It is interesting to find out that sockets were originally designed as a form of IPC on a single machine, before networking existed.
    – user251748
    Jun 2, 2017 at 13:56
5

Embedded systems are almost always inherently event-driven, even if they are not programmed explicitly as such.

These events come from things like hardware interrupts, button presses, period analog-to-digital readings, timer expirations, etc.

Low-power embedded systems are even more likely to be event-driven; they spend most of their time sleeping (CPU sleeping in a low-power mode), waiting for something to happen (that "something" is an event).

One of the most common and popular frameworks for event-driven embedded systems is the Quantum Platform (QP) (the QP also works under Linux, Windows and any unix-like OS.) State machines are a natural fit for event-driven programming, as the program is not "sequential" in the typical sense, rather, it is a set of "callbacks" that are invoked depending on the system state and current event.

3

Event Messages Gregor Hohpe.

Event Driven Architectures Gregor Hohpe.

SEDA architecture, Welsh, Culler, Brewer.

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

Finite State Machine is one common approach

Given(State.A)
When(Event.B)
Then(State.C)
    .and(Consequences.D)
2
  • 2
    1, this isn't really a coherent answer, and 2, FSM are not good examples of event usage. Jun 20, 2016 at 22:13
  • 1
    FSM. I'm sure the pastafarian religion observes a number of events ;-)
    – frIT
    Jun 22, 2016 at 12:14
0

In embedded systems, events occur during interrupts. There are many sources of interrupts, from timers to I/O.

Also, RTOS can have events too. One example is waiting for a message from another task.

0

For non embedded system but something I was doing in C# was SCADA system. There were many events linked to what was happening in the warehouse when load was unloaded part of system generated event and other part was writing new state to the database. We of course had some GUI client but it was just to show state of the database which was reflecting state of warehouse. So it was backend server software based on events and threading. Quite challenging to develop.

https://en.wikipedia.org/wiki/SCADA

Your Answer

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

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