As your class above has atleast two responsibilities i.e. creating a database connection and performing CRUD operations on the entities, so I think it violates the SOLID’s single responsibility principle.
You might create a seperate class to deal with the Database connection and register it as a dependency (through an interface) to the Database class that performs the CRUD operations. Here’s how it would look like:
//Pseudo code
interface IDatabaseConnection:
def create_connection(url):
...
class SqlDatabaseConnection implements IDatabaseConnection:
def create_connection(url):
...
class DatabaseService:
private IDatabaseConnection _dbConnection;
constructor(IDatabaseConnection dbConnection):
self._dbConnection = dbConnection
def select(self):
//use the dbConnection here to create a connection
//perform your select operation
...
def insert(self):
//use the dbConnection here to create a connection
//perform your insert operation
...
def update(self):
...
def delete(self):
...
Here’s how we will use it.
DatabaseService service = new DatabaseService(
new SqlDatabaseConnection(dbConnectionString)
);
...
service.insert(entity);
...
That also allows you use other SOLID priciples for the database connection.
Tip: If I would have hundereds of select operations, I might create seperate classes for CRUD operations something like below:
class SelectEntityDatabaseService implements ISelectEntityDatabaseService {...}
class CreateEntityDatabaseService implements ICreateEntityDatabaseService {...}
class UpdateEntityDatabaseService implements IUpdateEntityDatabaseService {...}
...
solved Does this class violate SOLID’s single responsibility principle? [closed]