Refactor. Using same code as in listing