Closures and event handling: Correct Solution


Suppose we are in an environment where CLICK, TICK, and KEY events can occur, and we have the following functions available:

onClick(closure)

Executes closure after every subsequent CLICK event.

onKeyPress(closure)

Executes closure after every subsequent KEY event.

afterDelay(tickCount, closure)

Executes closure once after exactly tickCount TICK events have occurred.

twice(closure)

Immediately executes closure two times.

Multiple closures can be registered to handle the same event. If this happens, they execute in the order they were registered.


Part 1

Consider the following code:

A
twice(() -> B);
C
afterDelay(1, () -> D);
E
onKeyPress(() -> F);
G

Write out the order in which all the marked statements will execute given the following sequence of events (showing both the marked statements and the event names):

TICK
KEY
TICK

Solution

A
B
B

TICK

KEY
F

TICK
D

AFTER
C
E
G

Although it is not necessary for getting credit for the conceptual mastery puzzles, it is a good idea to study a few examples of this puzzle at the next highest difficulty level. That level introduces a new twist: event handlers adding other event handlers. Understanding what happens you do that will help you avoid common mistakes on the later homeworks and the course project.


Part 2

Consider the following code:

public class StatefulPuzzle {
    private int x = 0;

    public void run() {
        onClick(() -> {
            x++;
            System.out.println("x=" + x);
        });

        onClick(() -> {
            if (x < 2) {
                System.out.println("Hi!");
            }
        });

        if (x < 1) {
            onClick(() -> {
                System.out.println("Bye!");
            });
        }

        System.out.println("End of run()");
    }
}

Given a call to run() followed by two CLICK events, what would this code print?

Solution

End of run()
x=1
Hi!
x=2
Hi!

Related puzzles: