Refactoring connection function