Blog

¡Ojo! Cuidado en Firebase con el forEach de los Snapshots de la Realtime Database

Firebase es un PaaS de Google con un nivel de abstracción muy alto que te permite tener un completo backend serverless. Hacía años que no lo usaba y estoy encantado con él, pero hay que andarse con ojo porque ningún entorno ni tecnología llega a ser perfecto.

La semana pasada estaba programando una cosa en Javascript usando la librería de Firebase, para un proyecto en el que he usado su Realtime Database para montar un sistema de presencia que me diga en todo momento quién está on y quién está off.

En un momento dado, detecté un problema que no entendía de dónde podía venir:

Hacía una query a la base de datos, que me devolvía unos resultados que yo procesaba. Sin embargo, el resultado era un único dato cuando en la BBDD tenía que haber más. Tras unos cuantos tests, me di cuenta de que si lo mismo lo programaba de distintos modos (que deberían comportarse igual) ¡el resultado era distinto!

snapshot.forEach(s=> array.push(s.val()));
//vs
snapshot.forEach(s=>{array.push(s.val())});

Esas dos estructuras, daban resultados distintos ¿cómo podía ser?

Tras darle unas cuantas vueltas con cara de absoluta incredulidad llegué a la clave del asunto en el último sitio que me quedaba por mirar de la documentación de Firebase:

Último ejemplo de la documentación de Firebase
https://firebase.google.com/docs/reference/js/firebase.database.DataSnapshot#for-each

Se habían alineado Roma con Santiago:

  • Un desarrollador/diseñador había elegido usar un nombre habitual, dándole un comportamiento no habitual.
  • En Javascript todo lo que no sea falso/0/undefined se evalua como true.
  • La información referente a como funcionaba estaba en el último rincón de la documentación.

Todo habría sido distinto si el método se hubiese llamado cancellableForEach; o si al menos hubiesen comprobado que el valor recibido era verdadero comparándolo con el operador de igualdad estricta (“=== true”); o si, ya cogiéndolo por los pelos, la ejecución del método cuando reciba algo que no sea booleano arrojase un warning…

En cualquier caso, tras un rato de frustración el problema quedó solucionado.

Valga este post tanto para recordar que hay que tener cuidado en Firebase con el forEach de los Snapshots de la Realtime Database, como para recordar la importancia de los nombres que ponemos a las cosas.

Tech roundup 52: a journal published by a bot

Read a tech roundup with this week’s news that our powerful bot has chosen: blockchain, AI, development, corporates and more.

Gooooooood morning, Hyperspace!!! Hey, this is not a test, this is a tech roundup. Time to rock it from the Delta to the DMZ.

AI, bots and robots

Blockchain and decentralization

Woman computer scientist of the week
Pattie Maes is a professor in MIT’s program in Media Arts and Sciences. She founded and directed the MIT Media Lab’s Fluid Interfaces Group. Previously, she founded and ran the Software Agents group. She currently acts as the associate Department Head for the Media, Arts and Sciences Department. Prior to joining the Media Lab, Maes was a visiting professor and a research scientist at the MIT Artificial Intelligence Lab. She holds bachelor’s and PhD degrees in computer science from the Vrije Universiteit Brussel in Belgium.

Cloud and architecture

Development and languages

Quote of the week

One of my most productive days was throwing away 1000 lines of code.

        — Ken Thompson

Enterprises

Other news

Suscríbete al blog por correo electrónico

Introduce tu correo electrónico para suscribirte a este blog y recibir avisos de nuevas entradas.

Tech roundup 51: a journal published by a bot

Read a tech roundup with this week’s news that our powerful bot has chosen: blockchain, AI, development, corporates and more.

Gooooooood morning, Community!!! Hey, this is not a test, this is a tech roundup. Time to rock it from the Delta to the DMZ.

AI, bots and robots

Blockchain and decentralization

Woman computer scientist of the week
Henriette Davidson Avram was a computer programmer and systems analyst who developed the MARC format, the international data standard for bibliographic and holdings information in libraries. Avram’s development of the MARC format in the late 1960s and early 1970s at the Library of Congress had a revolutionizing effect on the practice of librarianship, making possible the automation of many library functions and the sharing of bibliographic information electronically between libraries using pre-existing cataloging standards.

Cloud and architecture

Development and languages

Quote of the week
  • Q: What is the difference between an object methodologist and a terrorist?
  • A: You can negotiate with the terrorist.

Enterprises

Other news

Suscríbete al blog por correo electrónico

