You are on page 1of 19

Information and Software Technology 133 (2021) 106504

Contents lists available at ScienceDirect

Information and Software Technology


journal homepage: www.elsevier.com/locate/infsof

Context-Oriented Behavioral Programming✩


Achiya Elyasaf
Department of Software and Information Systems Engineering, Ben-Gurion University of the Negev, Israel

ARTICLE INFO ABSTRACT

Keywords: Context: Modern systems require programmers to develop code that dynamically adapts to different contexts,
Behavioral programming leading to the evolution of new context-oriented programming languages. These languages introduce new
Scenario-based programming software-engineering challenges, such as: how to maintain the separation of concerns of the codebase? how
Programming paradigm
to model the changing behaviors? how to verify the system behavior? and more.
Context awareness
Objective: This paper introduces Context-Oriented Behavioral Programming (COBP) — a novel paradigm for
Context-oriented programming
Context-Oriented Behavioral Programming
developing context-aware systems, centered on natural and incremental specification of context-dependent
behaviors. As the name suggests, we combine behavioral-programming (BP) — a scenario-based modeling
paradigm — with context idioms that explicitly specify when scenarios are relevant and what information
they need. The core idea is to connect the behavioral model with a data model that represents the context,
allowing an intuitive connection between the models via update and select queries. Combining behavioral-
programming with context-oriented programming brings the best of the two worlds, solving issues that arise
when using each of the approaches in separation.
Methods: We begin with providing abstract semantics for COBP and two implementations for the semantics,
laying the foundations for applying reasoning algorithms to context-aware behavioral programs. Next, we
exemplify the semantics with formal specifications of systems, including a variant of Conway’s Game of Life.
Then, we provide two case studies of real-life context-aware systems (one in robotics and another in IoT) that
were developed using this tool. Throughout the examples and case studies, we provide design patterns and a
methodology for coping with the above challenges.
Results: The case studies show that the proposed approach is applicable for developing real-life systems, and
presents measurable advantages over the alternatives — behavioral programming alone and context-oriented
programming alone.
Conclusion: We present a paradigm allowing programmers and system engineers to capture complex context-
dependent requirements and align their code with such requirements.

1. Introduction program is comprised of a set of scenarios (that say what to do)


and anti-scenarios (that say what not to do), that are interwoven
Requirements of context-aware system are often referring to the at run-time to generate a combined reactive system. Each scenario
system context, either by subjecting a requirement to a specific context and anti-scenario is specified as a sequential thread of execution that
(e.g., ‘‘do not use the GPS when battery is low’’, etc.), or by speci- isolates a specific aspect of the system behavior, desirably an individual
fying how the system should interact with the context (e.g., ‘‘change requirement. Thus, it is also called a b-thread. An application-agnostic
to emergency mode upon fire detection’’, etc.). This work formalizes execution mechanism repeatedly collects these scenarios, chooses ac-
and generalizes an approach for developing context-aware systems, by tions that are consistent with all the scenarios, executes them, and
combining scenario-based programming with context. Specifically, we continuously informs them of each selection. Previous demonstrations
propose to add explicit idioms for referencing of context in behavioral of BP include a show case of a fully functional nano-satellite [3], a
programming, as elaborated next. controller for a RoboSoccer player [4], an autonomous rover [5], a
Behavioral Programming (BP) [1,2] is a language-independent reactive IoT building [6], and more. We elaborate on BP in Section 2.
paradigm for programming reactive systems, designed to allow for In many cases, behaviors, or requirements, are bound to a context.
a natural and incremental specification of behavior. A behavioral In Chess for example, some behaviors are only relevant during a check,

✩ This work was partially supported by the Institute for Innovation in Transportation, Tel-Aviv University, Israel, and the Fuel-Choices and Smart-Mobility
Initiative, Israel.
E-mail address: achiya@bgu.ac.il.

