Refactor to use defer