Author-prepared version

A Decentralized Approach for Programming Interactive Applications with JavaScript and Blockly

Assaf Marron Gera Weiss Guy Wiener Weizmann Institute of Science Ben-Gurion University HP Labs [email protected] [email protected] [email protected]

Abstract Keywords Behavioral Programming, JavaScript, We present a decentralized-control methodology and a Coroutines, HTML 5, Blockly, Visual Pro- tool-set for developing interactive user interfaces. We gramming, Client-side, Web application, Browser focus on the common case of developing the client side of Web applications. Our approach is to combine vi- 1. Introduction sual programming using Google Blockly with a single- The behavioral programming (BP) approach is an ex- threaded implementation of behavioral programming tension and generalization of scenario-based program- in JavaScript. We show how the behavioral program- ming, which was introduced in [4, 11] and extended ming principles can be implemented with minimal pro- in [17]. In behavioral programming, individual re- gramming resources, i.e., with a single-threaded envi- quirements are programmed in a decentralized manner ronment using coroutines. We give initial, yet full, ex- as independent modules which are interwoven at run amples of how behavioral programming is instrumental time. Advantages of the approach include facilitation in addressing common issues in this application do- of incremental development [17], naturalness [10], and main, e.g., that it facilitates separation of graphical rep- facilitation of early detection of conflicting require- resentation from logic and handling of complex inter- ments [18]. A review of research and tool development object scenarios. The implementation in JavaScript and in behavioral programming to date appears in [14]. Blockly (separately and together) expands the avail- While behavioral programming mechanisms are avail- ability of behavioral programming capabilities, pre- able in several languages such as live sequence charts viously implemented in LSC, Java, Erlang and C++, (LSC), Java, Erlang and C++, its usage for complex to audiences with different skill-sets and design ap- real-world application and development of relevant proaches. methodologies are only beginning. The purpose of the research summarized in this pa- Categories and Subject Descriptors D.3.3 [Language per was to examine behavioral programming in a spe- Constructs and Features]: Concurrent programming cific application domain, and to adjust it to languages, structures; D.1.3 [Programming Techniques]: Concur- technologies and work methods that are used in this do- rent programming main. The paper also sheds light on the principles of programming behaviorally and the facilities required of General Terms Languages, Design, Human Factors behavioral-programming infrastructure. The paper describes and demonstrates the imple- mentation of behavioral programming in JavaScript and in Google’s Blockly for the client side of Web applications, and then discusses general usability and design principles highlighted by these implementa- tions. Clearly, in addition to the combined Blockly- and-JavaScript implementation shown here, behavioral [Copyright notice will appear here once ’preprint’ option is removed.] programming can be used with JavaScript without

Author-prepared version; See published version in AGERE! 2012 - ACM DL 1 2012/12/19 Blockly, or with Blockly with translation to another necessary, in the least, and in some cases, artificial and language, such as Dart. In this regard, Blockly is a layer even detrimental to the understandability of the text. above our JavaScript implementation, which can sim- In this context, of course, the language name Blockly plify development and facilitate experimenting with a fits nicely with its proposed use in programming be- variety of programming idioms. We hope that together haviorally. Still to minimize confusion, we avoided us- with previously described ideas about scenario-based ing the terms block and blocking in two other com- and behavioral programming, this paper will help drive mon software-related meanings, namely, (c) stopping the incorporation of these principles into a wide vari- a process or a subroutine while waiting for an event or ety of new and existing environments for development resource; and, (d) a segment of program code which with agents, actors, and decentralized control, and will contains all the commands between some end-markers help add them into the basic set of programming con- such as curly braces or begin and end. cepts that are understandable by and useful for novice and expert alike. 2. Behavioral Programming We propose that decentralized scenario oriented pro- In this section we outline the technique of Behavioral gramming techniques offer significant advantages over Programming for the development of reactive systems. traditional programming metaphors in this specific do- Formal definitions and comparisons with other pro- main. Consider, for example, an application with some gramming techniques appear in [14, 17, 19]. buttons on a screen where there is a requirement that A preliminary assumption in our implementation of the software reacts to a sequence of button clicks in behavioral programming is that an application, or a a certain way. Using a non-behavioral style with, e.g., system, is focused on processing streams of events with JavaScript, one of the standard programming languages the goal of identifying and reacting to occurrences of in this domain, the would handle each meaningful scenarios. Detected event sequences are button-click separately, and introduce special code to then used to trigger abstract, higher level, events, which manage state for recognizing the specific sequence of in turn may trigger other events. Some of these events events. We argue that with behavioral programming are translated to actions that the system takes to effect such a requirement can be coded in a single imperative changes in the external world. This cycle results with script with state management being implicit and natural a reactive system that translates inputs coming from its rather than explicit. See Section 5.1. sensors to actions performed by its actuators. Our choice of the domain of interactive technology Requested Events is influenced also by the current debate about the rel- b-thread ative merits of Flash and JavaScript/HTML5 technolo- Blocking gies (see, e.g., [28]). We believe that the technologi- b-thread cal discussion conducted mainly in industry should be b-thread accompanied with academic revisiting and analysis of b-thread software engineering and methodology aspects. Selected Event