https://doi.org/10.1016/j.infsof.2020.106504
Received 5 May 2020; Received in revised form 19 October 2020; Accepted 30 November 2020
Available online 30 December 2020
0950-5849/© 2020 The Author. Published by Elsevier B.V. This is an open access article under the CC BY license (http://creativecommons.org/licenses/by/4.0/).
A. Elyasaf Information and Software Technology 133 (2021) 106504

others are only relevant for pawns, etc. Behaviors may also interact However, it requires to adapt these approaches, since they are all
with the context by querying or changing it. In Chess for example, one designed under the assumption that the only protocol between the b-
of the behaviors is to trigger the ‘check’ context whenever an opponent threads is requesting, blocking, and triggering of events. Therefore,
pieces is threatening the king. Specifying context-aware requirements the formal semantics presented here lay the foundations towards such
(i.e., context-dependent requirements and requirements that change the adaptations.
system context) with b-threads — requires explicit, first-class citizen
Outline. Section 2 elaborates on the behavioral programming
idioms for referencing and changing the system context — something
paradigm and describes its shortcoming when it comes to handling
that is not defined for BP. In [6] and [4], context idioms were proposed
the system context. Section 3 formally defines COBP, giving abstract
for two implementations of BP, in live-sequence charts (LSC) [7] and in
semantics for the language and presents two implementations of the
JavaScript (respectively). Using the extended languages with first-class
paradigm. Sections 4 to 6 demonstrate how the abstract semantics
citizen context idioms, they demonstrated how the new idioms allow
can be used for formally specifying context-aware systems. In Sec-
for a direct specification of context-aware requirements, resulting in
tions 8 to 10 we provide two case studies of context-aware systems that
a better alignment between the requirements and the specification. In
were programmed using this implementation. In Section 11 we discuss
both languages, the context idioms were defined as syntactic sugars on
reasoning approaches for COP and BP, as well as other approaches for
top of the original language idioms, and translational semantics were
integrating context with modeling and programming. We conclude this
proposed for the new idioms.
paper in Section 12, with a discussion about future research directions.
In this paper, we generalize the approach of [4,6] and present
Context-Oriented Behavioral Programming (COBP) — a novel, language- 2. The context of this paper: Behavioral programming
independent paradigm for developing context-aware systems, centered
on natural and incremental specification of context-dependent behav- When creating a system using BP, developers specify a set of sce-
iors. Specifically, we propose to add first-class citizen context idioms to narios that may, must, or must not happen. Each scenario is a simple
BP and define new formal semantics for specifying the relation between sequential thread of execution, called b-thread, that is normally aligned
the system context and the system behavior. One of the advantages of with a system requirement, such as ‘‘stop moving’’ or ‘‘turn to target’’.
these formal semantics over the translational semantics of [4,6], is the The set of b-threads in a model is called a behavioral program (b-
ability to directly implement the paradigm in different programming program). During run-time, all b-threads participating in a b-program
languages, rather than relying on existing BP implementations and are combined, yielding a complex behavior that is consistent with
translating to them. Based on this ability, we also present a JavaScript- all said b-threads. As we elaborate below, unlike other paradigms,
based implementation for the paradigm and provide two case-study such as functional programming or object-oriented programming, BP
systems that were developed with it (Sections 8 to 10). does not force developers to pick a single behavior for the system to
Another approach for integrating context with programming is use. Rather, the system is allowed to choose any compliant behavior.
the context-oriented programming (COP) paradigm [8]. Over the last This allows the run-time to optimize program execution at any given
decade, COP has evolved in a variety of languages and approaches, moment, e.g., based on available resources. The fact that all possible
starting from Costanza and Hirschfeld [8]. While there are many system behaviors comply with the b-threads (and thus with the system
variations in the way they handle the contextual data and the relevant requirements), ensures that whichever behavior is chosen, the system
behavioral variations, the layers is the most widespread model by will perform as specified.
far [9]. Layers are a language abstraction, grouping definitions of To make these concepts more concrete, we now turn to a tutorial
partial methods that implement some fragment of an aspect of the example of a simple b-program, first presented in [1]. All of the
system behavior [8]. We compare some of the idioms of COP and COBP examples in this paper are specified formally, based on the transition
in Section 9. systems that we define in Section 3. JavaScript-based programs are
Both in COP and COBP, the system may have two contradicting presented in Sections 8 to 10.
behaviors, as long as they are bound to different contexts. Consider Consider a system that controls taps of hot and cold water, whose
for example conflicting requirements, overridden by the context, like output flows are mixed, with the following requirements:
‘‘vacuum the carpet’’ and ‘‘do not vacuum while someone is asleep’’.
Composing the contexts and the behaviors at runtime, may lead to 1. When the system loads, pour some small amount of cold water
unpredictable behavior. Thus, both context-oriented approaches re- three times.
quire reasoning and formal verification techniques for verifying their 2. When the system loads, pour some small amount of hot water
software, i.e., that it will function correctly in all contexts and combi- three times.
nations thereof. Since reasoning algorithms depend on having a formal Fig. 1 shows a b-program that fulfills these requirements. It consists of
specification of the system, an effort has been made in developing two b-threads, added at the program start-up. The first is responsible
formal semantics for COP (as elaborated in Section 11). For this reason, for fulfilling requirement #1, and the second fulfills requirement #2.
one of the major purposes of this paper is to generalize the translational The program’s structure is aligned with the system requirements,
semantics of [4,6], and define formal semantics for the COBP paradigm. with a single b-thread for each requirement, requesting, and blocking
As we demonstrate in Section 10.2, a COBP model that is based on events at each of their state (the 𝑅 and 𝐵 sets). Harel, Marron and
these semantics, allows for applying reasoning techniques on the entire Weiss [2] proposed a simple protocol for interweaving the b-threads
system (i.e., context, behavior, and execution mechanism) with no and executing the model, depicted in Fig. 2. B-threads repeatedly
further input needed, as opposed to some COP implementations that execute an internal logic and then synchronize with each other, by
allow for applying reasoning techniques only for part of the model, or submitting a synchronization statement to a central event arbiter. Once
require a manual translation of the code into a formal model. all b-threads have submitted their statements, the central event arbiter
Furthermore, one of the key advantages of scenario-based program- selects an event that was requested and was not blocked. B-threads that
ming (SBP) [7] in general, and of BP in particular, is the amenability either requested or waited for this event (specified on the edges in our
of the software artifacts to formal analysis and synthesis. As we elab- example) are resumed, while the rest of the b-threads remain paused
orate in Section 11, most of the tools for BP and SBP rely on the for the next cycle. Back to our example, the specification in Fig. 1 does
mathematically rigorous nature of the semantics in providing tools not dictate an order in which actions are performed since the b-threads
for running formal analysis and synthesis algorithms. The addition do not block events of each other. Thus, any of the following runs are
of context improves the modularity of the specification, thus may possible: Cold–Cold–Hot–Hot–Cold–Hot, or Cold–Hot–Cold–Hot–Cold–
contribute each of the methods, as we demonstrate in Section 10.2. Hot, etc. This contrast with, say, imperative programming languages

2
A. Elyasaf Information and Software Technology 133 (2021) 106504

Fig. 1. A b-program that pour ‘Cold’ and ‘Hot’ water three times each, that consists of a single b-thread for each requirement. The b-threads are executed simultaneously, requesting,
and blocking events at each of their state (the 𝑅 and 𝐵 sets).

Fig. 3. The Interleave b-thread — ensures that two actions of the same type cannot
be executed consecutively, by blocking an additional request of ‘Cold’ until the ‘Hot’
is performed, and vice-versa.

without affecting the existing behaviors. While not all changes to a b-


program are purely additive, many useful changes are, as demonstrated
in [2].

2.1. The absence of context in BP

In this paper, the term context refers to information that can be


used to characterize the situation of system’s entities or processes. The
Fig. 2. The life cycle of a b-program (adapted from [1]). B-threads repeatedly execute
term ‘context awareness’ refers to the system’s ability to use contextual
an internal logic and then synchronize with each other, by submitting a synchronization information [10]. Examples for context-aware systems are, adaptive
statement to a central event arbiter. Once all b-threads have submitted their statements, system, ubiquitous systems, and mobile systems, as they all require the
the central event arbiter selects an event that was requested and was not blocked. ability to change behavior with respect to context.
B-threads that either requested or waited for this event are resumed, while the rest
Consider for instance, a context-aware version of the above hot–cold
remain paused for the next cycle.
example, with many rooms and taps. The system may have context-
dependent requirements that define different behaviors, depending on
the context, e.g., the type of the room, the person who uses the taps, etc.
(e.g., Java, C) that would have to dictate exactly when each action While it is possible to express these aspects without explicit reference
should be performed. Thus, traditional programming paradigms are to context, we will show that direct idioms for working with context
prone to over specification, while behavioral programming avoids it. allow to reuse the scenarios and to make them more aligned with how
While a specific order of actions was not required originally, this requirements are defined (which was the main design goal for BP).
behavior may represent a problem. Consider for example an additional All the implementations of BP that we are aware of, do not support
requirement that the client requested after running the initial version direct communication between b-threads (with an exception of LSC that
we discuss in Section 11). On the contrary, as elaborated in Section 3.1,
of the system:
the formal semantics of BP define that the only data shared among the
3. Two actions of the same type cannot be executed consecutively. b-threads — are the events. Yet, sharing the system context among
the b-threads, overrides this definition. Thus, in practice, describing
While we may add a condition before requesting ‘Cold’ and ‘Hot’, context-aware systems using BP forces the programmer to use some
the BP paradigm encourages us to add a new b-thread for each new ‘‘hacks’’, such as sharing data using global variables, which violates the
requirement. Thus, we add a third b-thread, called Interleave, formal definition and breaks the ability to formally verify the programs.
presented in Fig. 3. Another ‘‘hack’’ is to send the entire system context embedded in each
event, making a lot of redundant code and breaking the alignment
The Interleave b-thread ensures that there are no repetitions,
between the b-threads and the requirements.
by forcing an interleaved execution of the performed actions: ‘Hot’ is
blocked until ‘Cold’ is executed, and then ‘Cold’ is blocked until ‘Hot’ 3. Context-oriented behavioral programming
is executed. Note that this b-thread can be added and removed without
affecting other b-threads. This is an example of a purely additive change, To address this problem, we present Context-Oriented Behavioral
where the system behavior is altered to match a new requirement Programming (COBP) — an extension to the behavioral-programming

3
A. Elyasaf Information and Software Technology 133 (2021) 106504

paradigm with explicit idioms for defining and referencing the context.
As previously noted, this approach was first presented in [6], where
the Live Sequence Charts (LSC) language was extended with context
idioms, along with a methodology for developing context-aware sys-
tems using the extended language. In [4], a similar extension has
been made to BPjs — an environment for running behavioral programs
written in JavaScript [11]. In both cases, the semantics were defined by
translating the context idioms to the existing idioms of LSC and BPjs. In
this paper we generalize these extended languages by defining abstract
semantics (rather than translational semantics) and lay the foundations
for further research on formal analysis and synthesis.
In COBP, the system state incorporates the context of the system
that can be queried and updated. For example, in the context-aware
version of the hot–cold system, we may define the context to be the
entire building, including the rooms, the taps, the amount of hot/cold
units that need to be poured, and any additional required data. We will
also define queries on the context such as 𝑟𝑜𝑜𝑚 𝑤𝑖𝑡ℎ 𝑡𝑎𝑝𝑠 and kitchen,
that return a list of all rooms with taps and of all kitchens, respectively.
A b-thread in COBP is a context-aware b-thread, denoted as CBT, that
is bound to a certain query on the context. Whenever there is a new
result to the query, a new live copy of the CBT is spawned, with the
query result given as a local variable to the live copy. Thus, we refer to
this result as the seed of the live copy. Similar to a b-thread, a CBT also
specifies an aspect of the system behavior that is relevant to each new
seed that is generated, allowing to use its data, and to query and update
the context. Back to our extended hot–cold system, we can convert the
original three b-threads into CBTs and bind them to the appropriate
query (i.e., 𝑟𝑜𝑜𝑚 𝑤𝑖𝑡ℎ 𝑡𝑎𝑝𝑠). Thus, the queries represent both the context
Fig. 4. The life cycle of a context-aware b-program. Each context-aware b-thread (CBT)
of the requirements and the context of the CBTs. The complete example is bound to a query on the contextual data. Whenever a new answer exists for a query,
of the extended hot–cold system is given in Section 5. new live copies are spawned for the relevant CBTs. The live copies repeatedly execute
The life cycle of COBP contains the life cycle of BP with several an internal logic that may depend on the contextual data and then synchronize with
each other, by submitting a synchronization statement to a central event arbiter. Once
modifications, as depicted in Fig. 4:
all live copies have submitted their statements, the arbiter selects an event that was
requested and was not blocked. The event is passed to the Effect Function that may
• The live copies are the ones that are executed, and the CBTs
update the contextual data, depending on its specification. The (updated) contextual
spawn new live copies upon each new answer to their query. dataset is passed back to the CBTs, along with the selected event. All CBTs that either
• The internal logic of the live copies does not only depend on the requested or waited for this event are resumed, while the rest remain paused for the
last event, as in BP, but also on the context. next cycle.

• An effect function receives the selected event and updates the


contextual data according to its specification. Then, the selected
event and the updated context are transferred back to the live Definition 2 (Behavior Thread). A behavior thread over an event-
copies. set 𝐸 is a tuple ⟨𝑆, →, 𝑖𝑛𝑖𝑡, 𝑅, 𝐵⟩, where ⟨𝑆, 𝐸, →, 𝑖𝑛𝑖𝑡⟩ forms a labeled
transition system, 𝑅 ∶ 𝑆 → 2𝐸 is a function that associates each state
We now turn to define the abstract semantics of COBP. We begin with the set of events requested by the b-thread when in that state,
with the BP semantics, adopted from the definitions of [2], since the
and 𝐵 ∶ 𝑆 → 2𝐸 is a function that associates each state with the set of
COBP semantics extend them.
events blocked by the b-thread when in that state.

3.1. BP semantics Definition 3. [Runs of a Set of b-threads] The runs of a set of b-


threads {⟨𝑆𝑖 , →𝑖 , 𝑖𝑛𝑖𝑡𝑖 , 𝑅𝑖 , 𝐵𝑖 ⟩}𝑛𝑖=1 , all over the event-set 𝐸, is defined as
The definition outline of the BP semantics is as follows: The def- the runs of the labeled transition system ⟨𝑆, 𝐸, →, 𝑖𝑛𝑖𝑡⟩, where 𝑆 = 𝑆1 ×
𝑒
inition of a labeled transition system (LTS) is given in Definition 1. ⋯ × 𝑆𝑛 , 𝑖𝑛𝑖𝑡 = ⟨𝑖𝑛𝑖𝑡1 , … , 𝑖𝑛𝑖𝑡𝑛 ⟩, and → includes a transition ⟨𝑠1 , … , 𝑠𝑛 ⟩ ←→
←←
In Definition 2, we define a b-thread as a labeled transition system in ⟨𝑠1 , … , 𝑠𝑛 ⟩ if and only if
′ ′
which events at each state can be marked as requested or as blocked.
Finally, Definition 3, defines the two basic rules for executing a set of ⋃
𝑛 ⋀ ⋃
𝑛
𝑒∈ 𝑅𝑖 (𝑠𝑖 ) 𝑒∉ 𝐵𝑖 (𝑠𝑖 ) (1)
b-threads: (1) An event occurs if and only if it is requested by some 𝑖=1 𝑖=1
b-thread and is not blocked by any b-thread; (2) All b-threads affected ⏟⏞⏞⏞⏞⏞⏟⏞⏞⏞⏞⏞⏟ ⏟⏞⏞⏞⏞⏞⏟⏞⏞⏞⏞⏞⏟
e is requested e is not blocked
by a given event undergo a state transition when the event occurs.
and
Definition 1 (Labeled Transition System [12]). A labeled transition ⋀
𝑛
𝑒
system is a quadruple ⟨𝑆, 𝐸, →, 𝑖𝑛𝑖𝑡⟩, where 𝑆 is a set of states, 𝐸 is ←← 𝑠′𝑖 )
(𝑠𝑖 ←→ (2)
𝑖=1
a set of events, → is a subset of 𝑆 × 𝐸 × 𝑆 called a transition relation, ⏟⏞⏞⏞⏞⏟⏞⏞⏞⏞⏟
and 𝑖𝑛𝑖𝑡 ∈ 𝑆 is an initial state. The runs of such a transition system are b-threads react to events
𝑒1 𝑒2 𝑒𝑖
sequences of the form 𝑠0 ←←←←→ ← 𝑠𝑖 ⋯, where 𝑠0 = 𝑖𝑛𝑖𝑡, and for
← ⋯ ←←←→
← 𝑠1 ←←←←→ Note that for the sake of simplifying the presentation, our defi-
all 𝑖 = 1, 2, … , 𝑠𝑖 ∈ 𝑆, 𝑒𝑖 ∈ 𝐸, and ⟨𝑠𝑖−1 , 𝑒𝑖 , 𝑠𝑖 ⟩ ∈→ (this membership will, nitions are very similar to those presented in [2], but not identical.
𝑒𝑖
from now, be written as 𝑠𝑖−1 ←←←→ ← 𝑠𝑖 for shortening and for simplifying The difference is that [2] assigned a separate set 𝐸𝑖 to each b-thread

the notions). and defined the joint event-set as 𝐸 = 𝑛𝑖=1 𝐸𝑖 . With this, they could

4
A. Elyasaf Information and Software Technology 133 (2021) 106504

automatically add an implicit self-loop at each b-thread’s state for any 3.2.2. Execution semantics for a context-aware behavioral program
𝑒 ∉ 𝐸𝑖 (i.e., event that the b-thread is not aware of). Here, to simplify In BP, the b-threads are executed, however in COBP, CBTs are not
the definitions, we explicitly add to all of our examples an ‘‘otherwise’’ directly executed. Whenever an aspect of the context becomes active
self-loop to all b-thread states. (i.e., there is a new result to the query) — a new live copy (Definition 7)
of each of the CBTs that are bound to the context — is spawned,
3.2. COBP semantics
with the result of the query used as the seed of the live copy, passed
to it as a local variable. The execution semantics of a context-aware
We begin with the definition of a context-aware behavioral program
and continue with its execution semantics. behavioral program (Definition 8) define a new LTS, where its states
are composed of the active live copies and the state of the system
3.2.1. Context-aware behavioral program context. The transition function defines how events are selected, how
A context-aware behavioral program is composed of the context the context is affected by the selected event, and how live copies are
data structure with its management functions (Definitions 4 and 5), spawned based on changes of the system context.
together with a set of context-aware b-threads (Definition 6). A context-
aware b-thread (CBT) is a behavioral thread that is bound to a certain Definition 7 (A Live Copy of a Context-Aware Behavior Thread). A live
query on the context. Our definition for context is inspired by the copy (instance) of a context-aware behavior thread is a tuple ⟨cbt , 𝑠, 𝑐⟩
definition of [10] — information that can be used to characterize the where cbt = ⟨𝑆, →, init , 𝑅, 𝐵, query⟩ is a context-aware behavior thread,
situation of entities or processes in a system. 𝑠 ∈ 𝑆, and 𝑐 ∈ range(query). We refer to 𝑐 as the seed of the live
copy. To simplify the notations, we extend the definition of 𝑅 and
Definition 4 (Context, Queries, and Updates). CTX is a (possibly infi- 𝐵 (see Definition 2) to accept a live copy: 𝑅(⟨cbt , 𝑠, 𝑐⟩) = 𝑅(𝑠) and
nite) set of all possible contexts that the system is designed to be aware 𝐵(⟨cbt , 𝑠, 𝑐⟩) = 𝐵(𝑠).
of. At any given moment the system is in a context ctx ∈ CTX . The
management of the context is done by the sets QUERY and UPDATE,
Definition 8 (Runs of Context-Aware B-Threads). The runs of a set
where each member query ∈ QUERY is a function with dom(query) =
of context-aware b-threads over an event-set 𝐸, and a cbt-set CBT , is
CTX (and arbitrary range) and each member update ∈ UPDATE is a
function from CTX to CTX . Finally, ctx init denotes the initial context of defined as the runs of the LTS ⟨𝑆, 𝐸, →, 𝑖𝑛𝑖𝑡⟩, where:
the system. 1. 𝑆 = {⟨ctx, LC⟩ ∶ ctx ∈ CTX , LC is a set of live copies}
As said before, we envision a complex data structure representing 2. init = ⟨ctx 𝑖𝑛𝑖𝑡 , {⟨cbt , 𝑠, 𝑐⟩ ∶ cbt ∈ CBT , 𝑠 = init (cbt ),
the different aspects of the contextual data. The set CTX is a mathemat- 𝑐 ∈ query(cbt )(ctx init )}⟩
𝑒
ical representation of all possible states of this data structure. While it 3. → includes a transition ⟨ctx, LC⟩ ←→ ←← ⟨ctx ′ , LC ′ ⟩ if and only if
may read as if we only allow one context at a time for the whole system, ⋃ ⋀ ⋃
this context is actually a combination of many contextual aspects, as we (a) 𝑒 ∈ 𝑅(𝑙𝑐) 𝑒∉ 𝐵(lc)
lc∈LC lc∈LC
demonstrate in the examples below. ⏟⏞⏞⏞⏞⏞⏞⏟⏞⏞⏞⏞⏞⏞⏟ ⏟⏞⏞⏞⏞⏞⏞⏟⏞⏞⏞⏞⏞⏞⏟
In applications, we envision a language for querying and updating 𝑒 is requested 𝑒 is not blocked
the context state such as SQL or procedural code, as we will show. In (b) ctx ′ = effect (𝑒)(ctx)
this case, the result of a query can be, for example, a tuple in a table (c) LC ′ = LC ′run ∪ LC ′new where
or the number of people in a room. We therefore do not to restrict the
range of the 𝑞𝑢𝑒𝑟𝑦 function in our mathematical abstraction.
′ 𝑒, 𝑐𝑡𝑥′ , 𝑐
𝐿𝐶𝑟𝑢𝑛 = {⟨𝑐𝑏𝑡, 𝑠′ , 𝑐⟩ ∶ ⟨𝑐𝑏𝑡, 𝑠, 𝑐⟩ ∈ 𝐿𝐶 and 𝑠 ←←←←←←←←←←←←←←→ ← 𝑐𝑏𝑡 𝑠′ }
Definition 5 (The Effect Function). The connection between the events ⏟⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏟⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏟
that the system generates and the updates of the context are defined by running live copies (based on transition systems)
the function effect ∶ 𝐸 → UPDATE that maps events to context update
functions. and
{ }
Note that we separate the definition of the event from the definition ′ ⟨𝑐𝑏𝑡, 𝑖𝑛𝑖𝑡(𝑐𝑏𝑡), 𝑐⟩ ∶ 𝑐𝑏𝑡 ∈ 𝐶𝐵𝑇 ,
𝐿𝐶𝑛𝑒𝑤 = ′
of its effect to enforce a separation of concerns between behavioral 𝑐 ∈ 𝑞𝑢𝑒𝑟𝑦(𝑐𝑏𝑡)(𝑐𝑡𝑥 ) ⧵ 𝑞𝑢𝑒𝑟𝑦(𝑐𝑏𝑡)(𝑐𝑡𝑥)
⏟⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏟⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏟
aspects and data aspects. spawned live copies (based on new query results)

Definition 6 (A Context-Aware Behavior Thread). A context-aware be-


havior thread (cbt) over an event-set 𝐸 is a tuple ⟨𝑆, →, init , 𝑅, 𝐵, query⟩,
3.3. A short discussion
where 𝑆, 𝐸, and init are as defined in Definition 2, query ∈ QUERY is
a query that the cbt is bound to. Here, the transition relation → is a
subset of 𝑆 × CTX × range(query) × 𝐸 × 𝑆, meaning that the transition of Compared to the BP semantics, these semantics embed the state of
a contextual b-thread may be conditioned not only on the last event, the context in the system state and extend the transition function to
but also on the context at the time of the transition and on a query support the new state. Since the semantics formally specify the entire
result. Similarly, 𝑅 and 𝐵 can be conditioned, i.e., they are members system (i.e., context, behavior, and execution mechanism) — reasoning
of the set 𝑆 × CTX × range(query) → 2𝐸 . To simplify future notations, techniques can be applied on the complete system/model with no fur-
we define the functions init (cbt ) = init , and query(cbt ) = query. ther input (as elaborated and demonstrated in Section 10.2). Moreover,
Conceptually, CBTs play the same role as regular b-threads. The key the formal semantics, allow for generating different perspectives of the
addition is the ability to explicitly connect the behavior of the b-thread model, such as:
with the context and with the answer of the query that seeded the
• Context-behavior perspective: Represents relations between
b-thread. For example, in Chess, one can directly specify the castling
requirement: ‘‘(1) Neither king nor rook involved in castling may have contexts and behaviors, such as: ‘‘which behaviors are bound
moved from the original position; (2) There must be no pieces between to a certain context’’, ‘‘affected by the termination of a certain
the king and the rook’’.1 context’’, etc.
• Behavior-context perspective: Represents how behaviors affect
the context, e.g., which contexts queries can be affected by a
1
www.chesscoachonline.com/chess-articles/chess-rules. certain CBT.

5
A. Elyasaf Information and Software Technology 133 (2021) 106504

Fig. 5. A CBT (in LSC and JavaScript) that specifies that a room’s light should be turned on/off based on its occupancy. Since the scenario is bound to the NonemptyRoom
query (defined in the DAL), once a room (any room) becomes occupied, a new live copy of the scenario is spawned with the room given as the local variable 𝑟.

• Context-context perspective: Represents the relations between called BPjs [11]. In both implementations, context idioms (i.e., CBT,
different aspects of the context, such as: temporal (e.g., contexts effect function, etc.) are translated into idioms of the underline BP
day and night cannot be active simultaneously) and structural implementation.
(e.g., the building context is composed of rooms, a kitchen instance Both the PlayGo and the BPjs tools allow for scenarios (or b-
is also a room instance, etc.). threads) to share data objects between them. Yet, to avoid a violation
of the BP semantics, it is ‘‘well known’’ among BP developers that
These perspectives (and others), may ease the development process
scenarios are prohibited to indirectly alter the behavior of each other
by improving the readability, explainability, and correctness of the
by modifying shared objects. The COBP semantics address this issue by
model.
formalizing the connection between the data objects and the behavioral
Another interesting feature of the semantics is the process of context
specification. According to Definition 8, the change to 𝑐𝑡𝑥 during a
activation, i.e., adding a result to a query and spawning live copies. We
transition (i.e., Definition 8 [3.b]) must occur before advancing the set
note that only UPDATE functions may change the context, and they are
of live copies (i.e., Definition 8 [3.c]). Our implementations use shared
triggered only by the EFFECT function, that is triggered only upon se-
objects for maintaining the system context (i.e., 𝑐𝑡𝑥), and synchronize
lecting an event. Thus, while live copies are advanced simultaneously,
the access using the BP execution mechanism that chooses an event and
only one UPDATE function can be triggered during a system transition.
advances the b-threads.
Changes to the context may yield new results for one or more QUERY
functions and upon such a change, all the CBTs that are bound to these
3.4.1. System design
queries will spawn live copies simultaneously. For example, once a new
To increase the modularity and the separation of concerns of spec-
room of type kitchen is added to the context (either dynamically by
ifications, we adapt the multilayered architectural pattern. We note that
using the effect function mechanism or statically by adding it to the
according to the COBP semantics, the CBTs are unaware of the context
initial context), all CBTs that are bound to the 𝑟𝑜𝑜𝑚 𝑤𝑖𝑡ℎ 𝑡𝑎𝑝𝑠 query
schema, the UPDATE set, how each 𝑞 ∈ QUERY is defined, and how
and kitchen query spawn live copies simultaneously. This behavior is
the effect function is defined. This information represents data-related
desired if there is no special requirement for an order. If there is
aspects of the system, rather than behavioral, and the interface between
such a requirement, then the BP and COBP paradigms encourage us
the CBTs and the context is defined by the queries’ names and the
to specify this additional requirement with an additional CBT (like the
contract of the effect function (i.e., the effect of each event). With
third, interleave b-thread of the hot–cold example). Adhering to the
respect to these insights, we define the layers as follows:
formal semantics, our JavaScript implementation delicately deals these
nuances and others (elaborated below). 1. The business-logic layer (BLL) consists of the behavioral specifi-
The implementation of the event arbitrer, that continuously selects cation — the set of CBTs that specify the behavior of the system.
a requested and not blocked event, can be either naïve, i.e., select one When developing this layer, the programmer must be aware
randomly, or advanced, e.g., by using priorities, heuristics, learning, of which information is accessible from the context (i.e., the
etc. Again, this behavior is desired assuming that there is no special queries’ names and the structure of their results) and how events
requirement for ordering the events. Of course, such a degree of par- affect the context.
allelism may cause unpredictable behavior, and while the specification 2. The data-access layer (DAL) abstracts the context-related deci-
may be aligned to the requirements, there may be problems with the sions for the BLL. The contextual data is stored in a structured
requirements themselves. In order to deal with this problem, different dataset (e.g., a relational database, classes, etc.) and managed
reasoning approaches have been proposed for BP, as we elaborate in using a data-access layer (DAL). The DAL is defined by a ‘‘query
Section 11. We further demonstrate the process of context activation and command repository’’ and an effect function. The ‘‘query and
in the examples below. command repository’’ manages the contextual data using a high-
level query language (e.g., SQL, methods, etc.). The context’s
3.4. Implementations ‘select’ queries allow for triggering a stored procedure whenever
a record is added or removed from its result (in analogy to
In this section, we describe two COBP implementations and discuss ‘‘database views’’), and the context’s ‘update’ commands update
their relation to the semantics. The first one is based on the PlayGo the data as required (by adding, deleting, and changing objects
implementation of LSC [13] and is fully described in [6]. The second and object relations). Based on the selected event, the effect
implementation [4] is based on a JavaScript implementation of BP, function uses the ‘update’ commands for changing the context.

6
A. Elyasaf Information and Software Technology 133 (2021) 106504

To simplify the notations of the examples below, we define the 5. Example: A context-aware hot–cold system
effect of all events as the identity function (i.e., they do not
change the context), unless explicitly specified otherwise. We now demonstrate how the extended hot–cold system can be
3. The application (or service) layer defines the interaction be- implemented using the abstract semantics. We begin with describing
tween the BLL and the environment (e.g., a GUI, network mes- the system requirements:
sages, etc.). This interaction is already defined in BP by using
a publish–subscribe mechanism, where external, environmental 1. A building has different room types, such as: kitchen, bathroom,
events are selected only at a super step, i.e., when there are bedroom, living room, hall, etc.
no more internal events to select. Similarly, the environment 2. Kitchens and bathrooms have a button and a hot and a cold taps.
may listen to internal events and act upon them (e.g., trigger 3. For each room with taps:
actuators). The complete mechanism is elaborated in [2].
(a) When the button is pressed, pour some small amount of
The multilayered architecture facilitates the separation of concerns cold water three times.
between the layers, and by binding b-threads to queries, the modularity (b) When the button is pressed, pour some small amount of
of the behavioral specification is increased. Fig. 5 depicts how CBTs are hot water three times.
specified using this design. In the examples and case studies below, we
follow this design and separate each implementation into three sections 4. For each kitchen — two pouring actions of the same type cannot
— Context Specification (for the DB schema), Data-Access Layer, and be executed consecutively.
Behavioral Specification.
We note that requirements 3 and 4 define the desired system behav-
3.4.2. Spawning an terminating live copies ior for each room-with-taps/kitchen (respectively). Requirements 1 and
PlayGo includes a mechanism for spawning live copies upon 2 define data constraints on the system or data aspects of the system,
changes to data objects, allowing us to use it for dynamically activating thus define the schema of the system context rather than its behavior.
and terminating CBTs’ live copies. BPjs does not have such mecha- We also note that the system context is static and does not change
nism, though it can be created by adding a b-thread that waits for throughout the lifetime of this system. Of course, this is not always true
contextual-data updates and then requests an event that contains a list as requirements may depend on dynamic changes to the context, as we
of new/ended results to the queries. This event is used for spawning demonstrate in Section 6. For example, a requirement may depend on
and terminating live copies, as elaborate next. personal preferences (e.g., whenever Joe uses the kitchen’s taps — pour
We implement CBT as a function that registers a regular b-thread only two units), room temperature (e.g., do not pour hot water when
(see Listing 1). The b-thread waits for new-results announcement and the room temperature is high), etc.
registers another b-thread for each result (for executing 𝑓 𝑢𝑛𝑐 in paral-
lel), with the new answer given as a parameter.
5.1. Implementation
bp.registerCBT = function(name, query, func) {
bp.registerBThread("cbt: " + name, function() { We define the possible events to be 𝐸 = {Push𝑖 , Hot 𝑖 , Cold 𝑖 ∶ 𝑖 ∈ N},
while(true) { where 𝑖 represents the 𝑖th room, Push𝑖 represents pushing the room’s
bp.sync({ waitFor: CTX.NewResults(query)})
button, and Hot 𝑖 ∕Cold 𝑖 represents pouring hot/cold (respectively) wa-
.data.forEach(c =>
bp.registerBThread( ter.
"Live copy: " + name + " " + c.id,
function() { func(c); }); ); Context specification
}}); } • RoomType = {kitchen, bathroom, living room, …} is a set of all room
types.
Listing 1: The implementation of a CBT in BPjs.
• The 𝑖th room in the building is represented by room𝑖 = ⟨𝑖, type𝑖 ⟩,
In some cases, a live-copy should terminate whenever its seed where 𝑖 ∈ N is the room number and type𝑖 ∈ RoomType represents
no longer answers its query. In Chess, for example, live copies that the type of the room.
handle a piece’s behavior are no longer relevant once the piece is • The set of all possible system contexts, CTX , is defined as the set of
captured. The implementations and semantics of BP and COBP allow all possible rooms — {room𝑖 ∶ 𝑖 ∈ N}.
for b-threads/live copies to terminate themselves. Thus, live copies
may listen to the aforementioned announcement event and terminate
Data-access layer
themselves. This behavior can be either explicitly specified for certain
As noted before, the behavioral requirements depend on two aspects
states, or it can be implicitly applied to all. While the latter may be
of the context — ‘room with taps’ and ‘kitchen’. Therefore, the DAL has
preferred when the ‘‘certain states’’ are all of them, caution is required
since live copy may need to release resources or do some actions before the following two queries:
terminating. • RoomWithTaps = {⟨𝑖, type𝑖 ⟩ ∶ 𝑖 ∈ N ∧ type𝑖 ∈
{𝑘𝑖𝑡𝑐ℎ𝑒𝑛, 𝑏𝑎𝑡ℎ𝑟𝑜𝑜𝑚}}.
4. Examples: Motivations and overview
• Kitchen = {⟨𝑖, type𝑖 ⟩ ∶ 𝑖 ∈ N ∧ type𝑖 = kitchen}.
To demonstrate how context-aware systems can be specified, ex- The queries’ names are used by the CBTs as an abstraction for the
ecuted, and verified, using the abstract semantics, we now present queries. Thus, future changes to the context specification (e.g., due to
two toy examples that are given here merely for understanding these additional requirements) will not affect the definitions of the CBTs.
concepts. For each example, we demonstrate its ‘‘execution’’ using the
Since the system context is static and does not change, the effect
formal semantics, showing how the context and the live copies change
function for all events is the identity function.
over time.
While here we implement the examples abstractly, they have a
JavaScript implementation as well, that can be downloaded and ex- Behavioral specification (CBTs)
ecuted from https://github.com/bThink-BGU/Papers-2020-COBP. Fol- We translate the b-threads of Section 2 to CBTs, binding the hot/-
lowed by these examples, we present two real-life systems developed cold b-threads to the RoomWithTaps query, and the interleave b-thread
using our JavaScript implementation (Sections 8 to 10). to the kitchen query:

7
A. Elyasaf Information and Software Technology 133 (2021) 106504

CBT Cold ∶ Query=RoomWithTaps Table 1


𝐵𝑇𝐶𝑜𝑙𝑑 = The succinctness of a COBP specification for the extended hot–cold example, compared
to a BP specification.
otherwise
# of # of # b-threads # CBTs
bathrooms kitchens (BP) (COBP)
𝑅 = {Cold 𝑖 } 0 0 0 3
Cold 𝑖 𝐵=∅ Cold 𝑖 1 0 2 3
0 1 3 3
1 1 5 3
Push𝑖 Cold 𝑖 2 1 7 3
𝑅=∅ 𝑅 = {Cold 𝑖 } 𝑅 = {Cold 𝑖 }
start 2 2 10 3
𝐵=∅ 𝐵=∅ 𝐵=∅ 10 10 50 3

otherwise otherwise otherwise


a similar BP code will have two b-threads for each room with taps and
CBT Hot ∶ Query=RoomWithTaps an additional b-thread for each kitchen. Table 1 shows the correlation
𝐵𝑇𝐻𝑜𝑡 = in BP between the number of rooms and the code length, as opposed
otherwise to COBP, where the code length is unaffected.

Formal verification. Harel et al. [14] showed how verification of be-


𝑅 = {Hot 𝑖 } havioral programs can be automated and streamlined by combining
Hot 𝑖 𝐵=∅ Hot 𝑖 properties of individual modules, specified and verified separately.
They demonstrated how their method may yield an exponential accel-
eration of the verification process when compared with model-checking
𝑅=∅ Push𝑖 𝑅 = {Hot 𝑖 } Hot 𝑖 𝑅 = {Hot 𝑖 }
start the composite application.
𝐵=∅ 𝐵=∅ 𝐵=∅ In some cases, the context idioms generate individual modules that
allow for using the compositional verification approach of [14] for
otherwise otherwise otherwise verifying the behavior of a context-aware behavioral program. In this
example, each answer to each of the two queries creates a set of live
copies (two for a bathroom and three for a kitchen). According to the
CBT Int ∶ 𝑄𝑢𝑒𝑟𝑦 = 𝐾𝑖𝑡𝑐ℎ𝑒𝑛 implementation, each set uses its own set of events (on the edges, in 𝑅,
𝐵𝑇𝐼𝑛𝑡 = or in 𝐵) — {Push𝑖 , Hot 𝑖 , Cold 𝑖 ∶ 𝑖 ∈ N}. In addition, the effect function
Cold 𝑖 does not change the context. Thus, each set is an independent module
that does not affect the behavior of other sets.
𝑅=∅ 𝑅=∅ Based on these observations, to verify the consistency of the pro-
start start gram behavior with the kitchens’ interleave requirement (requirement
𝐵 = {Hot 𝑖 } 𝐵 = {Cold 𝑖 }
4), it is sufficient to use one kitchen only. For that, we will show
that for a single kitchen, the LTS of Definition 8 is equivalent to
Hot 𝑖
the LTS of Definition 3. Since it is possible to verify behavioral pro-
grams, it is also possible to verify this program. Given the initial state
5.2. Execution demonstrations ⟨{⟨1, kitchen⟩}, {LC Cold,1 , LC Hot ,1 , LC Int ,1 }⟩, Definition 8 is equivalent to
Definition 3, since: (1) Definition 8[3.a] ≡ Definition 3[1]; (2) ctx ′ =
For demonstrating the execution of the above program, we denote effect (𝑒)(ctx) = ctx; (3) LC ′ = LC ′run ; and (4) LC ′run ≡ Definition 3[2].
LC 𝑋,𝑖 as a live copy of CBT 𝑋 for room 𝑖, where 𝑋 ∈ {Cold, Hot , Int }. This simple example shows how a COBP program can be verified us-
We note that while 𝑖 is a parameter in the definition of the LTS of each ing the abstract semantics. In addition it shows how the context idioms
CBT, when the live copies are spawned, their seed (i.e., a result to the increase the modularity of the program, thus allow for exponential ac-
CBT’s query) contains the value of 𝑖. celeration of the verification process. In Section 9.2 we demonstrate the
In this example, we assume that there are three rooms: a kitchen,
verification process of COBP program written in JavaScript, and in Sec-
a bathroom, and a bedroom. We define our initial context to be
tion 11 we survey additional reasoning techniques for scenario-based
{⟨1, kitchen⟩, ⟨2, bathroom⟩, ⟨3, bedroom⟩}, and our initial live copies are
programming.
thus: {LC Cold,1 , LC Hot ,1 , LC Int ,1 , LC Cold,2 , LC Hot ,2 }. Each live copy uses a
different subset of events, meaning that the behavior of each room with
6. Example: The game of life
taps is independent with the behavior of other rooms. Therefore, we
note two observations:
The Game of Life, or simply Life, is a zero-player game based on a
1. The interleave CBT is bound to the Kitchen query. Thus, upon cellular automaton, devised by Conway in 1970 [15]. The game board
pushing the button of the kitchen and the bathroom, the is an infinite, two-dimensional orthogonal grid of cells, where each
kitchen’s Hot/Cold events (Cold 1 and Hot 1 ) will be interleaved, cell can be either populated with an individual or unpopulated. Each
and the bathroom’s hot/cold events (Cold 2 and Hot 2 ) will not. individual interacts only with its neighbors, that is, individuals that
2. There are no constrains on the order of events between the dif- are in one of the eight cells adjacent to it. The user sets the initial
ferent rooms. Thus, for example, the following order is possible: population of the game. Then, the following four rules are applied to
Push1 , Cold 1 , Push2 , Hot 2 , Hot 1 , Hot 2 , Cold 1 , Hot 1 , Cold 2 , the individuals of the first generation to generate the population of the
Cold 1 , Hot 2 , … first generation:

5.3. A short discussion 1. Any individual with fewer than two neighbors — dies — as if by
underpopulation.
Succinctness. In some cases, COBP specifications are more succinct 2. Any individual with two or three neighbors — lives on to the
than BP specifications. In this example, we had three CBTs only, while next generation.

8
A. Elyasaf Information and Software Technology 133 (2021) 106504

3. Any individual with more than three neighbors — dies — as if • reproduce(row, col)(⟨Pop, Tick⟩) = ⟨Pop ∪ {⟨row, col⟩}, Tick⟩, is the
by overpopulation. effect of the event reproduce(row, col), adding the reproduced
4. Any three individuals that are the only ones that surrounds an individual to the population.
unpopulated cell — reproduce an individual at that cell. • tick(⟨Pop, Tick⟩) = tock(⟨Pop, Tick⟩) = ⟨Pop, 1 − Tick⟩, are the effects
of the events tick and tock.
All rules are applied simultaneously to all of the individuals —
births and deaths occur simultaneously, at a discrete moment called
Behavioral specification (CBTs)
a tick. The rules are repeatedly applied to create further generations.
For each rule, we define a context-aware b-thread, called CBT 𝑖 as
We note that each requirement depends on a different aspect of the
the CBT for the 𝑖th rule, where 𝑄𝑖 is the definition of its query, and
context: for the first requirement — ‘‘individual with fewer than two
BT 𝑖 is the definition for its tuple ⟨𝑆, →, init , 𝑅, 𝐵⟩.
neighbours’’, for the second requirement — ‘‘individual with two or
three neighbours’’, and so on. CBT 1 ∶ 𝑄𝑢𝑒𝑟𝑦 = 𝑄1
𝐵𝑇1 =
6.1. Implementation
𝑅 = die(row,col) die(row,col) 𝑅=∅
start
We define the possible events as 𝐸 = {die(row,col), reproduce 𝐵 = {tick} 𝐵=∅
(row,col), tick, tock ∶ row, col ∈ N}, where the events die(row, col) and
reproduce(row,col) represent the death and reproduce (respectively) of
otherwise
an individual at the cell ⟨row,col⟩. Finally, to synchronize the creation
of live copies we used tick to represent the state of the system at the CBT 2 ∶ 𝑄𝑢𝑒𝑟𝑦 = 𝑄2
beginning moment of a generation, and tock to represent the rest of the
𝐵𝑇2 =
system states.
𝑅=∅
start
Context specification 𝐵=∅
• We define the set of all possible system contexts, CTX , to be
{⟨Pop, Tick⟩ ∶ Pop ⊆ {⟨row, col⟩ ∶ row, col ∈ N}, Tick ∈ {0, 1}}, CBT 3 ∶ 𝑄𝑢𝑒𝑟𝑦 = 𝑄3
where the population (represented by Pop) is a set of locations 𝐵𝑇3 =
of all living individuals, and Tick = 1 if and only if all of the die(row,col)
𝑅 = die(row,col) 𝑅=∅
individuals have finished processing their rules for the current start
𝐵 = {tick} 𝐵=∅
generation, and the rules-processing of the following generation
has not yet started.
otherwise
• The set of all cells that can be reached from the cell ⟨row,col⟩
in one step, is defined by the function ngb(row,col) = {⟨row + CBT 4 ∶ 𝑄𝑢𝑒𝑟𝑦 = 𝑄4
1, col⟩, ⟨row +1, col+1⟩, ⟨row, col+1⟩, ⟨row −1, col+1⟩, ⟨row −1, col⟩,
𝐵𝑇4 =
⟨row-1, col-1⟩, ⟨row, col − 1⟩, ⟨row + 1, col − 1⟩}.
otherwise

Data-access layer
As noted before, each requirement is bound to a different context. 𝑅 = reproduce(row,col)
start
Therefore, for each context we define a different query, labeling it by 𝐵 = {tick}
the requirement ID:
reproduce(row,col)
⎧⎧ ⎫
⎪⎪ ⟨𝑟𝑜𝑤, 𝑐𝑜𝑙⟩ ∶ ⎪
⎪ ⟨𝑟𝑜𝑤, 𝑐𝑜𝑙⟩ ∈ 𝑃 𝑜𝑝 𝑅=∅
𝑄 1 = ⎨⎨⎪
⎬, 𝑡𝑖𝑐𝑘 = 1
⎪ 𝐵=∅
⎪⎩ ∧ |𝑛𝑔𝑏(𝑟𝑜𝑤, 𝑐𝑜𝑙) ∩ 𝑃 𝑜𝑝| < 2 ⎭
⎪∅ , otherwise
⎩ To synchronize the generation tick, we define:
⎧⎧ ⎫
⎪⎪ ⟨𝑟𝑜𝑤, 𝑐𝑜𝑙⟩ ∶ ⎪ CBT 𝑡𝑖𝑐𝑘 𝑄𝑢𝑒𝑟𝑦 = 𝑄𝑡𝑖𝑐𝑘
⎪ ⟨𝑟𝑜𝑤, 𝑐𝑜𝑙⟩ ∈ 𝑃 𝑜𝑝
𝑄 2 = ⎨⎨⎪
⎬, 𝑡𝑖𝑐𝑘 = 1

𝐵𝑇𝑡𝑖𝑐𝑘 =
⎪⎩ ∧ 2 ≤ |𝑛𝑔𝑏(𝑟𝑜𝑤, 𝑐𝑜𝑙) ∩ 𝑃 𝑜𝑝| ≤ 3 ⎭ tick
⎪∅ , otherwise

𝑅 = {𝑡𝑖𝑐𝑘} 𝑅 = {𝑡𝑜𝑐𝑘}
⎧⎧ ⎫ start
⎪⎪ ⟨𝑟𝑜𝑤, 𝑐𝑜𝑙⟩ ∶ ⎪
𝐵=∅ 𝐵 = 𝐸 ⧵ {𝑡𝑜𝑐𝑘}
⎪ ⟨𝑟𝑜𝑤, 𝑐𝑜𝑙⟩ ∈ 𝑃 𝑜𝑝
𝑄 3 = ⎨⎨⎪
⎬, 𝑡𝑖𝑐𝑘 = 1

⎪⎩ ∧ |𝑛𝑔𝑏(𝑟𝑜𝑤, 𝑐𝑜𝑙) ∩ 𝑃 𝑜𝑝| > 3 ⎭ tock
otherwise otherwise
⎪∅ , otherwise

⎧⎧ ⎫ 6.2. Execution demonstrations
⎪⎪ ⟨𝑟𝑜𝑤, 𝑐𝑜𝑙⟩ ∶ ⎪
⎪ ⟨𝑟𝑜𝑤, 𝑐𝑜𝑙⟩ ∉ 𝑃 𝑜𝑝
𝑄 4 = ⎨⎨⎪
⎬, 𝑡𝑖𝑐𝑘 = 1
⎪ We now demonstrate the execution of the program with different
⎪⎩ ∧ |𝑛𝑔𝑏(𝑟𝑜𝑤, 𝑐𝑜𝑙) ∩ 𝑃 𝑜𝑝| = 3 ⎭ initial populations. We do that by presenting how the context and the
⎪∅ , otherwise
⎩ live copies change over the generations. For each generation 𝑖, we
present the set of the live copies at their initial state, denoted by LC𝑖 ,
The effect function is:
and the state of the context at the beginning of the generation, denoted
• die(row, col)(⟨Pop, Tick⟩) = ⟨Pop ⧵ {⟨row, col⟩}, Tick⟩, is the effect by 𝑐𝑡𝑥𝑖 . Given 𝑛𝑎𝑚𝑒 ∈ {1, 2, 3, 4, 𝑡𝑖𝑐𝑘}, we denote LC 𝑛𝑎𝑚𝑒,⟨𝑟𝑜𝑤,𝑐𝑜𝑙⟩ =
of the event die(row, col) that removes the individual from the ⟨CBT 𝑛𝑎𝑚𝑒 , 𝑄𝑛𝑎𝑚𝑒 , ⟨𝑟𝑜𝑤, 𝑐𝑜𝑙⟩⟩ as the live copy of CBT 𝑛𝑎𝑚𝑒 where the result
population. of 𝑄𝑛𝑎𝑚𝑒 (i.e., the seed — 𝑐), is ⟨𝑟𝑜𝑤, 𝑐𝑜𝑙⟩.

9
A. Elyasaf Information and Software Technology 133 (2021) 106504

7.1. Implementation

The mating dance involves eight ‘dancing’ steps of three lonely


individuals around an unpopulated cell ⟨𝑟𝑜𝑤, 𝑐𝑜𝑙⟩, until they complete
a circle. We represent the dancing step of the three individuals with the
event 𝑠𝑡𝑒𝑝(𝑟𝑜𝑤, 𝑐𝑜𝑙), that is added to the previously defined event-set (in
Section 6.1).
Fig. 6. A mating dance. The three, lonely gray individuals surround the unpopulated
One way to implement the B requirements, is to add a condition
cell at the center. At each of the following eight generations, the three individuals
will move one step along the arrows, from one cell to another, until returning to their to each of the CBTs of the original system, that validates that the
original position, completing the mating dance. Then, they will reproduce an individual individual does not participate in a mating dance. We will take a
at the center cell. more subtle approach that is made possible by the COBP paradigm.
Specifically, since only the context of the original requirements has
changed, and the behavior did not, we use the original CBTs and only
Two lonely individuals. In this example, the seed generation has two change their queries to exclude the case of a mating dance.
individuals that are not neighbors. According to the rules, they must
die in the following iteration, i.e., the answer for 𝑄1 contains the two
individual (and only them): Context specification
No changes.
ctx 0 = ⟨{⟨5, 5⟩ ⟨10, 10⟩}, 0⟩
LC0 = {CBT tick , LC 1,⟨5,5⟩ , LC 1,⟨10,10⟩ }
Data-access layer
LC1 = ∅
To simplify 𝑄𝐴 , we define the function isLonely that receives a cell
Three individuals in a row (Blinker). There are interesting patterns and returns true iff it has no neighbors: isLonely(row, col) = 𝑡𝑟𝑢𝑒 ⟺
in Life, categorized by the behavior of the individuals. The oscillators (|ngb(row, col) ∩ Pop| = 0).
category includes patterns that the individuals return to their initial Our queries are then:
state after a finite number of generations. One of these patterns is
⎧⎧ ⟨row, col⟩ ∶ ⎫
the Blinker, where three individuals are ordered in a horizontal line, ⎪⎪ ⎪
⎪⎪ ⟨row, col⟩ ∉ Pop
with no empty cells between them. On even generations the individuals ⎪
⎪⎨ ∧ |ngb(row, col) ∩ Pop| = 3 ⎬, 𝑡𝑖𝑐𝑘 = 1
return to their initial state, and on odd generations the individuals • 𝑄𝐴 = ⎨⎪ ⎪
⎪⎪ ∧ ∀⟨𝑖, 𝑗⟩ ∈ ngb(row, col) ∩ Pop ∶
change to a vertical position. Thus, the execution will be: ⎪
⎪⎩ 𝑖𝑠𝐿𝑜𝑛𝑒𝑙𝑦(𝑖, 𝑗) ⎭
⎪∅ , otherwise
ctx 2𝑖 = ⟨{⟨5, 4⟩ ⟨5, 5⟩ ⟨5, 6⟩}, 0⟩ ⎩
LC2𝑖 = { CBT tick , LC 1,⟨5,4⟩ , LC 2,⟨5,5⟩ , LC 1,⟨5,6⟩ , LC 4,⟨4,5⟩ , LC 4,⟨6,5⟩ } • For each of the original queries in , we add the following constraint to
make sure that the individuals do not participate in a mating dance:
ctx 2𝑖+1 = ⟨{⟨4, 5⟩ ⟨5, 5⟩ ⟨6, 5⟩}, 0⟩
∄⟨𝑖, 𝑗⟩ ∈ 𝑄𝐴 ∶ ⟨row, col⟩ ∈ ngb(𝑖, 𝑗). The new queries are:
LC2𝑖+1 = {CBT tick , LC 1,⟨4,5⟩ , LC 2,⟨5,5⟩ , LC 1,⟨6,5⟩ , LC 4,⟨5,4⟩ , LC 4,⟨5,6⟩ }
⎧⎧ ⎫
⎪⎪ ⟨row, col⟩ ∶ ⎪
7. Example: An evolved game of life ⎪⎪ ∄⟨𝑖, 𝑗⟩ ∈ 𝑄𝐴 ∶ ⟨row, col⟩ ∈ ngb(𝑖, 𝑗) ⎪

𝑄𝐵1 = ⎨⎨⎪ ∧ ⟨row, col⟩ ∈ Pop ⎬, 𝑡𝑖𝑐𝑘 = 1

While the CBTs for the game rules demonstrate the concept of ⎪⎪ ∧ |ngb(row, col) ∩ Pop| < 2 ⎪
⎪⎩ ⎭
context, they consist of a single state, thus missing the ‘scenario’ trait ⎪∅ , otherwise

of BP.
Consider for example the following new requirements for the game ⎧⎧ ⎫
⎪⎪ ⟨row, col⟩ ∶ ⎪
(in analogy to the Laws of Robotics by Asimov [16]): ⎪⎪ ∄⟨𝑖, 𝑗⟩ ∈ 𝑄𝐴 ∶ ⟨row, col⟩ ∈ ngb(𝑖, 𝑗) ⎪

𝑄𝐵2 = ⎨⎨⎪ ∧ ⟨row, col⟩ ∈ Pop ⎬, 𝑡𝑖𝑐𝑘 = 1

A. Any three lonely individuals (i.e., individuals with no neigh- ⎪⎪ ∧ 2 ≤ |ngb(row, col) ∩ Pop| ≤ 3 ⎪
bors) that are the only ones that surround an unpopulated ⎪⎩ ⎭
⎪∅ , otherwise
cell — perform the mating dance — a complete clockwise cir- ⎩
cling around the unpopulated cell (depicted in Fig. 6). Upon ⎧⎧ ⎫
completion, the three reproduce an individual at that cell. ⎪⎪ ⟨row, col⟩ ∶ ⎪
⎪⎪ ∄⟨𝑖, 𝑗⟩ ∈ 𝑄𝐴 ∶ ⟨row, col⟩ ∈ ngb(𝑖, 𝑗) ⎪
B. otherwise, the original rules are valid: ⎪
𝑄𝐵3 = ⎨⎨⎪ ∧ ⟨row, col⟩ ∈ Pop ⎬, 𝑡𝑖𝑐𝑘 = 1

1. Any individual with fewer than two neighbors — dies — ⎪⎪ ∧ |ngb(row, col) ∩ Pop| > 3 ⎪
as if by underpopulation. ⎪⎩ ⎭
⎪∅ , otherwise
2. Any individual with two or three neighbors — lives on to ⎩
the next generation. ⎧⎧ ⎫
3. Any individual with more than three neighbors — dies — ⎪⎪ ⟨row, col⟩ ∶ ⎪
⎪⎪ ∄⟨𝑖, 𝑗⟩ ∈ 𝑄𝐴 ∶ ⟨row, col⟩ ∈ ngb(𝑖, 𝑗) ⎪
as if by overpopulation. ⎪
4. Any three individuals that are the only ones that sur- 𝑄𝐵4 = ⎨⎨⎪ ∧ ⟨row, col⟩ ∉ Pop ⎬, 𝑡𝑖𝑐𝑘 = 1

⎪⎪ ∧ |ngb(row, col) ∩ Pop| = 3 ⎪
rounds an unpopulated cell — reproduce an individual at ⎪⎩ ⎭
that cell. ⎪∅ , otherwise

We note that rule A defines a new context-dependent requirement, To the effect function we add an effect for the step(row,col) event,
while B rules only refine the context of the original rules. that advances the neighbors to their next dance location:

10
A. Elyasaf Information and Software Technology 133 (2021) 106504

for each one of them. Thus, for simplification, we denote the indi-
viduals as block = {⟨5, 0⟩, ⟨5, 1⟩, ⟨6, 0⟩, ⟨6, 1⟩}, and their live copies as
LCblock = {LC 𝐵2,⟨5,0⟩ , LC 𝐵2,⟨5,1⟩ , LC 𝐵2,⟨6,0⟩ , LC 𝐵2,⟨6,1⟩ }.

Generation 0:
ctx 0 = ⟨{⟨0, 1⟩, ⟨2, 0⟩, ⟨2, 2⟩} ∪ block, 0⟩
LC0 = {CBT tick , LC 𝐴,⟨1,1⟩ } ∪ LCblock

Generation 1:
ctx 1 = ⟨{⟨0, 1⟩, ⟨1, 1⟩, ⟨2, 0⟩, ⟨2, 2⟩} ∪ block, 0⟩
LC1 = { CBT tick , LC 𝐵1,⟨0,1⟩ , LC 𝐵3,⟨1,0⟩ , 𝐿𝐶𝐵2,⟨1,1⟩ , LC 𝐵3,⟨1,2⟩ ,
LC 𝐵1,⟨2,0⟩ , LC 𝐵3,⟨2,1⟩ , LC 𝐵1,⟨2,2⟩ } ∪ LCblock

Generation 2:
𝑐𝑡𝑥2 = ⟨{⟨1, 0⟩, ⟨1, 1⟩, ⟨1, 2⟩, ⟨2, 1⟩} ∪ 𝑏𝑙𝑜𝑐𝑘, 0⟩
LC2 = {CBT 𝑡𝑖𝑐𝑘 , 𝐿𝐶𝐵3,⟨0,1⟩ , 𝐿𝐶𝐵1,⟨1,0⟩ , 𝐿𝐶𝐵2,⟨1,1⟩ ,
Fig. 7. The individuals (in gray) at the beginning of the first three generation of the 𝐿𝐶𝐵1,⟨1,2⟩ , 𝐿𝐶𝐵2,⟨2,1⟩ } ∪ LC𝑏𝑙𝑜𝑐𝑘
extended Game of Life example. For each cell/individual that one of the rules is valid
for — the rule number is stated. The block pattern is at the bottom of the grid, and 7.3. A short discussion
the mating-dance pattern is at the top of the grid at generation 0. The dancing takes
place during generation 0, and at the end of the dance, a new individual is spawned Our initial definition for requirement A did not require that the
at cell ⟨1, 1⟩.
three individuals will be lonely. When we implemented and run the
last example, we observed a bug — in some cases, during the mating
dance, the individuals have been duplicated and each copy stepped into
step(row,col)(⟨𝑃 𝑜𝑝, 𝑇 𝑖𝑐𝑘⟩) = ⟨(Pop ⧵ ngb(row,col)) ∪
⏟⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏟⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏟ a different cell. We added an assertion that checks this run property,
Remove old locations and because of the formal semantics of the COBP paradigm, we were
{next (row, col, 𝑖, 𝑗) ∶ ⟨𝑖, 𝑗⟩ ∈ ngb(row,col)) ∩ Pop}, Tick⟩ able to verify the existence of the bug. Moreover, we were able to
⏟⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏟⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏟ find an initial seed that causes the bug — when the three cells are
Add next locations
ordered in a vertical or a horizontal line, then they are neighbors of
where next (row, col, 𝑖, 𝑗) is a function that returns the consecutive cell two unpopulated cells (i.e., from the two sides of the line). In fact,
to ⟨𝑖, 𝑗⟩ in the mating dance circle. For example, next (row, col, row, we discovered that the bug was in the requirements which is why
col + 1) = ⟨row,col, row + 1, col + 1⟩, next (row, col, row + 1, col + 1) = we changed them to three lonely individuals. We provide a detailed
⟨row, col, row + 1, col⟩, and so forth. description of the verification process and related experiments that we
have conducted in Section 10.2.
Behavioral specification (CBTs)
8. Case studies: Motivation and overview
Since the behavior of the original CBTs did not change, only their
context, we only change the query names of the CBTs (i.e., 𝑄1 will now
We now turn to present two case studies of two different industrial
be 𝑄𝐵1 , 𝑄2 will now be 𝑄𝐵2 , etc.). We define the following additional
fields — robotics and the internet-of-things. In both case studies we
CBT for rule A:
developed the systems using our BPjs-based implementation, described
in Section 3.4.
CBT 𝐴 : 𝑄𝑢𝑒𝑟𝑦 = 𝑄𝐴
The purposes of these case studies are: to present an implementation
𝐵𝑇𝐴 =
of the paradigm and a syntax for the abstract semantics; to discuss addi-
otherwise otherwise
tional implementation details and design patterns; and to demonstrate
real-life use cases where the paradigm may excel other paradigms, both
𝑅 = {step(row,col)} step(row,col) 𝑅 = {step(row,col)} context oriented and not. To keep the focus of this paper, we only
start
𝐵 = {tick} 𝐵 = {tick} discuss the key differences between our implementation and possible
implementations in other paradigms and languages. Additional aspects
⋯ step(row,col) × 7 ⋯ are discussed in Section 11.
The contextual data is stored in a relational database (an in-memory
𝑅 = {step(row,col)} reproduce(row,col) 𝑅=∅ SQLite database2 ) and managed by a data-access layer (DAL) using
𝐵 = {tick} 𝐵=∅ the Hibernate ORM framework.3 In analogy to ‘‘database views’’, the
context’s ‘select’ queries allow for triggering a stored procedure when-
ever a record is added or removed from its result (i.e., announcing
otherwise
the changes via events and spawning live copies upon new records)
. The context’s ‘update’ commands update the data as required (by
adding, deleting, and changing objects and object relations). Query and
7.2. Execution demonstrations update commands are accessed by their IDs in the business-logic layer
(i.e., the behavioral specification defined by the CBTs), leaving the
context-related implementation decisions to the lower layer (i.e., the
Mating dance and still life. In this example, depicted in Fig. 7, we have
DAL and the DB).
two patterns. At the bottom of the grid, is the block pattern of the still
This implementation can be found at https://github.com/bThink-
life type. It is called ‘still life’ since it does not change over generations.
BGU/BPjs-Context and the following case studies can be found at https:
The second pattern is our new dancing pattern. We demonstrate the //github.com/bThink-BGU/Papers-2020-COBP.
run for three generations, presenting only the initial state of each
generation. The dance starts and completes during the first generation.
Since the individuals of the block pattern do not change over 2
SQlite –https://www.sqlite.org
3
generations, at each generation a new live copy of CBT 𝐵2 is generated Hibernate ORM — https://hibernate.org/orm.

