How reduce code repitition in the given code?

Viewed 47
class TransactionAccess
{
    public static void GetTransactions()
    {
        string connString = "Host=localhost;Username=postgres;Password=1234;Database=ExpenseManagerDB";
        using (var connection = new NpgsqlConnection(connString))
        {
            var transactions = connection.Query<TransactionView>(@"SELECT t.transaction_id,t.account_id,a.account_name, a.type,t.note, t.amount, t.date
                                                               FROM account AS a
                                                               INNER JOIN transaction AS t ON a.account_id = t.account_id");
            transactions.Dump();
        }
    }

    public static void GetTransactionInfo(int id)
    {
        string connString = "Host=localhost;Username=postgres;Password=1234;Database=ExpenseManagerDB";
        using (var connection = new NpgsqlConnection(connString))
        {
            var transactionInfo = connection.Query<TransactionView>(@"SELECT a.account_name, a.type, DATE(t.date), t.amount, t.note, t.transaction_id 
                                                                  FROM transaction AS t 
                                                                  INNER JOIN account AS a ON t.account_id = a.account_id 
                                                                  WHERE t.transaction_id = @id", new { id });
            transactionInfo.Dump();
        }
    }

}

In the above code, I am using connString and connection many times in every function sepeartely. How to reduce and that and use only one connection and connString?

1 Answers

You're already seeing that you have code duplication (that's the commonly used term) inside your class. You are now storing them in each method seperately. How about storing them inside your class?

Related