Figure 1. Behavioral programming execution cycle: About the terms block and blocking all b-threads synchronize, declaring requested and As we are dealing with languages and programming id- blocked events; a requested event that is not blocked ioms, the reader should note that the term block appears is selected and b-threads waiting for it are resumed. in this paper in two different meanings: (a) a brick or a box - referring to programming command drawn as More specifically, in a behavioral program, event a two-dimensional shape; and (b) a verb meaning to sequences are detected and generated by independent forbid or to prevent, associated with the behavioral pro- threads of behavior that are interwoven at run time in gramming idiom for declaring events that must not hap- an enhanced publish/subscribe protocol. Each behav- pen at a given point in time. It is interesting to observe ior thread (abbr. b-thread) specifies events which, from that these meanings are individually commonly used its own point of view must, may, or must not occur. and are appropriate for the intent, that finding alterna- As shown in Figure 1, the infrastructure consults all tive terms for the sole purpose of disambiguation, is un- b-threads by interweaving and synchronizing them, and

Author-prepared version; See published version in AGERE! 2012 - ACM DL 2 2012/12/19 selects the events that will constitute integrated sys- ness of b-threads (see Section 5) facilitate subsequent tem behavior without requiring direct communication adding and changing of event choices. between b-threads. Specifically, all b-threads declare The behavioral programming technique facilitates events that should be considered for triggering (called new automated approaches for planning in execu- requested events) and events whose triggering they for- tion [12, 15], program verification and synthesis [13, bid (block), and then synchronize. An event selection 18, 22], visualization and debugging of concurrent ex- mechanism then triggers one event that is requested and ecution [5], natural language coding of scenarios [9], not blocked, and resumes all b-threads that requested and program repair [20] . the event. B-threads can also declare events that they simply “listen-out for”, and they too are resumed when 3. Infrastructure Implementation these waited-for events occur. 3.1 Coordinating behaviors written in JavaScript This facilitates incremental non-intrusive develop- In principle, the concepts of behavioral programming ment as outlined in the example of Figure 2. For are language independent and indeed they have been another example, consider a game-playing program, implemented in a variety of languages using differ- where each game rule and each player strategy is added ent techniques. However, certain language facilities in a separate module that is oblivious of other rules are needed in order to control the execution, synchro- and strategies. Detailed examples showing the power nization and resumption of the simultaneous behav- of incremental modularity in behavioral programming iors. In LSC this is done by the control mechanism appear, e.g., in [17–19]. which, interpreter-like, advances each chart along its WhenLowAddHot WhenLowAddCold Stability Event Log locations (see, e.g. [16]). In Java [17], Erlang [32] and wait for wait for wait for ⋯ C++ the mechanism is implemented as independent AddHot while WaterLevelLow WaterLevelLow WaterLevelLow threads or processes and uses language constructs such blocking AddHot as wait and notify for suspension and resumption. request request AddCold AddCold AddHot AddCold When executed in a browser, a JavaScript application AddHot is typically executed as a single thread in a single pro- request request wait for AddCold AddHot AddCold AddCold AddHot cess, hence another mechanism is needed. Note that while AddCold for the present proof-of-concept, the choice is indeed request request blocking ⋯ JavaScript, but the language-independent principles AddHot AddCold AddHot can be implemented also in other technologies, say, Figure 2. Incremental development of a system for controlling wa- Flash ActionScript, if appropriate constructs are avail- ter level in a tank with hot and cold water sources. The b-thread able for suspension and resumption. WhenLowAddHot repeatedly waits for WaterLevelLow events and requests three times the event AddHot. WhenLowAddCold performs a similar action In JavaScript 1.7 [27] (currently supported in the with the event AddCold, reflecting a separate requirement, which was intro- browser) the yield command was introduced duced when adding three water quantities for every sensor reading proved to be insufficient. When WhenLowAddHot and WhenLowAddCold run si- which allows the implementation of generators and multaneously, with the first at a higher priority, the runs will include three coroutines, and we chose to use it for our BP im- consecutive AddHot events followed by three AddCold events. A new re- quirement is then introduced, to the effect that water temperature should plementation - providing suspension and resumption be kept stable. We add the b-thread Stability, to interleave AddHot and in single-threaded multi-tasking. Briefly, the yield AddCold events using the event-blocking idiom. mechanism allows a method to return to its caller, and In behavioral programming, all one must do in or- upon a subsequent call, continue from the instruction der to start developing and experimenting with sce- immediately after the most recent return. Thus, in the narios that will later constitute the final system, is to context of coroutines, coordinated behavioral execution determine the common set of events that are relevant can be described as follows: to these scenarios. While this still requires contempla- Behavior threads are implemented as JavaScript tion, it is often easier to identify these events than to coroutines. For example, the b-thread Stability of determine objects and associated methods. By default, the water-tap example is shown in the following code- events are opaque and carry nothing but their name, snippet. The b-thread two calls to yield correspond to but they can be extended with rich data and functional- the two boxes of this b-thread in Figure 2. ity. Further, the incremental traits of BP and the small- function() {

Author-prepared version; See published version in AGERE! 2012 - ACM DL 3 2012/12/19 while (true) { ers for variables and sub-clauses of the commands and yield ({ can express scope of program-segment containment, request: [], wait: ["addHot"], relying on the notation of a block containing physi- block: ["addCold"] cally other blocks, with possible nesting. The popu- }); yield ({ larity of the Scratch language suggests that this style request: [], of coding is more accessible to children than standard wait: ["addCold"], block: ["addHot"] programming languages, and perhaps even other visual }); languages, such as LSC. However, we also feel that the } combination of visualization and language customiza- } tion make Blockly an excellent platform for demon- The infrastructure executes in cycles. In each cycle, the strating coding techniques that would otherwise require b-threads are called one at a time. The coroutine of pseudo-code or abstraction, and it may also provable each b-thread returns, using the yield command, spec- suitable for complex applications. ifying this coroutine’s declaration of requested events, While Scratch and BYOB are interpreted (in SmallTalk blocked events and waited-for events. Once each of the and now also in Flash), Blockly and Waterbear di- b-threads has been called and has returned in this man- agrams are translated into code (we use JavaScript) ner, and its declarations have been recorded, the infras- which can later be manipulated and executed natively tructure selects for triggering an event that is requested without dependency on the development environment. and not blocked. The infrastructure then resumes all Our implementation of behavioral programming in b-threads that requested or waited for the event, by call- Blockly includes new (types of) blocks: the b-thread ing them (and only them), one by one, as part of the block new cycle. In fact this description summarizes the majority of what was needed for our implementation of behavioral programming in JavaScript. More details appear in Ap- pendix A. The b-threads are, of course, application spe- for the b-thread logic (the string b-thread in the cific and are provided by the application programmer. template can replaced by the programmer with the Since JavaScript requires that the yield command b-thread’s name or description); the b-Sync block be visible in the source of the coroutine at least once, in the present implementation we chose not to hide it within a method dedicated to behavioral synchroniza- tion and declarations, such as the bSync method in the Java implementation. Indeed, we feel that this diversity in command name usage across languages emphasizes for synchronization and bidding of requested, waited- that BP benefits, such as ease of state management and for, and blocked events; and, a lastEvent block where incrementality (see Section 5), can be gained by imple- b-threads that wait for a number of events can examine menting and using BP principles in any language and the one that indeed happened. with a variety of idioms. For illustration, the Stability b-thread of the water-tap example, is coded in Blockly as 3.2 Behavioral blocks for Blockly The Google Blockly environment [8] is built along principles similar to those of the popular Scratch lan- guage [30]. Other languages and environments in this family include, among others, BYOB/SNAP! [26], MIT App Inventor [1], and Waterbear [6]. In these lan- guages, the programmer assembles scripts from a menu of block-shaped command templates that are dragged onto a canvas. The Blockly blocks contain placehold-