11
A. Elyasaf Information and Software Technology 133 (2021) 106504

bool Turtlebot3Drive::controlLoop() {
switch(state){
case GET_TB3_DIRECTION:
if(distToObstacle[CENTER] > min_forward_dist){
if(distToObstacle[LEFT] < min_side_dist){
previous_position = position;
state = TB3_RIGHT_TURN;
}else if(distToObstacle[RIGHT] < min_side_dist){
previous_position = position;
state = TB3_LEFT_TURN;
}else { state = TB3_DRIVE_FORWARD; }
}
if(distToObstacle[CENTER] < min_forward_dist){
previous_position = position;
state = TB3_RIGHT_TURN;
} break;
case TB3_DRIVE_FORWARD:
Move(LINEAR_VELOCITY, 0.0);
state = GET_TB3_DIRECTION;
break;
Fig. 8. The TurtleBot3 world (credit: http://emanual.robotis.com). The Robot must not case TB3_RIGHT_TURN:
hit the walls while moving around. ...

Listing 2: Part of the tutorial code for the decision-making component


of the TurtleBot simulation.
9. Case study: A robotic operating system

Modern autonomous robots, such as smart manipulators and self-


driving cars and drones, run many parallel tasks such as obstacle walls (see Fig. 8). Part of the tutorial code for this decision-making
avoidance, exploration, mapping, and navigation. Concurrently, they component is presented in Listing 2, written in C++. This specific imple-
also need to plan ahead, do fault detection, and preserve their integrity. mentation raises many questions: Is it readable? Is it understandable?
Many service applications such as, e.g., home-assistance robots, surveil-
Can we easily adjust the code upon new requirements (e.g., do not
lance robotics, inspection, rescue robotics, or entertainment robotics
turn right more than three times in a row)? Can we reuse this code
require to achieve several goals at the same time. The goals may conflict
for different tasks (e.g., if we wish to both avoid walls and reach
with one another, and the significance of a task is frequently context
four coordinates in a certain order)? While there are better practices
dependent. For instance, in a car, avoiding a far obstruction may be of
for implementing this robot, a context-oriented approach has several
little significance relative to achieving a nearby target position.
advantages such as: a higher level of modularity of the behavioral
In this case study, we demonstrate how COBP can be used for
specification (i.e., behaviors are bound to contexts); a better alignment
developing decision-making components in ROS-based robotic systems.
to the requirements, a better agility (i.e., changing the context of a
The Robot Operating System (ROS) framework aims to simplify the
requirement only changes the context of the b-thread, a separation of
task of creating complex and robust robot behavior. At the lowest
level, ROS offers a message passing interface that provides an inter- concerns between the behavior and the data structure, etc.); and more.
process communication. On top of it, common robot-specific libraries
and tools are supplied to get the robot up and running quickly. While 9.1. Implementation
ROS simplifies the task of developing robots, it does not include built-
in tools for developing the complex and robust robot behaviors. Thus, The possible events are {move(𝑙, 𝑎), scan(⟨𝑑1 , … , 𝑑360 ⟩), CTX .
decision-making components are developed in various ways, such as
Ended(𝑞, 𝑐)}, where move represents moving forward the robot with a
coded using imperative languages (e.g., C++ or Python); modeled
linear velocity of 𝑙 and rotating it in with an angular velocity of 𝑎, scan
using third-party libraries, such as behavior-tree libraries (e.g., http:
represents the distances from the robots to obstacles in 360 degrees,
//wiki.ros.org/decision_making); or, learned by means of artificial in-
and CTX.Ended declares that 𝑐 is no longer the answer to query 𝑞.
telligence [17]. Behavior tree is a plan execution, describing the system
behavior by switching between a finite set of tasks [18]. They are
popular among robots developers and they are considered as a ‘‘very Context specification
efficient way of creating complex systems that are both modular and Since this problem is extremely simple, the context schema (that
reactive’’ [18]. While that may be true, some behaviors are defined defines CTX ) is specified by a single table, called robot , with four
more easily by describing what must not happen. Consider for example attributes — an id (primary key), and three numbers, called oAhead,
a robot, designed to do tasks while avoiding obstacles, or ignoring oLeft , and oRight , that represent the distance from the robot to an
certain actions when the battery is low. Adding such conditions may obstacle in that direction (if there is no obstacle, the value is infinite).
cause the tree to grow unwieldy. Refactoring conditions as hierarchy Since there is only one robot, the table will contain only one row,
nodes, or composing multiple trees, address the size problem, but may though it supports more.
cause additional problems as complex nodes and undesired behaviors.
To better capture the idea of how COBP can be used for developing
robots, we have implemented a COBP version of the decision-making Data access layer
component, taken from the official ROS tutorial.4 The component de- QUERY and UPDATE are defined in Table 2. The effect function of
fines how to move the robot around, while avoiding collision with the the scan event triggers a call to the update function SetObstacles with
the relevant data —
scan(⟨𝑑1 , ⋯ , 𝑑360 ⟩)(ctx) = SetObstacles({ "a":𝑑CENTER ,"l":
4
The official ROS tutorial http://wiki.ros.org/turtlebot3_simulations. 𝑑LEFT , "r":𝑑RIGHT }).

12
A. Elyasaf Information and Software Technology 133 (2021) 106504

Table 2 bp.registerCBT("GoToPowerSocket",
The ‘‘query and command’’ repository for the ROS case study.
"LowBattery", function(r) {
Type Name Command bp.sync({ request: bp.Event("NewTarget",
Q Robot SELECT * FROM robot { pos: socket_pos }) });
Q ObstacleAhead SELECT * FROM robot });
WHERE oAhead < min_forward_dist
Q ObstacleLeft SELECT * FROM robot // The result of the Delivery query has two ↩
WHERE oLeft < min_side_dist properties
Q ObstacleRight SELECT * FROM robot
WHERE oRight < min_side_dist // of type Target - source and target.
U SetObstacles UPDATE robot SET bp.registerCBT("Deliver", "Delivery", function(d) {
oAhead=:a, oLeft=:l, oRight=:r bp.sync({ request: newTarget(d.source) });
bp.sync({ waitFor: CTX.Ended("Target", d.source) });
bp.sync({ request: newTarget(d.target) });
bp.registerCBT("Movement", "Robot", function(r) { bp.sync({ waitFor: CTX.Ended("Target", d.target) });
while(true) });
bp.sync({ request:[
move(0.3, 0), /* move forward */ bp.registerCBT("GoToTarget", "Target", function(t) {
move(0, -1.5), /* turn left */ while(true) {
move(0, 1.5) /* turn right */] }); // calculate the moves for reaching the target.
}); var path = calcPath(t.robot, t.pos);
if(path.length == 0) {
bp.registerCBT("Avoid obstacles: ahead", // The TargetReached command ends the context ↩
"ObstacleAhead", function(r) { by
bp.sync({ block: move(0.3, 0), // deleting t from table Target.
waitFor: CTX.Ended("ObstacleAhead", r) }); bp.sync({ request: targetReached(t) });
}); break;
} else
bp.registerCBT("Avoid obstacles: left", bp.sync({ block: allMovesExcept(path[0]),
"ObstacleLeft", function(r) { waitFor: path[0]] });
bp.sync({ block: move(0, -1.5), }
waitFor: CTX.Ended("ObstacleLeft", r) }); });
});
Listing 4: Additional CBTs for the two new requirements: ‘‘when
bp.registerCBT("Avoid obstacles: right", the battery is low, the robot must reach the nearest power socket for
"ObstacleRight", function(r) { recharging’’, or ‘‘if the robot has a package to deliver, it must first take
bp.sync({ block: move(0, 1.5), it from the source location and then take it to its destination’’.
waitFor: CTX.Ended("ObstacleRight", r) });
});

Listing 3: The COBP version of the code in Listing 2. The method


This implementation is a bad practice since it breaks the context
bp.registerCBT registers a CBT where the parameters are: the name
abstraction. There is a difference between the sequence of events that
of the CBT, the query name, and the behavioral specification of the CBT
triggered the activation/deactivation the context, and the behavior of
given a seed 𝑟.
a system during the context. Consider for example a new requirement
that specifies that the robot can move backwards as well. In this case,
the context will end, however the live copy that waits for other, specific
movements — will remain blocked, which may lead to a deadlock.
Behavioral specification (CBTs)
Verification. The block idiom may lead to deadlocks in BP and COBP
The code in Listing 3 is the COBP implementation for the decision- programs. For example, if our robot will reach a corner while facing
making component. The ‘‘Movement’’ CBT specifies the possible moves it — all of the possible moves will be blocked and our program will
of the robot, by constantly requesting to move forward, turn right, reach a deadlock. This bug, of course, is in the requirements, and can
or turn left. The last three CBTs block linear and angular movements be solved by, e.g., allowing to move backwards. Yet, in more complex
in case the movement will cause the robot to collide an obstacle. systems it might not be trivial to detect such deadlocks. Furthermore,
Each of these CBTs is bound to an obstacle query (i.e., ObstacleAhead, the dynamic changes of the context may lead to additional unpredicted
ObstacleLeft , and ObstacleRight ), blocking the movement until the con- behaviors, a problem that is shared with the COP paradigm as well
text ends. We note that the scan event is triggered by ROS and is not (elaborated in Section 11). BPjs has a verification tool that we used
presented in this code. The execution engine of BPjs orchestrate the live to detect the deadlock. We elaborate on this tool in Section 10.2.
copies, driving the robot around while avoiding the walls.
Higher level of incrementallity and agility. The context idioms allow
9.2. A short discussion for adding new variations of the behavior under different contexts,
thus improving the agility of the program. Consider for example a
This case study demonstrated several advantages of the paradigm. new requirement: ‘‘when the battery is low, the robot must reach the
nearest power socket for recharging’’, or ‘‘if the robot has a package
Context activation vs. behavior. The ‘‘Avoid obstacles’’ CBTs block the
movement towards an obstacle as long as the context lasts. Another to deliver, it must first take it from the source location and then take
option to break the ‘blocking’ is to wait for other movements, for it to its destination’’. Handling such requirements after the system is
example: developed using a non-context-oriented approach, requires normally a
redesign of the code. The COBP paradigm on the other hand, allows us
bp.sync({ block: move(0, 1.5), to add these behavioral variation without changing the current CBTs,
waitFor: [move(0, -1.5),move(0.3, 0)] }); as demonstrated in Listing 4. The code assumes some changes to the

13
A. Elyasaf Information and Software Technology 133 (2021) 106504

schema — adding a batteryLevel attribute to the robot table and two new
tables, called Target and Delivery. In addition, there are changes to the
DAL — adding queries and command for retrieving and manipulating
the data of the new schema, as well as updating the effect function for
triggering the new UPDATE commands.

Comparison to COP. As we explained in Section 1, the layers in COP


are a language abstraction, grouping definitions of partial methods that
implement some fragment of an aspect of the system behavior [8]. The
layers and the COBP queries share the key concept of grouping the
behavioral variations. The name of the layer/query captures the context
of these variations, and the definition of the partial methods are like the
definitions of the CBTs. The differences though, reveal the some of the
key differences between the two paradigms (that we discuss here and
in Section 11):

• Code organization: One of the challenges in the design of context-


aware systems is organizing code of crosscutting aspects [9].
Context-dependent behaviors are often aspects that crosscut the
application logic. While the partial methods in COP handle the
aspects of the context-dependent behaviors, the other method
parts (of these partial methods) may handle other aspects. Thus,
it is difficult to organize the codebase without compromising
the maintainability and the separation of concerns. In COBP, the Fig. 9. A model of a specific context in a system and its relation to other contexts [19].
alignment between the requirements and the specification, allows The user explicitly specifies the relations, such as: implications, requirements, conjunc-
for a natural organization of the codebase. The queries are aligned tions, disjunctions, causality, and more. In COBP, any order is possible, unless the
requirements explicitly specify otherwise, which in that case, will be specified in the
to the contexts of the requirements (in our case study: robot,
behavioral layer using CBTs.
obstacles, etc.), and the CBTs are aligned to the requirements.
• Layer/Context activation: In COP, the layer activation mechanism
handles the composition of the partial methods of the activated
layers. Such a composition is hard to handle since it is crucial should be turned on once a motion is detected, and should be turned
to define (and when possible, to reason) the calling order of off if there is no motion detection for three minutes; R7). In emergency,
the partial methods as it may affect the behavior. To address lights that are on must not be turned off.
this problem, several languages with formal semantics have been We begin with identifying the context of the requirements, ob-
proposed for specifying the requirements of this composition. For serving that while requirements R5 and R6 specify that the behavior
example, Cardozo et al. [19] proposed a Petri net-based context depends on motion detection, the actual context of these requirements
model called CoPN (depicted in Fig. 9). Using this language, is that the room is empty/nonempty. Moreover, using a motion sensor
developer explicitly specify the relations between the different for detecting occupancy is only one option that may change over
layers, where each relation can of a different type, such as: time. Thus, we change these requirements slightly to depend on the
implications, requirements, conjunctions, disjunctions, causality, occupancy of the rooms — In 𝑋, the 𝑌 should be turned on when there
etc. These relations are usually not part of the requirements or the is someone in the room and turned off when the room is empty (𝑋 is
system specification, and are derived from the implementation rooms/office rooms and 𝑌 is light/air-conditioner, depending on the
of the system. Thus, it may be hard to change the model upon requirement). We also add the following requirement: R8 A room is
changes to the requirements or to the code. We further elaborate considered as empty if and only if it has no movement for more than
on COP semantics in Section 11. three minutes.
In COBP, all new live copies are simultaneously activated and
advanced. If the requirements impose a specific order of events 10.1. Implementation
(as in the hot–cold example), then we will have a dedicated CBT
for explicitly specify it. The possible system events are {on(𝑟, 𝑑), off (𝑟, 𝑑), motionDetected(𝑟),
roomIsEmpty(𝑟), roomIsNonempty(𝑟), CTX.Ended(𝑞, 𝑐)}, where on and off
are used to turn on/off a device 𝑑 in room 𝑟 (i.e., light or air-
10. Case study: A smart building
conditioner), motionDetected pushed to the system by the motion sensor
of room 𝑟, roomIsEmpty∕roomIsNonempty are used to declare that room
In this case study, we demonstrate how COBP can be used for de-
𝑟 is empty/nonempty (respectively), and CTX.Ended declares that 𝑐 is
veloping reactive IoT systems, by developing the example of [6] using
no longer the answer to query 𝑞 (i.e., the context 𝑐 has ended).
our BPjs-based implementation. We first list a set of requirements for a
smart-building system and implement it. Next, we introduce additional
requirements and refine the system specification, demonstrating the Context specification
flexibility and agility offered by the paradigm. We begin with specifying the context in mind, in light of the given
The initial requirements are as follows: requirements, including physical entities and logical ones. Fig. 10 de-
Physical: R1) The room types include offices, kitchens, and re- picts the specification of the context schema (i.e., entities and the rela-
strooms; R2) Each room has a motion detector and a smart light; R3) tionships among the them). It includes the following entities: Building,
An Office has a smart air-conditioner; R4) Events are emitted when a Room, Kitchen, Office, Restroom (originating from R1); the isEmpty
motion starts or stops. attribute of Room (R5 and R6); and Emergency (R7). We further
Behavioral: R5) In all rooms, the light should be turned on once define the devices entities, i.e., MotionSensor, SmartLight (R2); and
a motion is detected, and should be turned off if there is no motion AirConditioner (R3). Of course this is just one of the ways to define
detection for three minutes; R6) In office rooms, the air-conditioner the schema for these requirements. We adopt the UML class diagram

