Refactoring Database Connections for Better Maintainability in ProyectoTransversalG14
Improving Project Architecture
In the ProyectoTransversalG14 project, a Java-based application utilizing MariaDB, we recently undertook a refactoring effort to improve code cleanliness and security. Our primary goal was to modernize the way we manage database connectivity, moving away from hardcoded or redundant connection logic.
The Problem: Redundant Connectivity Logic
Previously, the application relied on a dedicated connection class that manually handled database access. This approach often leads to tight coupling, making it difficult to swap database configurations or implement robust connection pooling.
Think of the old connection logic as having a dedicated, static courier for every single message you want to send—it's inefficient and creates a bottleneck when you need to scale. By removing this manual connection class, we can move towards a more centralized, standard approach for managing data access.
Implementation Steps
1. Removing Manual Connections
The first step involved decommissioning the specific connection class. By stripping away this boilerplate, we reduce the footprint of our codebase and move towards using standard interfaces for persistence.
2. Updating Environment Configuration
After removing the custom connection class, it is crucial to ensure that environment-specific settings are managed securely. Always use .gitignore to prevent sensitive credentials from being committed to your version control system.
// Avoid hardcoding credentials. Use a Configuration Provider
public class DatabaseConfig {
public static Connection getConnection() throws SQLException {
String url = System.getenv("DB_URL");
String user = System.getenv("DB_USER");
String password = System.getenv("DB_PASS");
return DriverManager.getConnection(url, user, password);
}
}
This approach uses environment variables, ensuring that your actual database credentials remain outside of the source code.
Outcomes
By simplifying the codebase and removing unnecessary classes, the project is now leaner and follows better security practices regarding environment configuration. This refactoring sets the stage for implementing more advanced dependency injection patterns in the future.
Takeaways
- Always prefer environment variables over hardcoded connection strings.
- Keep your codebase clean by removing redundant utility classes that can be handled by standard libraries or frameworks.
- Use
.gitignorestrictly to protect your configuration files and credentials.
Generated with Gitvlg.com