Skip to content

Latest commit

 

History

History
38 lines (29 loc) · 1.11 KB

24-013.md

File metadata and controls

38 lines (29 loc) · 1.11 KB

functions that know how to do one thing

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:

  1. normalize the form data (convert someField to an int)
  2. 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.