14
A. Elyasaf Information and Software Technology 133 (2021) 106504

bp.registerCBT("Light: On",
"NonemptyRoom", function(room) {
bp.sync({ request: on(room.light) });
});
bp.registerCBT("Light: Off",
"EmptyRoom", function(room) {
bp.sync({ request: off(room.light) });
});

bp.registerCBT("Air-conditioner: On",
"NonemptyOffice", function(office) {
bp.sync({ request: on(office.airConditioner) });
});
bp.registerCBT("Air-conditioner: Off",
Fig. 10. The context schema for the smart-building case study. Both physical and "EmptyOffice", function(office) {
logical entities are represented in the schema. bp.sync({ request: off(office.airConditioner) });
});
Table 3
The ‘‘query and command’’ repository for the smart building case study. bp.registerCBT("Emergency: Lights",
Type Name Command "Room", function(room) {
Q Room SELECT * FROM roomt while(true)
Q Office SELECT * FROM office bp.registerCBT("Emergency: Light " + room.id,
Q Emergency SELECT * FROM emergency "Emergency", function(e) {
Q EmptyRoom SELECT * FROM room bp.sync({ block: off(room.light),
WHERE isEmpty=1 waitFor: CTX.Ended("Emergency", e) });
Q NonemptyRoom SELECT * FROM room });
WHERE isEmpty=0 });
Q EmptyOffice SELECT * FROM office
WHERE isEmpty=1 bp.registerCBT("Mark room as nonempty",
Q NonemptyOffice SELECT * FROM office
WHERE isEmpty=0 "EmptyRoom", function(room) {
Q NoMovement SELECT * FROM room bp.sync({ waitFor: motionDetected(room) });
WHERE timeFrom(lastMovement) bp.sync({ request: roomIsNonempty(room) });
> :seconds });
U RoomIsNonempty UPDATE room SET isEmpty=0 bp.registerCBT("Mark room as empty", "NoMovement",
WHERE id=:rId {seconds: 3*60}, function(room) {
U RoomIsEmpty UPDATE room SET isEmpty=1 bp.sync({ request: roomIsEmpty(room),
WHERE id=:rId waitFor: motionDetected(room) });
U UpdateMovement UPDATE room
SET lastMovement=date('now') });
WHERE id=:rId
Listing 5: The behavioral specification of the smart-building
case study. The last two CBTs specify when to mark a room as
empty/nonempty. The additional parameter in the last CBT provides
notation for devising the schema, though other representations may be the seconds parameter to the NoMovement query (see Section 10.2).
used as well.
Once the schema is designed, we populate it with the initial pre-
defined data. That is, adding buildings and rooms to the database and
associating devices to specific rooms, and rooms to specific buildings. Behavioral: R11) If a worker enters a room, announce her name in
the room’s speaker; R12) During an emergency, turn on all lights.
Data access layer To cope with these requirements, we can add object types that
QUERY and UPDATE are defined in Table 3. The effect of the represent new aspects of the context. To the schema, we add a Smart
motionDetected event updates the timestamp of the last movement by
Speaker data type (similarly to the other devices) (R9) and a Worker
calling UpdateMovement . The effect of roomIsEmpty and roomIsNonempty
data type, both associated with Room (see Fig. 11). To the DAL we
trigger a call to the corresponding update commands — RoomIsEmpty
and RoomIsNonempty. add commands for marking and un-marking that a worker has entered
a room (R11) (similar to the room occupancy update commands). We
Behavioral specification (CBTs) also modify the effect function for triggering them. For getting a view
The behavioral specification is given in Listing 5. The first two CBTs, of all workers that are inside a room (R10), we add the WorkerInARoom
Light ∶ On∕Off , are bound to queries EmptyRoom and NonemptyRoom query, defined as SELECT * FROM worker WHERE id IS NOT NULL. Fi-
(respectively), handling R5. The next two CBTs, nally, we add the following CBTs: two for detecting entrance/leaving of
Airconditioner ∶ On∕Off , are bound to the EmptyOffice and workers (and triggering the appropriate marking/unmarking command
NonemptyOffice queries (respectively), handling R6. R7 is handled in the using the effect function) (R10, R11); one for turning the lights on
Emergency ∶ Lights CBT, and finally, the last two CBTs, during an emergency (R12) (similar to the Emergency CBT in Listing
Mark room as empty/nonempty handle R8.
5); and one for announcing the worker name (demonstrated in Listing
As development evolves, new requirements may arise. In our exam-
6) (R11).
ple these include:
Physical: R9) Smart speakers are installed in all rooms (in addition Thanks to the incrementality feature of BP, no changes to the previ-
to R2 devices); R10) Workers can be identified in the system (e.g., by ous specification are needed, we only added elements to the schema, to
a RF tag or a Bluetooth device), while visitors cannot. the query and command repository, and to the behavioral specification.

