samedi 23 octobre 2021

How to implement behaviour in multiple classes?

Suppose n classes, each one of those got the same behavior at insertion in database:

  1. create connection
  2. query definition
  3. data for query definition
  4. error handling(in case duplicated or integrity errors in database)
  5. close connection

Some of the classes don't need this implementation, others need one implementation(says insert_user implementation) and other ones need two or more implementation(insert_reasons, insert_reason_video each one of those with different query, data definition and error handling)

How can I avoid copy/paste code. I'm coding in python

class One:
    def insert_objects(self, objects=None):
        db, cursor = open_connection()
        query_insert_object = """INSERT INTO objects (name, model_id)
        VALUES (%s,(SELECT id FROM models WHERE name=%s));"""
        try:
            for object in objects:
                object_data = (object, self.name)
                cursor.execute(query_insert_object, object_data)
            db.commit()
        except IntegrityError as e:
            if e.msg == "Column 'model_id' cannot be null":
                print("model_id no ha sido insertado, inserte el modelo")
            if e.msg == "Duplicate entry 'perrito-3' for key 'name'":
                print("model.name-object.name previamente insertado para el modelo: {}".format(self.name))
            db.rollback()
        finally:
            close_connection(db, cursor)

    def insert_model(self):
        db, cursor = open_connection()
        query_insert_model = """INSERT INTO models(name) VALUES (%s);
        """
        data_model = (self.name)
        try:
            cursor.execute(query_insert_model, data_model)
            db.commit()
        except IntegrityError a e:
            print("model.name previamente insertado con valor: {}".format(self.name))
            db.rollback()
        finally:
            close_connection(db, cursor)

class Two:
    def insert_user(self):
        db, cursor = open_connection()
        query_insert_user = """INSERT INTO users (id, name) VALUES (%s,%s);"""
        data_user = (self.id, self.name)
        try:
            cursor.execute(query_insert_user, data_user)
            db.commit()
        except IntegrityError:
            print("user.id previamente insertado con valor: {}".format(self.id))
            db.rollback()
        finally:
            close_connection(db, cursor)
.
.
.
class N:
    def insert(self):
        """Generalization of above code"""
        db, cursor = open_connection()
        query = get_query()
        data = get_data()
        try:
            execute_insert()
        except:
            error_handling()
        finally:
            close_connection()

Note: I've already seen Strategy Pattern but still no found solution for multiple implementations

Aucun commentaire:

Enregistrer un commentaire