Refactoring: code in functions, re-ordering