Introducción a la programación conductual con React: solicitar, esperar y bloquear

La programación conductual (BP) es un paradigma acuñado en el artículo de 2012 de David Harel, Assaf Marron y Gera Weiss.

Directamente del resumen:

La programación de comportamiento simplifica la tarea de lidiar con la falta de especificación y los requisitos en conflicto al permitir la adición de módulos de software que no solo pueden agregar sino también modificar comportamientos existentes .

Conceptos de alto nivel

Primero explicaré los conceptos de alto nivel usando un ejemplo de dos componentes de React MoviesListy MoviesCount. Uno muestra una lista de películas, el otro muestra la cantidad de películas que hay. Luego me sumergiré en cómo funciona exactamente la programación conductual.

Ambos componentes obtienen datos de la misma URL HTTP. Fueron desarrollados por dos equipos diferentes en una gran organización. Cuando renderizamos ambos componentes en una página, tenemos un problema ya que realizan la misma solicitud:

Poco sabíamos que estos son componentes conductuales . Esto significa que podemos hacer algo bastante inteligente para evitar que se activen ambas solicitudes:

const MoviesCountFromList = withBehavior([ function* () { // block FETCH_COUNT from happening yield { block: ['FETCH_COUNT'] } }, function* () { // wait for FETCH_LIST, requested by the other // MoviesList component, and derive the count const response = yield { wait: ['FETCH_LIST'] } this.setState({ count: response.length }) }])(MoviesCount)

En el ejemplo anterior, entramos en el MoviesCountcomponente. Nosotros esperamos y solicitamos a que algo suceda. Y, de manera más exclusiva para la programación conductual, también bloqueamos que algo sucediera.

Debido a que estábamos tratando de evitar que se dispararan ambas solicitudes, bloqueamos la activación del FETCH_COUNTevento (dado que el FETCH_LISTevento ya había adquirido los mismos datos ).

Agregar funcionalidad a los componentes existentes sin modificar su código es la novedad del paradigma de programación conductual.

De manera intuitiva, esto puede permitir la creación de componentes más reutilizables.

En el resto del artículo, profundizaré en cómo funciona la programación conductual (BP), específicamente en el contexto de React .

Repensar el flujo de programación

Para lograr la funcionalidad anterior, debemos pensar en los comportamientos de programación de manera un poco diferente. Específicamente, los eventos juegan un papel crucial en la organización de la sincronización entre los diversos comportamientos que definimos para nuestros componentes.

const addHotThreeTimes = behavior( function* () { yield { request: ['ADD_HOT'] } yield { request: ['ADD_HOT'] } yield { request: ['ADD_HOT'] } })
const addColdThreeTimes = behavior( function* () { yield { request: ['ADD_COLD'] } yield { request: ['ADD_COLD'] } yield { request: ['ADD_COLD'] } })
run( addHotThreeTimes, addColdThreeTimes)

Cuando ejecutamos el código anterior, obtenemos una lista de eventos solicitados:

ADD_HOTADD_HOTADD_HOTADD_COLDADD_COLDADD_COLD

Como era de esperar, se ejecuta el primer comportamiento. Una vez hecho esto, continúa el segundo comportamiento. Sin embargo, las nuevas especificaciones de nuestro componente nos obligan a cambiar el orden en el que se activan ambos eventos. En lugar de disparar ADD_HOTtres veces, y luego ADD_COLDtres veces, queremos que se intercalen y disparen ADD_COLDjusto después de a ADD_HOT. Esto mantendrá la temperatura algo estable.

...
const interleave = behavior( function* () { while (true) { // wait for ADD_HOT while blocking ADD_COLD yield { wait: ['ADD_HOT'], block: ['ADD_COLD'] }
 // wait for ADD_COLD while blocking ADD_HOT yield { wait: ['ADD_COLD'], block: ['ADD_HOT'] } } })
run( addHotThreeTimes, addColdThreeTimes, interleave)

En el ejemplo anterior, presentamos un nuevo comportamiento de intercalación que hace exactamente lo que necesitamos.

ADD_HOTADD_COLDADD_HOTADD_COLDADD_HOTADD_COLD

Cambiamos el orden de ejecución de las cosas, sin tener que modificar el código de los comportamientos ya escritos.

El proceso se resume en el gráfico siguiente.

Los conceptos clave de esta forma de programación son los operadores de solicitud , espera y bloqueo . La semántica de estos operadores es:

  • Solicitar un evento: proponer que se considere el evento para su activación y solicitar ser notificado cuando se active
  • Esperando un evento: sin proponer su activación, solicitando ser notificado cuando se active el evento
  • Bloquear un evento: prohibir la activación del evento, vetar solicitudes de otros b-threads.

Cada subproceso b (subproceso de comportamiento) vive por sí solo y no es consciente de otros subprocesos. Pero todos están entrelazados en tiempo de ejecución, lo que les permite interactuar entre sí de una manera muy novedosa.

La sintaxis del generador es esencial para el funcionamiento de un programa conductual. Necesitamos controlar cuándo pasar a la siguiente declaración de rendimiento.

Volver a React

¿Cómo se pueden utilizar estos conceptos de BP en el contexto de React?

Resulta que a través de componentes de alto orden (HOC), puede agregar este lenguaje de comportamiento a los componentes existentes de una manera muy intuitiva:

class CommentsCount extends React.Component { render() { return {this.state.commentsCount} }}
const FetchCommentsCount = withBehavior([ function* () { yield { request: ['FETCH_COMMENTS_COUNT']} const comments = yield fetchComments() yield { request: ['FETCH_COMMENTS_COUNT_SUCCESS']} this.setState({ commentsCount: comments.length }) },])(CommentsCount)

Aquí estamos usando withBehavior, de la biblioteca b-thread, para hacer CommentsCountun componente de comportamiento. Específicamente, estamos haciendo que obtenga los comentarios y muestre los datos una vez que estén listos.

Para componentes simples, esto podría no ser un cambio de juego. Pero imaginemos componentes más complejos, con mucha lógica y otros componentes dentro de ellos.

Podríamos imaginar todo el sitio web de Netflix como un /> component:

Original text


When we use this component in our app, we’d like to interact with it. Specifically, when a movie is clicked, we don’t want to start the movie immediately, but instead we want to make an HTTP request, show other data about the movie, and then start the movie.

Without changing code inside the /> component, I’d argue that this would be impossible to achieve without it being a behavioral component.

Instead let’s imagine that /> was developed using behavioral programming:

const NetflixWithMovieInfo = withBehavior([ function* () { // First, block the MOVIE_START from happening // within  until a new // FETCH_MOVIE_INFO_SUCCESS event has been requested. // The yield statement below can be read as: // wait for FETCH_MOVIE_INFO_SUCCESS while blocking MOVIE_START yield { wait: ['FETCH_MOVIE_INFO_SUCCESS'], block: ['MOVIE_START'] } }, function* () { // Here we wait for MOVIE_CLICKED, which is // triggered within , and we fetch our // movie info. Once that's done we request a new event // which the earlier behavior is waiting upon const movie = yield { wait: ['MOVIE_CLICKED'] } const movieInfo = yield fetchMovieInfo(movie) yield { request: ['FETCH_MOVIE_INFO_SUCCESS'], payload: movieInfo } }])(Netflix)

Above we’ve created a new NetflixWithMovieInfo component which modifies the behavior of the /> component (again, without changing its source code). The addition of the above behaviors makes it so that MOVIE_CLICKED will not trigger MOVIE_START immediately.

Instead, it uses a combination of “waiting while blocking”: a wait and a block can be defined within a single yield statement.

The picture above describes, more in detail, what is happening within our behavioral components. Each little box within the components is a yield statement. Each vertical dashed arrow represents a behavior (aka b-thread).

Internally, the behavioral implementation will start by looking at all the yield statements of all b-threads at the current synchronization point, depicted using an horizontal yellow line. It will only continue to the next yield statement within a b-thread if no events in other b-threads are blocking it.

Since nothing is blocking MOVIE_CLICKED , it will be requested. We can then continue to the next yield statement for the Netflix behavior. At the next synch point, the b-thread on the far right, which is waiting for MOVIE_CLICKED, will proceed to its next yield statement.

The middle behavior that is waiting-and-blocking does not proceed. FETCH_MOVIE_INFO_SUCCESS was not requested by other b-threads, so it still waits-and-blocks. The next synchronization point will look something like this:

As before, we will look at all the yield statement at this synchronization point. This time, however, we cannot request MOVIE_START because there’s another b-thread that is blocking it (the black yield statement). The Netflix component will therefore not start the movie.

FETCH_MOVIE_INFO_SUCCESS on the far right, however, is free to be requested. This will unblock MOVIE_START at the next synch point.

All this in practice allowed us to change the order of things happening within other components, without directly modifying their code. We were able to block certain events from firing until other conditions were met in other components.

This changes the way we might think of programming: not necessarily a set of statements executed in order, but rather an interleaving of yield statements all synchronized through specific event semantics.

Here’s a simple animation depicting the way b-threads are executed and interwoven at runtime.

Programming without changing old code

There is another way we can understand this programming idiom. We can compare the way we currently program as specifications change, versus how it would be done with behavioral programming.

In the above caption, we imagine how behavior may be added to a non-behavioral program. We start with a program described only using three black rectangles (on the left).

As specifications change, we realize we need to modify the program and add new behavior in various sections of the program, depicted as newly added colored rectangles. We continue doing this as requirements for our software change.

Every addition of behavior requires us to change code that was written, which possibly litters the old behavior with bugs. Furthermore, if the program we are changing is part of various other modules used by different people, we might be introducing unwanted behavior to their software. Finally, it may not be possible to change specific programs as they might be distributed as libraries with licensed source code.

In the above figure, we see how the same program-modifications can be achieved using behavioral programming idioms. We still start with our three rectangles on the left as we did before. But as new specifications arise, we don’t modify them. Instead we add new b-threads, represented as columns.

The resulting program is the same, although constructed in a very different way. One of the advantages of the behavioral approach is that we don’t have to modify old code as requirements change.

You can also imagine developing each b-thread in parallel, possibly by different people in a large organization, since they do not directly depend on each other.

The benefit of this approach also seems to be with packaging: we can change the behavior of a library without needing to access or modify its source-code.

APIs not only as props, but as events

Currently, the only way for a React component to communicate with the outside world is via props (apart from the Context API).

By making a component behavioral, instead of using props, we tell the outside world about when things happen within the component by yielding events.

To allow other developers to interact with the behavior of a component, we must therefore document the events that it requests, the events it waits for, and finally the events it blocks.

Events become the new API.

For instance, in a non-behavioral Counter component, we tell the outside world when the counter is incremented and what the current count is, using an onIncrement prop:

class Counter extends React.Component { state = { currentCount: 0 } handleClick = () => { this.setState(prevState => ({ currentCount: prevState.currentCount + 1 }), () => { this.props.onIncrement(this.state.currentCount) }) } render() { {this.state.currentCount} + }}
 console.log(currentCount) }/>

What if we want to do something else before the counter’s state gets incremented? Indeed we could add a new prop such as onBeforeIncrement, but the point is that we don’t want to add props and refactor code every time a new specific arises.

If we transform it into a behavioral component we can avoid refactoring when new specifications emerge:

class Counter extends React.Component { state = { currentCount: 0 } handleClick = () => { bp.event('CLICKED_INCREMENT') } render() { {this.state.currentCount} + }}
const BehavioralCounter = withBehavior([ function* () { yield { wait: ['CLICKED_INCREMENT'] } yield { request: ['UPDATE_CURRENT_COUNT'] }
 this.setState(prevState => ({ currentCount: prevState.currentCount + 1 }), () => { this.props.onIncrement(this.state.currentCount) }) }])(Counter)

Notice how we moved the logic for when the state is updated inside a b-thread. Furthermore, before the update actually takes place, a new event UPDATE_CURRENT_COUNT is requested.

This effectively allows other b-threads to block the update from happening.

Components can also be encapsulated and shared as different packages, and users can add behavior as they see fit.

// package-name: movies-listexport const function MoviesList() { ...}
// package-name: movies-list-with-paginationexport const MoviesListWithPagination = pipe( withBehavior(addPagination))(MoviesList)
// package-name: movies-list-with-pagination-logicexport const MoviesListWithDifferentPaginationLogic = pipe( withBehavior(changePaginationLogic))(MoviesListWithPagination)

Again this is different from simply enhancing a component, as a regular HOC would do. We can block certain things from happening in the components we extend from, effectively modifying their behavior.

Conclusion

This new programming idiom might feel uncomfortable at first, but it seems to alleviate a prominent issue we have when using UI components: it is hard to reuse components, because they don’t blend with the environment they were put into.

In the future, perhaps using these behavioral concepts, we will be able to add new behavior to apps by simply mounting new components. Stuff like this will be possible:

Additionally, events don’t need to pollute the whole app and can be broadcast only within a specific environment.

Thanks for reading! If you’re interested in an actual implementation of behavioral programming, please see my current work in progress library that works with React: //github.com/lmatteis/b-thread. The Behavioral Programming homepage also contains various implementations.

For more information on this exciting new concept, I suggest you read the scientific papers on Behavioral Programming or check some of my other articles on the subject.