Refactoring connection code