Disclaimer: My experience is mainly development with statically typed languages, and even if I understand how dynamic types works, I'm not very familiar with the common practices, neither I'm very aware of the usual tips and tricks yet.
I recently started to work in a project where we use serverless and deploy some lambdas in AWS with javascript. After deep diving the existing code I found out a common practice that shocked me a bit:
When a lambda is invoked and it receives a JSON payload, there is an initial pre-processing, converting all the values in the object to strings.
const mapValues = require('lodash/mapValues')
const escape = require('validator/lib/escape')
...
const body = mapValues(requestBody, value => escape('' + value))
...
Then after that pre-processing, the real work begins (validation, processing, invoking other services, etc...)
My first thoughts this are:
Benefit: Helps to reduce the cognitive load of the possible different types, enabling to assume that everything will be always a string.
Downside: Extra complexity dealing with non-string values, such as numbers.
Q1: Are there any other benefits and pitfalls to using this approach?
Q2: Could this be considered a bad practice? If so, why? (facts, not opinions please)
Thanks in advance! :)
Interesting question. I suggest you to ask the author if they 're available. Here are some of my thoughts:
I argue having string values does not reduce but increase cognitive load, as you have to watch out to convert them when doing basic arithmetics. I am sure all of us have seen at least once 1+1
being 11
.
Also, handling every data as strings is a so bad practice it even has its own mock name: stringly typed. This is the cookbook example of that.
The only valid reason I can possibly imagine is to prevent various injection attacks against the service. In some scenarios, if the user is allowed to send in arbitrary json, it is possible to make the service execute code paths that it would not do normally. (something whacky like {"__proto__":[],"length":1,"0":"foo"}
coerects to "foo"
but is typeof object, this could bypass some flawed validation logic. mongodb is also prone to some attacks alike). But even in this case, proper validation would be much better than converting every value to string.