Say I have a library function that expects a JSON-encoded object and does some things with it:
function foo(bar) {
const baz = JSON.parse(bar);
doTheThing(baz);
doTheOtherThing(baz.qux);
}
Now I encounter an object that is not already JSON-encoded but I want to do the same things with it. Since I don't want to touch the library that includes foo()
, I just do this:
const bar = JSON.stringify(baz);
foo(bar);
That this is bad should be obvious; we should have a version of foo()
that takes as input the unencoded object to avoid the wasted (and perilous) roundtrip through JSON. However, I've seen variations on this antipattern repeated many times in my career. It has nothing to do with Javascript or JSON; it could be Unicode encodings or image file formats or whatever, but the essence of the problem is that the cost of changing the existing code is perceived to be so high that we end up writing code that shoehorns data into some format just so it can be translated back into a useable format later.
I have to think that someone has previously described this problem. My search-fu is probably not just not good enough to find that discussion. Does this antipattern have a name?