15
A. Elyasaf Information and Software Technology 133 (2021) 106504

Table 4
Experimenting with a non-context-aware verification algorithm on the smart-building example. The com-
bination of two rooms and two movements resulted with ‘‘out of memory’’ exception, even though the
sequence of events of each room is not influenced by the events of other rooms. A context-aware algorithm
could have verify the behavior of the only one room.
Setup Results
# of # of # of # of Time (s)
rooms moves simulated states
minutes
1 1 1 10 61 3.5
2 1 2 10 178 7.3
3 1 1 20 236 8.1
4 1 2 20 1496 42
5 2 1 10 869 29
6 2 2 10 Out of memory
7 2 1 20 70,001 177.4

a context is active, should be separated from the logic of when to acti-


vate/deactivate a context, that ought to be encapsulated in dedicated
CBTs. Consider for example future requirements for nonempty rooms,
such as: resume music, open the shutters, etc. The encapsulation of the
when-logic allows us to incrementally add simple what CBTs, and it
allows for future changes to the when mechanism.

Verification. As noted before, BPjs has a verification tool that we used


for detecting undesired behaviors in this paper’s examples. The tool
traverses the state space of the program and validates certain aspects of
the system behavior, such as: the absence of deadlocks or user-defined
assertion. The input of this tool is the behavioral program and a set of
assertions to validate. Once a violation is detected, the trace of events
that led to the violation is returned to the user for inspection.
Fig. 11. Schema for the new requirements. The behavioral specification in our case depends on time and move-
ments detection, both triggered by the environment. Since the environ-
bp.registerCBT("AnnounceWorkerName", ment must be simulated during the verification, we added one CBT for
"WorkerInARoom", function(worker) { simulating movements in each room and one CBT for simulating time.
bp.sync({ request: announce(worker.name) }); We experimented with several configurations, varying in the number
}); of rooms, the simulation length, and the number of movements. The
experiments where conducted on a computer with an Intel i5-4570
Listing 6: A new requirement — announce workers names CPU and 16GB RAM (using max. 12GB). The results, summarized in
Table 4, reveal that any combination of two rooms and two movements
resulted with an ‘‘out of memory’’ exception, even though the sequence
of events of each room is independent of the events of other rooms. The
10.2. A short discussion reason for this exception is that we did not modify the BPjs verification
algorithm for context-related optimizations. Thus, it treats the context
Separation of concerns. To determine the occupancy of a room, we as a regular local variable of one of the b-threads (see our implemen-
created two CBTs that kept the isEmpty attribute updated. It should be tation in Section 3.4). Yet, a simple context-aware optimization could
noted that there is simpler way to determine the occupancy — remove have verify the behavior of only one room. More generally, while a
the isEmpty attribute and the update commands (RoomIsEmpty and b-program verification algorithm must consider all b-threads, in COBP
RoomIsNonempty) and change the queries EmptyRoom and it is sometimes enough to verify the CBT behavior instead of verifying
NonemptyRoom to: the behavior of each live copy. We further discuss this in Section 11.

