How do programmers practice code reuse

前端 未结 14 1255
天涯浪人
天涯浪人 2021-02-13 14:14

I\'ve been a bad programmer because I am doing a copy and paste. An example is that everytime i connect to a database and retrieve a recordset, I will copy the previous code and

14条回答
  •  后悔当初
    2021-02-13 14:42

    Depending on the size of the project can change the answer.

    For a smaller project I would recommend setting up a DatabaseHelper class that does all your DB access. It would just be a wrapper around opening/closing connections and execution of the DB code. Then at a higher level you can just write the DBCommands that will be executed.

    A similar technique could be used for a larger project, but would need some additional work, interfaces need to be added, DI, as well as abstracting out what you need to know about the database.

    You might also try looking into ORM, DAAB, or over to the Patterns and Practices Group

    As far as how to prevent the ole C&P? - Well as you write your code, you need to periodically review it, if you have similar blocks of code, that only vary by a parameter or two, that is always a good candidate for refactoring into its own method.

    Now for my pseudo code example:

    Function GetCustomer(ID) as Customer
       Dim CMD as New DBCmd("SQL or Stored Proc")
       CMD.Paramaters.Add("CustID",DBType,Length).Value = ID
       Dim DHelper as New DatabaseHelper
       DR = DHelper.GetReader(CMD)
       Dim RtnCust as New Customer(Dx)
       Return RtnCust
    End Function
    
    Class DataHelper
      Public Function GetDataTable(cmd) as DataTable
        Write the DB access code stuff here.
        GetConnectionString
        OpenConnection
        Do DB Operation
        Close Connection
      End Function
      Public Function GetDataReader(cmd) as DataReader
      Public Function GetDataSet(cmd) as DataSet
      ... And So on ...
    End Class
    

提交回复
热议问题