refactoring function and adding tests