I came across some code like this today:
handleSubmit (formData) {
const { actions, doc } = this.props
actions.save({
...formData,
someField: parseInt(formData.someField, 10)
}, doc)
}
and while it's not terrible, it stands out that this function is doing more than it should. It knows how to:
- normalize the form data (convert
someField
to an int) - call the
save
action
If we rewrite those two things as separate functions:
normalizeFormData (data) {
return {
...data,
someField: parseInt(data.someField, 10)
}
}
handleSubmit (formData) {
const { actions, doc } = this.props
actions.save(this.normalizeFormData(formData), doc)
}
Now it reads more clearly, and we have an easy place to unit-test some edge cases in the normalizeFormData
pure function.
We've also gained some useful encapsulation. The handleSubmit
function only needs to know about forwarding the data to the right place. All of the knowledge of the nature of that data is contained in the normalizeFormData
function.