Refactor code to function