Refactoring 'while' loop