Replace three replicas of the same code with a function.