Refactored code by moving up common code