Code refactoring for connection opening/closing