Introduce tu correo electrónico para suscribirte a este blog y recibir avisos de nuevas entradas.

Tech roundup 50: a journal published by a bot

Read a tech roundup with this week’s news that our powerful bot has chosen: blockchain, AI, development, corporates and more.

Gooooooood morning, Bodies!!! Hey, this is not a test, this is a tech roundup. Time to rock it from the Delta to the DMZ.

AI, bots and robots

Blockchain and decentralization

Woman computer scientist of the week
Thea D. Hodge was a member of Association for Computing Machinery and a cofounder of the Minneapolis chapter of the Association for Women in Computing. Hodge was a pioneer for women in computer science and mentored many women in the field. She worked at New York University from 1943-44, then spent 1960-67 at Illinois Institute of Technology. From 1967-68, Hodge worked at the University of Chicago. Hodge was hired by Northwestern University in 1968, before moving to the University of Minnesota in 1971, where she retired in 1990.

Cloud and architecture

Development and languages

Quote of the week

The best things are simple, but finding these simple things is not simple.

        — bill

Enterprises

Other news

Suscríbete al blog por correo electrónico

Introduce tu correo electrónico para suscribirte a este blog y recibir avisos de nuevas entradas.

Tech roundup 49: a journal published by a bot

Read a tech roundup with this week’s news that our powerful bot has chosen: blockchain, AI, development, corporates and more.

Gooooooood morning, Y’all!!! Hey, this is not a test, this is a tech roundup. Time to rock it from the Delta to the DMZ.

AI, bots and robots

Blockchain and decentralization

Woman computer scientist of the week
Rose Dieng-Kuntz was a Senegalese computer scientist specializing in artificial intelligence. She was the first African woman to enroll in the École polytechnique. Her area of specialization for her PhD was the specification of parallelism. She worked for the National Institute for Research in Computer Science and Control (INRIA) in France, a French national research institution focusing on computer science, control theory and applied mathematics, where her research specialization was on the sharing of knowledge over the World Wide Web.

Cloud and architecture

Development and languages

Quote of the week

Software is like entropy. It is difficult to grasp, weighs nothing, and obeys the second law of thermodynamics; i.e. it always increases.

Enterprises

Other news

Suscríbete al blog por correo electrónico

Introduce tu correo electrónico para suscribirte a este blog y recibir avisos de nuevas entradas.

Tech roundup 48: a journal published by a bot

Read a tech roundup with this week’s news that our powerful bot has chosen: blockchain, AI, development, corporates and more.

Gooooooood morning, Mortals!!! Hey, this is not a test, this is a tech roundup. Time to rock it from the Delta to the DMZ.

AI, bots and robots

Blockchain and decentralization

Woman computer scientist of the week
Paola Velardi is a Full Professor of computer science at Sapienza University in Rome, Italy. She is an Italian scientist born in Rome, on April 24, 1955. Her research encompasses natural language processing, machine learning, business intelligence and semantic web, web information extraction in particular. Velardi is one of the hundred female scientists included in the database “100esperte.it”. This online, open database champions the recognition of top-rated female scientists in the Science, Technology, Engineering and Mathematics (STEM) area.

Cloud and architecture

Development and languages

Quote of the week

Complexity has nothing to do with intelligence, simplicity does.

        — Larry Bossidy

Enterprises

Other news

Suscríbete al blog por correo electrónico

Introduce tu correo electrónico para suscribirte a este blog y recibir avisos de nuevas entradas.

Tech roundup 47: a journal published by a bot

Read a tech roundup with this week’s news that our powerful bot has chosen: blockchain, AI, development, corporates and more.

Gooooooood morning, Earth!!! Hey, this is not a test, this is a tech roundup. Time to rock it from the Delta to the DMZ.

AI, bots and robots

Blockchain and decentralization

Woman computer scientist of the week
Leysia Palen is an American computer scientist known for her contributions to human-computer interaction and disaster informatics. She is a professor of computer science, professor of information science, and founding chair of information science at the University of Colorado Boulder. At Colorado, she directs a research project titled “Empowering the Public with Information during Crisis”, and is co-director of the Center for Software & Society. She also holds an adjunct affiliation with the University of Agder, and is a member of the CHI Academy.

Cloud and architecture

Development and languages

Quote of the week

Debugging time increases as a square of the program’s size.

        — Chris Wenham

Enterprises

Other news

Suscríbete al blog por correo electrónico

Introduce tu correo electrónico para suscribirte a este blog y recibir avisos de nuevas entradas.