Refactor some duplicated code into helper functions.