Author-prepared version; See published version in AGERE! 2012 - ACM DL 4 2012/12/19 and is automatically compiled into the JavaScript code To transform application decisions into effects on shown in Section 3.1. the environment, an HTML entity can activate JavaScript The advantages of programming in this manner are code using another part of the behavioral infrastruc- discussed in Section 5. We will only mention here ture we added in Blockly/HTML/JavaScript, the verb that the visualness of Blockly adds to the usability of when eventName, as follows:

BP principles, while behavioral decomposition should bilities, such as list concatenation, that are not specific In this simple example, there are no application- to behavioral programming. logic b-threads and the actuator is driven directly by 4. Programming an Interactive Application the behavioral event generated by the sensor. Behaviorally - an Example-driven Tour In the present implementation, events are simply character strings. The semantics of triggering a be- In this section we present the underlying design prin- havioral event in Blockly is notifying (or resuming) ciples for applications coded with Blockly, JavaScript, any b-thread or HTML entity that registered interest and HTML, via a review of several small applications. in the specified event, using the b-Sync block or the The code and additional explanations are available on- when_eventName idiom, respectively. line at www.b-prog.org We believe that the design of a reactive behavioral 4.1 Sensors and Actuators application should start with analysis and determina- tion of the sensors and actuators and the associated A key design principle is separating the “real” world events. For example, Figure 3 in Section 4.3 shows from the application logic using appropriate interfaces such an event list for a richer example. The behaviors for translating occurrences in the environment into en- can then be added incrementally, as requirements are tities that can be processed by the application, and ap- analyzed. Of course, as needed, sensors and actuators plication decisions into effects on the environment. can be modified or replaced. In this approach the role We begin our example-driven tour with examination of GUI design can be separated from that of application of the sensors and actuators of a simple application logic programming, and deciding about sensors and ac- which consists of the following three buttons: tuators can be seen as a development stage in which ne- gotiation and agreement between individuals acting in these capacities take place. The requirements for this application are that when 4.2 Application-logic b-threads the user clicks Button1 the greeting should be changed We now move to a slightly richer example - a water-tap to “Good Morning” and when the user clicks Button2 application similar to the one described in Section 2. the greeting should be changed to “Good Evening”. We This application’s logic is coded in the following b- first have to create a sensor for the button clicking: threads. One b-thread adds five quantities of hot water

