-4

Is a class that contains a connection method and methods that do select, insert, update, delete, a violation of the single responsibility principle?

class Database:
  
  def create_connection(self, url):
    ...
  
  def select(self):
    ...
    
  def insert(self):
    ...
  
  def update(self):
    ...
    
  def delete(self):
    ...

Lucas Emanuel
  • 470
  • 2
  • 10
  • You should not see it as "do one thing". You should see it as: "a single reason to change". These are not laws. These are principles. You should not get lost in pointless discussions. The class looks completely ok. – Yavor Mitev Sep 07 '22 at 13:27

1 Answers1

1

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 {...}
...
DavS
  • 36
  • 3