TypeName Command 11. Related work


Q EmptyRoom SELECT * FROM room WHERE
timeFrom(lastMovement) > 3 Several modeling and programming languages include constructs
Q NonemptyRoom SELECT * FROM room WHERE that can be used for describing context. Harel’s statecharts [20], for
timeFrom(lastMovement) <= 3 example, introduced clustering for grouping behaviors under specific
conditions. Below, we show how LSC constructs can also be used
While this solution is simpler and more concise, it breaks the for modeling context. While COBP explicitly defines context idioms,
separation of concerns and defines behavioral aspects in the data these languages do not. We identify three main advantages of using
layer. Consider for example a change in the requirements, designed to explicit context idioms. First, for achieving an alignment between
the code/model and context-aware requirements, the language must
improve the occupancy detection, where the occupancy is determined
include explicit ‘‘first-class citizen’’ idioms for referencing and changing
by two sensors and the thresholds for the sensors are different during
the system context. Second, modeling context without explicit context
working hours. By specifying the behaviors and the logical decisions
idioms may cause tight coupling between the data specification and
in the CBTs only, we improve the agility of the system and achieve a
the behavioral specification, as we demonstrated in BP and as we
better separation of concerns.
demonstrate below in LSC. The context idioms proposed in this paper
Encapsulation. One experience in developing COBP systems yielded an allow for a better separation-of-concerns by splitting the context-related
encapsulation rule of thumb. The CBTs that specify what to do while design from the behavioral design, using the multilayered architectural

