Refactor common code and reduce nesting