CodeSOD: Making the Thingie Work
Alyssa inherited some code from... well, she isn't entirely sure from whom. There are names that come up in git blame, but even for some more recent commits, Alyssa has no idea who they are. Contractors? Interns? Randos pulled in off the street and handed a keyboard?
Based on the code quality, the last option is surprisingly likely.
const endpoints = mainThingie?.endpoints ?? [];const filteredWidgets: WidgetWithEndpoint[] = widgets.filter( (widget): widget is WidgetWithEndpoint => { if (!widget.endpoint) return false; return endpoints.map((mainThingieEndpoint) => _.isEqual(widget.endpoint, mainThingieEndpoint)).includes(true); },);
The customers of this application are allowed to define their own custom widgets for certain pieces of data. The purpose of this block of TypeScript is to find all the widgets that map to this "Thingie"- and it's worth noting, these names are not anonymized. widgets come from one backend service, while "Thingie"s come from another. Their endpoints (stored locally in each backend service) must match.
So, how do we do this filtering? Well, first, we discard any widgets that don't have an endpoint. That makes sense.
Then, we map our "Thingie" endpoints, and this is where things start looking a bit weird. What are we converting an endpoint to? Well, a boolean value based on _.isEqual. _.isEqual does a deep comparison of two objects. Then, if that array contains a true value- the includes call- we know the widget has a matching "Thingie".
Now, one thing: endpoints have a clear ID field, suitable for a primary key, and thus is the only thing you actually need to compare- a deep comparison isn't needed. And in fact, it's the deep comparison that drew Alyssa's attention to this function.
One day, it was working fine. The next day it broke. One of the backend services added a field to the endpoint JSON, used by some of its consumers. This additional field broke the deep equality test.
The developers responsible have a habit of, "misusing libraries to do things they weren't intended to do," Alyssa writes, "and then bending over backwards in all the other places to accommodate that."
[Advertisement] ProGet's got you covered with security and access controls on your NuGet feeds. Learn more.