16
A. Elyasaf Information and Software Technology 133 (2021) 106504

pattern. Finally, the idioms and their formal semantics allow for im- Table 5
A comparison between the performance of BPjs verification tool and NASA’s JavaP-
proving verification algorithms, as we demonstrated in Section 10.2
athFinder (JPF). The formal semantics allow BPjs to count as states only synchronization
and discuss below. points, whereas JPF must look at all thread interleaving options.
Tool B-Threads States Time (ms)
11.1. Context-awareness in scenario-based programming JPF 3 438,568 511,000
JPF 6 out of memory
BPjs 25 27 2205
To the best of our knowledge, besides of the work of [4,6] that we BPjs 10,000 402 640,358
generalize here, there is no prior work on context for BP. Yet, there are
two, somewhat related works that we discuss here.
The work on BP began with scenario-based programming (SBP), a
way to create executable specifications of reactive systems, introduced 2. Bar-Sinai, Weiss and Shmuel [11] presented a verification tool
through the language of live sequence charts (LSC) and its Play-Engine for BPjs that we used for the examples of this paper (elaborated
implementation [7,21]. As explained in Section 3.4, while BP allows in Section 10.2). The tool avoids the translation by directly
traversing the state space of the program, as in NASA’s Java-
for behavioral specification only, the LSC language includes idioms for
PathFinder (JPF) [32]. The method only allows for explicit
both behavioral and data specifications. The lifelines represent objects,
model-checking. The advantage, however, is that it allows for
possibly with data properties, allowing to share data among scenarios.
model-checking any code because it uses the JavaScript inter-
A lifeline can either refer to a concrete object, or define a binding
preter in its state-space traversal. Bar-Sinai [33] compared the
expression that is evaluated at runtime, meaning that a live-copy of
performance of this method to the performance of JPF (also
the chart is instantiated whenever there is a new answer to the binding
summarized in Table 5). To compare, they verified with both
expression. Indeed here and in [6], we utilize this trait for defining
tools different programs with various number of b-threads. JPF
the context idioms as syntactic sugars of dynamic binding. Moreover,
verified the program as a standard, non-BP program, there-
the Play-Engine specification splits each chart to a prechart and a main
fore looking at all thread interleaving options, while BPjs only
chart, where the prechart describes events (and conditions), that when
counted synchronization points as states. Not surprisingly, the
they occur (or are satisfied), the system will attempt to execute the
JPF verification process was much longer, taking 85 s to verify
specification in the main chart. Thus, binding a chart to a context can
a program containing three b-threads, visiting 438,568 states.
be achieved by defining the context query inside the prechart area. While trying to verify a program with six b-threads, JPF ran out
While these two traits (dynamic binding and prechart) allow for sharing of memory after 8:31 min. BPjs was able to verify a program
data among scenarios, as previously noted, explicit context idioms have containing 10,000 b-threads in 10:67 min.
several advantages. 3. [14] used a hybrid approach that assumes that state explosion
Atir et al. [22] proposed to use the dynamic binding trait for ex- only comes from the b-threads composition, rather than their
tending LSC with idioms for specifying hierarchies between scenarios. individual size. Given that, the space of each b-thread can be
Using hierarchies, they were able to abstract parts of the behaviors to translated to a model, used by a model-checker for analyzing the
different charts and activate them from several places. Atir et al. did composition of the b-threads. This method allows for a robust
not refer to context specification, however in some cases, context can verification framework without manually creating a translator,
be viewed (and implemented) as hierarchy. The COBP paradigm and though it only applies to systems with small b-threads (in terms
the semantics we define here, extends this idea to other context types. of number of states).
4. Maoz and Ringert [34] used a tool for direct specification of
11.2. Synthesis and reasoning models using SMV-like languages. They presented a case study
of developing a software controller for a forklift robot using
GR(1) [30] synthesis tools. Their main observation is that exten-
A recent literature review [23], argued that the industry is cur-
sions of the specification language with auxiliary variables and
rently concerned with the quality assurance of context-aware software
higher-level specification patterns support writing specifications
systems (i.e., that the software will not fail upon context changes),
with better confidence. On the other hand, with growing specifi-
while failing to cover aspects of functional assurance. The problem with
cation size, understanding reasons for synthesized behavior and
covering all the possible variations of context during testing execution
for unrealizability turned out to be a major challenge.
is not feasible. This is where formal methods and reasoning techniques
may excel. In Section 10.2, we demonstrated how the addition of context to
As we explained in Section 1, COP and COBP share the need for the model improves its modularity, and how it can be used to improve
applying reasoning techniques on their model, in order to cope with the verification algorithm of [11]. Yet, such improvements, require an
unpredictable behavior that may occur due to the dynamic adaptation adaptation of each of the above approaches since all are designed under
to context conditions. In fact, the BP paradigm faces this problem as the assumption that the only protocol between b-threads is requests,
well, due to the distributed nature of the paradigm, resulting in many blocking, and triggering of events. In practice, when people use BP with
tailored reasoning techniques that we now elaborate on. shared data they know that the model-checking technologies will not
Starting from the pioneering work of Harel, Kugler and Pnueli [24], be applicable to their models. The formal COBP semantics presented
most of the synthesis and analysis tools for BP and SBP rely on the here enable the change of this, by adding mechanisms to encode the
mathematically rigorous nature of the semantics in providing tools for state of the context data so that the model-checker is aware of the new
running formal analysis and synthesis algorithms [11,14,25–30]. There form of inter-thread communication.
are different approaches for verifying behavioral code:
11.3. Context-oriented programming
1. Harel et al. [24] translated the model to SMV [31] and analyzed
the equivalent SMV model. The method allows for symbolic BP and COBP are language-independent paradigms, with abstract
model-checking that relies on a robust verification framework, semantics that are used and implemented by all BP languages. The
though it requires a translation that may not be either sound or evolution of COP was the other way around, where the first languages
complete. have been proposed before the semantics. Some COP implementations

17
A. Elyasaf Information and Software Technology 133 (2021) 106504

do not have formal semantics and require the translation of the ac- • Comparing COBP and COP. Both COBP and COP allow for context-
tual code to some formal language, for applying reasoning techniques aware programming, though they are fundamentally different
(see Section 11.3.1). Semantics have also been proposed for specific from each other. Some of the issues that were presented here
COP languages (see Section 11.3.2). Finally, some COP implementa- from the perspective of COBP, have been addressed and discussed
tions allow for developing the system in a modular manner (see Sec- by others from the perspective of COP. An in-depth comparison
tion 11.3.3), where part of the system (for example, the layer-activation between the two paradigms is needed for comprehending the
constraints) is formally specified, and the rest is defined using the differences between them.
underlying programming-language constructs (e.g., Java, Python, etc.). • Evaluating methodology aspects. We present several approaches
All the different COP languages and semantics elaborate below do for specifying COBP programs. The different examples demon-
not provide a formal semantics for the complete program (i.e., the busi- strated good and bad practices, discussing their advantages and
ness logic and its relation to the context). Thus, reasoning techniques disadvantages. Yet, these practices impact both qualitative and
can be applied only to the formally-specified parts, as opposed to COBP, quantitative aspects of the specifications, raising the need for a
where the model can be both executed and reasoned. user study that will evaluate these aspects.

