Refactoring with a while loop