CodeSOD: The Hash Array
When Arbuzo joined a new team, they helpfully provided him some sample code to show him how to interact with their JSON API. It was all pretty standard-looking stuff. If, for example, they fetched a Customer object, it would have some fields about the customer, and an array containing links to orders that customer had made. One of the samples helpfully showed iterating across the orders array:
let i = 1;while(cust.orders[i]) { //do stuff with cust.orders[i] i++;}
That got Arbuzo's attention, because it's such a weird and wrong way to solve this problem. Even if we ignore the arbitrary "start the array at 1" choice, it's such an awkward way to iterate across an array.
When Arbuzo checked the actual response data, however, he realized they weren't iterating across an array:
{ "cust_id": 55, "cust_name": "Dewey, Cheatum, and Howe LTD", "cust_addr": ..., ..., "orders": { "1": "customer/55/orders/1", "2": "customer/55/orders/2", ... "8": "customer/55/orders/12" }}
There are cases where might want to have a map indexed by integers, like for example if you were making a sparse array. This is not one of those cases- all the order entries for each customer are simply incremented. I call this particular anti-pattern the "hash array": you're using a map to implement an array.
Abruzo couldn't rewrite the service, so he did the next best thing, and added a step to the response handling which did: cust.orders = Object.values(cust.orders) to turn things back into a proper array. Unfortunately, this wasn't the style laid out in the sample code Abruzo had been handed at the start, so it was rejected, and he also got to write lots of weird while constructs to traverse the hash arrays.
[Advertisement] Keep the plebs out of prod. Restrict NuGet feed privileges with ProGet. Learn more.