refactoring: factor out duplicate code