Refactoring and error handling