Declaration of competing interest


11.3.1. Language-independent semantics
In Section 9.2 we elaborated on CoPN, a Petri net-based language The authors declare that they have no known competing finan-
for modeling run-time context activations [19], allowing for both rea- cial interests or personal relationships that could have appeared to
soning the model and using it at run-time. [35] proposed another influence the work reported in this paper.
approach for representing program states as graph nodes, connected
by their relations. This approach allows for simulating context-oriented Acknowledgment
programs, though it is not possible to reason the consistency of the
activation nor use it for run-time context compositions. The author would like to thank Gera Weiss for his invaluable help
with this paper.
11.3.2. Language-specific semantics
Costanza and D’Hondt [36] extended the ContextL language with References
declarative constraints on layers. The extension simplifies the enforce-
[1] David Harel, Assaf Marron, Gera Weiss, Behavioral programming, Commun. ACM
ment of the constraints and allows the programmer to interactively
55 (7) (2012) 90.
fulfill unmet constraints. The authors of EventECJ proposed to manu- [2] David Harel, Assaf Marron, Gera Weiss, Programming coordinated behavior
ally specify transition-rules between different contexts with finite-state in java, in: ECOOP 2010 – Object-Oriented Programming, Springer Berlin
automata [37,38]. Another solution, presented for Subjective-C, use a Heidelberg, 2010, pp. 250–274.
[3] Michael Bar-Sinai, Achiya Elyasaf, Aviran Sadon, Gera Weiss, A scenario based
DSL for expressing layer dependencies [39]. While these semantics are
on-board software and testing environment for satellites, in: 59th Israel Annual
language-specific (and there more), some of them allow for reasoning Conference on Aerospace Sciences, IACAS 2019, Vol. 2, 2019, pp. 1407–1419.
both the context activation and the behavioral variation. [4] Achiya Elyasaf, Aviran Sadon, Gera Weiss, Tom Yaacov, Using behavioral
programming with solver, context, and deep reinforcement learning for playing a
simplified robocup-type game, in: 2019 ACM/IEEE 22nd International Conference
11.3.3. Modular languages on Model Driven Engineering Languages and Systems Companion, MODELS-C,
A modular approach has been proposed in [40], where layer inter- IEEE, 2019, pp. 243–251.
faces define a contract between the layers and the classes. Each layer [5] Guy Katz, Assaf Marron, Aviran Sadon, Gera Weiss, On-the-fly construction of
composite events in scenario-based modeling using constraint solvers, in: Model-
must implement one or more layer interfaces, and each class allows
Driven Engineering and Software Development, ctitle=MODELSWARD 2019,
layer interfaces. Implementation means that the behavior of the layer SCITEPRESS - Science and Technology Publications, 2019, pp. 141–154.
satisfies the layer interfaces it implements, and allowing an interface [6] Achiya Elyasaf, Assaf Marron, Arnon Sturm, Gera Weiss, A context-based
layer means that the class satisfies the specifications for the allowed behavioral language for IoT, in: Regina Hebig, Thorsten Berger (Eds.), CEUR
Workshop Proceedings, Vol. 2245, CEUR-WS.org, Copenhagen, Denmark, 2018,
layer interface. This change allows for applying a modular reasoning
pp. 485–494.
in the layer activation mechanism for composing the partial methods [7] Werner Damm, David Harel, LSCS: breathing life into message sequence charts,
in the activated layer. Form. Methods Syst. Des. 19 (1) (2001) 45–80.
[8] Pascal Costanza, Robert Hirschfeld, Language constructs for context-oriented
programming: An overview of contextL, in: Proceedings of the 2005 Symposium
12. Concluding remarks on Dynamic Languages, ACM, 2005, pp. 1–10.
[9] Guido Salvaneschi, Carlo Ghezzi, Matteo Pradella, Context-oriented pro-
This paper introduced Context-Oriented Behavioral Programming gramming: A software engineering perspective, J. Syst. Softw. 85 (2012)
1801–1817.
(COBP) — a novel paradigm for developing context-aware systems —
[10] Gregory D. Abowd, Anind K. Dey, Peter J. Brown, Nigel Davies, Mark Smith,
built on top of the behavioral-programming paradigm. The paper aimed Pete Steggles, Towards a better understanding of context and context-awareness,
at formally defining the paradigm and introducing it through different in: Handheld and Ubiquitous Computing, Comput. Syst. 40 (3) (1999) 304–307.
examples and discussions. As described in Section 11, more research [11] Michael Bar-Sinai, Gera Weiss, Reut Shmuel, BPjs - An extensible, open infras-
tructure for behavioral programming research, in: 21st ACM/IEEE International
is required on adapting current reasoning techniques for effectively
Conference on Model Driven Engineering Languages and Systems: Companion
applying them on COBP specifications. Also, further user studies and Proceedings, MODELS-Companion 2018, 2018.
case studies are needed for comparing the paradigm to other paradigms [12] Robert M. Keller, Formal verification of parallel programs, Commun. ACM 19
and for evaluating additional aspects of the paradigm. Specifically: (7) (1976) 371–384.
[13] David Harel, Shahar Maoz, Smadar Szekely, Daniel Barkan, PlayGo: Towards
a comprehensive tool for scenario based programming, in: Proceedings of
• Comparing COBP and BP. The advantages (and possible disadvan-
the IEEE/ACM International Conference on Automated Software Engineering,
tages) of COBP over BP can be evaluated by many metrics, such ASE’10, 2010, pp. 359–360.
as improved specifications in terms of readability, understand- [14] David Harel, Amir Kantor, Guy Katz, Assaf Marron, Lior Mizrahi, Gera Weiss,
ability, maintainability, incrementality, succinctness. Moreover, On composing and proving the correctness of reactive behavior, in: Proceedings
of the International Conference on Embedded Software, EMSOFT, IEEE, 2013,
COBP provides more design patterns than BP. For example, in BP,
pp. 1–10.
conflicting behaviors can be arbitrated by specifying priorities, [15] Martin Gardner, Mathematical games, Sci. Am. 222 (6) (1970) 132–140.
whereas in COBP they can also be defined in different contexts. [16] Isaac Asimov, Runaround, Astounding Sci. Fiction 29 (1) (1942) 94–103.

18
A. Elyasaf Information and Software Technology 133 (2021) 106504

[17] Gal A. Kaminka, Mor Vered, Noa Agmon, Plan recognition in continuous [29] Joel Greenyer, Daniel Gritzner, Timo Gutahr, Florian König, Nils Glade, Assaf
domains, in: Sheila A. McIlraith, Kilian Q. Weinberger (Eds.), Proceedings of the Marron, Guy Katz, Scenariotools – A tool suite for the scenario-based modeling
Thirty-Second AAAI Conference on Artificial Intelligence, (AAAI-18), the 30th and analysis of reactive systems, Sci. Comput. Programm. (2017).
Innovative Applications of Artificial Intelligence (IAAI-18), and the 8th AAAI [30] Nir Piterman, Amir Pnueli, Yaniv Sa’ar, Synthesis of reactive(1) designs, in:
Symposium on Educational Advances in Artificial Intelligence, EAAI-18, New E. Allen Emerson, Kedar S. Namjoshi (Eds.), Verification, Model Checking, and
Orleans, Louisiana, USA, February 2–7, 2018, AAAI Press, 2018, pp. 6202–6210. Abstract Interpretation, Springer Berlin Heidelberg, Berlin, Heidelberg, 2006, pp.
[18] Michele Colledanchise, Petter Ögren, Behavior trees in robotics and AI: An 364–380.
introduction, 2017, CoRR, abs/1709.00084. [31] Kenneth L. McMillan, The SMV systems, 1993, pp. 61–85.
[19] Nicolás Cardozo, Sebastián González, Kim Mens, Ragnhild Van Der Straeten, [32] Gary Lindstrom, Peter C. Mehlitz, Willem Visser, Model checking real time java
Jorge Vallejos, Theo D’Hondt, Semantics for consistent activation in using java pathfinder, in: Doron A. Peled, Yih-Kuen Tsay (Eds.), Automated
context-oriented systems, Inf. Softw. Technol. 58 (2015) 71–94. Technology for Verification and Analysis, Third International Symposium, ATVA
[20] David Harel, Statecharts: A visual formalism for complex systems, Sci. Comput. 2005, Taipei, Taiwan, October 4-7, 2005, Proceedings, in: Lecture Notes in
Programm. 8 (3) (1987) 231–274. Computer Science, vol. 3707, Springer, 2005, pp. 444–456.
[21] David Harel, Rami Marelly, Come, Let’s Play: Scenario-Based Programming Using [33] Michael Bar-Sinai, Extending Behavioral Programming for Model-Driven
LSCs and the Play-Engine, Springer Science & Business Media, 2003. Engineering (Ph.D. thesis), Ben-Gurion University of the Negev, Israel, 2020.
[22] Yoram Atir, David Harel, Asaf Kleinbort, Shahar Maoz, Object composition in [34] Shahar Maoz, Jan Oliver Ringert, Synthesizing a lego forklift controller in GR(1):
scenario-based programming, in: Proceedings of the Theory and Practice of A Case Study, in: Pavol Cerný and Viktor Kuncak and Parthasarathy Madhusudan
Software, 11th International Conference on Fundamental Approaches To Software (Eds.), Proceedings Fourth Workshop on Synthesis, SYNT 2015, San Francisco,
Engineering, in: FASE’08/ETAPS’08, Springer-Verlag, Berlin, Heidelberg, 2008, CA, USA, 18th July 2015, in: EPTCS, vol. 202, 2015, pp. 58–72.
pp. 301–316. [35] Hans Schippers, Tim Molderez, Dirk Janssens, A Graph-based operational seman-
[23] Santiago Matalonga, Felyppe Rodrigues, Guilherme Horta Travassos, Charac- tics for context-oriented programming, in: Proceedings of the 2Nd International
terizing testing methods for context-aware software systems: Results from a Workshop on Context-Oriented Programming, 2010, pp. 1–6.
quasi-systematic literature review, J. Syst. Softw. 131 (2017) 1–21. [36] Pascal Costanza, Theo D’Hondt, Feature descriptions for context-oriented pro-
[24] David Harel, Hillel Kugler, Rami Marelly, Amir Pnueli, Smart play-out of gramming, in: Steffen Thiel, Klaus Pohl (Eds.), Software Product Lines, 12th
behavioral requirements, in: Mark Aagaard, John W. O’Leary (Eds.), Formal International Conference, SPLC 2008, Limerick, Ireland, September 8-12, 2008,
Methods in Computer-Aided Design, 4th International Conference, FMCAD 2002, Proceedings. Second Volume, Workshops, Lero Int. Science Centre, University of
Portland, OR, USA, November 6-8, 2002, Proceedings, in: Lecture Notes in Limerick, Ireland, 2008, pp. 9–14.
Computer Science, vol. 2517, Springer, 2002, pp. 378–398. [37] Tetsuo Kamina, Tomoyuki Aotani, Hidehiko Masuhara, EventCJ: A context-
[25] David Harel, Itai Segall, Planned and traversable play-out: A flexible method oriented programming language with declarative event-based context transition,
for executing scenario-based programs, in: Proceedings of the 13th International in: Paulo Borba, Shigeru Chiba (Eds.), Proceedings of the 10th International
Conference on Tools and Algorithms for the Construction and Analysis of Conference on Aspect-Oriented Software Development, AOSD 2011, Porto de
Systems, in: TACAS’07, Springer-Verlag, Berlin, Heidelberg, 2007, pp. 485–499. Galinhas, Brazil, March 21–25, 2011, ACM, 2011, pp. 253–264.
[26] David Harel, Hillel Kugler, Amir Pnueli, Synthesis revisited: Generating statechart [38] Tomoyuki Aotani, Tetsuo Kamina, Hidehiko Masuhara, Featherweight Eventcj: A
models from scenario-based requirements, in: Hans-Jörg Kreowski, Ugo Mon- core calculus for a context-oriented language with event-based per-instance layer
tanari, Fernando Orejas, Grzegorz Rozenberg, Gabriele Taentzer (Eds.), Formal transition, in: Proceedings of the 3rd International Workshop on Context-Oriented
Methods in Software and Systems Modeling, Essays Dedicated To Hartmut Ehrig, Programming, 2011, pp. 1–7.
on the Occasion of His 60th Birthday, in: Lecture Notes in Computer Science, [39] Sebastián González, Programming in Ambience: Gearing up for Dynamic
vol. 3393, Springer, 2005, pp. 309–324. Adaptation to Context (Ph.D. thesis), UCL-Université Catholique de Louvain,
[27] David Harel, Hillel Kugler, Shahar Maoz, Itai Segall, Accelerating smart play-out, 2008.
in: Jan van Leeuwen, Anca Muscholl, David Peleg, Jaroslav Pokorný, Bernhard [40] Aotani Tomoyuki, Gary T. Leavens, Towards modular reasoning for context-
Rumpe (Eds.), SOFSEM 2010: Theory and Practice of Computer Science, 36th oriented programs, in: Proceedings of the 18th Workshop on Formal Techniques
Conference on Current Trends in Theory and Practice of Computer Science, for Java-Like Programs, FTfJP’16, Association for Computing Machinery, New
Spindleruv MlÝN, Czech Republic, January 23-29, 2010. Proceedings, in: Lecture York, NY, USA, 2016, pp. 1–7.
Notes in Computer Science, vol. 5901, Springer, 2010, pp. 477–488.
[28] David Harel, Robby Lampert, Assaf Marron, Gera Weiss, Model-checking behav-
ioral programs, in: 2011 Proceedings of the Ninth ACM International Conference
on Embedded Software, EMSOFT, 2011, pp. 279–288.

19

You might also like