Refactoring code for better nesting