refactor to remove code duplication between branches of if block