samedi 24 avril 2021

Hard-coding & Redundant Code in Psycopg2 / PostgreSQL?

I am currently following a course on data engineering, and am a bit dumbfound by the examples and exercices provided in the data modeling section:

Everything is hardcoded and "copy-paste" rules the place...

Here is a brief example:

try: 
    cur.execute("INSERT INTO music_store2 (transaction_id, customer_name, cashier_name, year, albums_purchased) \
                 VALUES (%s, %s, %s, %s, %s)", \
                 (1, "Amanda", "Sam", 2000, "Rubber Soul"))
except psycopg2.Error as e: 
    print("Error: Inserting Rows")
    print (e)

try: 
    cur.execute("INSERT INTO music_store2 (transaction_id, customer_name, cashier_name, year, albums_purchased) \
                 VALUES (%s, %s, %s, %s, %s)", \
                 (1, "Amanda", "Sam", 2000, "Let it Be"))
except psycopg2.Error as e: 
    print("Error: Inserting Rows")
    print (e)
    
try: 
    cur.execute("INSERT INTO music_store2 (transaction_id, customer_name, cashier_name, year, albums_purchased) \
                 VALUES (%s, %s, %s, %s, %s)", \
                 (2, "Toby", "Sam", 2000, "My Generation"))
except psycopg2.Error as e: 
    print("Error: Inserting Rows")
    print (e)
    
try: 
    cur.execute("INSERT INTO music_store2 (transaction_id, customer_name, cashier_name, year, albums_purchased) \
                 VALUES (%s, %s, %s, %s, %s)", \
                 (3, "Max", "Bob", 2018, "Help!"))
except psycopg2.Error as e: 
    print("Error: Inserting Rows")
    print (e)
    
try: 
    cur.execute("INSERT INTO music_store2 (transaction_id, customer_name, cashier_name, year, albums_purchased) \
                 VALUES (%s, %s, %s, %s, %s)", \
                 (3, "Max", "Bob", 2018, "Meet the Beatles"))
except psycopg2.Error as e: 
    print("Error: Inserting Rows")
    print (e)

I must confess that, at first sight, I can't help but think that this is really poorly written, hard to maintain code and that using variables and loops instead would be much better.

However, remembering that I can sometime be an ignorant and arrogant simpleton, I step back and refrain from jumping to conclusion.

Could it be that this actually is standard practice ?

Could all this hard coding and copy-pasting be here for a good reason ?

Many thanks in advance for your comments

Aucun commentaire:

Enregistrer un commentaire