The clicking is captured by the standard use of the HTML verb onclick and the ensuing activation of JavaScript code. The function bp.event is part of the behavioral infrastructure in JavaScript, and it creates the behavioral event passed as a parameter. Details Another adds five quantities of cold water and termi- about event triggering appear in Section 4.3 nates:

Author-prepared version; See published version in AGERE! 2012 - ACM DL 5 2012/12/19 And, the third b-thread which interleaves the events is the same as the one shown in Section 3.2. The result The game is won when the rocket lands safely on the is of course the interleaved run of ten events alternating landing pad, and is lost if the rocket either lands on the repeatedly between addHot and addCold. landing-pad when it is not aligned with it, or if it misses Each b-thread is contained within the Blockly block the landing-pad altogether. of b-thread. The b-thread can use any Blockly block As suggested in Section 4.1 we first agree on the for implementing the desired logic. To synchronize events, and the associated sensors and actuators in the with other b-threads the b-Sync block is used, with the game. They are listed in Figure 3. three parameters of requested, waited-for, and blocked As described in the infrastructure section, at every events. synchronization point, the declarations of all b-threads In contrast with the BPJ Java implementation, where are consulted, an event is selected for triggering, and b-thread priorities were assigned explicitly, in the b-threads that requested or waited for that event are re- Blockly implementation, b-thread priority is implied sumed. Events that are generated by sensors are han- by its physical location on the development canvas, dled as follows. The function bp.event dynamically with the topmost b-thread being called first, and the creates a b-thread which requests the event at the next lowest b-thread being called last in every execution cy- synchronization point, and terminates once the event is cle. When a new b-thread is added some dragging may triggered. be needed in order to insert it at the desired priority. When an execution cycle ends and no event is trig- When starting an application, the Blockly infrastruc- gered, the system is considered to have completed a su- ture also triggers a behavioral event called start to perstep. The next behavioral event, if any, must come activate the JavaScript behavioral programming infras- from a sensor reporting some external environment tructure and execution of all b-threads. event. The sensor-generated event initiates a new su- perstep which then continues until, again, there are no events to be selected. To force a sensor-generated 4.3 Execution Cycle Details event to be triggered only at a beginning of a new To show finer points about the interweaving of b-threads future superstep, the sensor code should not call the in the Blockly/JavaScript environment, we examine an event-triggering function directly, but should set it as application for a computer game where the player at- a timer-driven JavaScript event. Due to the JavaScript tempts to land a rocket on a landing pad on the surface single-threaded non-preemptive events mechanism the of a planet, or perhaps a space shuttle on a space sta- code will run as soon as the current function (the super- tion. The rocket moves at a fixed speed in the vertical step) ends. This is shown below where a RocketLeft direction. Using GUI buttons, the player can move the actuator uses a when_ clause and the function trigger rocket right and left to be positioned directly above the to serve as a RocketTouchedLeftWall sensor. landing pad. The player can also press the Up button