我是一个糟糕的程序员,因为我正在复制和粘贴.一个例子是,每当我连接到数据库并检索记录集时,我将复制先前的代码并进行编辑,复制设置datagridview和编辑的代码.我知道短语代码重用,但我实际上并没有使用它.我如何利用代码重用,这样我就不必复制和粘贴数据库代码和datagridview代码.
代码重用的本质是采用通用操作并对其进行参数化,以便它可以接受各种输入.
以谦虚printf为例.想象一下,如果你没有printf,只有write,或类似的东西:
//convert theInt to a string and write it out.
char c[24];
itoa(theInt, c, 10);
puts(c);
Run Code Online (Sandbox Code Playgroud)
现在这很糟糕,每次都要写,而且实际上是有点儿.因此,一些聪明的程序员决定他厌倦了这一点,并写了一个更好的功能,一举打印到stdout.
printf("%d", theInt);
Run Code Online (Sandbox Code Playgroud)
你不需要像printf它的可变参数和格式字符串那样花哨.即使只是一个简单的例程,例如:
void print_int(int theInt)
{
char c[24];
itoa(theInt, c, 10);
puts(c);
}
Run Code Online (Sandbox Code Playgroud)
会很快地做到这一点.这样,如果要更改print_int为始终打印到stderr,您可以将其更新为:
void print_int(int theInt)
{
fprintf(stderr, "%d", theInt);
}
Run Code Online (Sandbox Code Playgroud)
现在你的所有整数都会被神奇地打印成标准错误.
您甚至可以将该函数和您编写的其他函数捆绑到一个库中,这只是您可以加载到程序中的代码集合.
遵循代码重用的做法就是为什么你甚至有一个数据库可以连接到:有人创建了一些代码来存储磁盘上的记录,重新设计它直到其他人可以使用,并决定将其称为数据库.
图书馆并没有神奇地出现.它们由程序员创建,以使他们的生活更轻松,并使他们更快地工作.
根据项目的规模可以改变答案。
对于较小的项目,我建议设置一个 DatabaseHelper 类来执行所有数据库访问。它只是打开/关闭连接和执行数据库代码的包装器。然后在更高的级别上,您可以编写将要执行的 DBCommand。
类似的技术可以用于更大的项目,但需要一些额外的工作,需要添加接口、DI,以及抽象出您需要了解的有关数据库的内容。
您还可以尝试研究 ORM、DAAB 或模式和实践小组
至于如何预防ole C&P?- 当您编写代码时,您需要定期检查它,如果您有类似的代码块,仅因一两个参数而变化,那么这始终是重构为自己的方法的良好候选者。
现在我的伪代码示例:
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
Run Code Online (Sandbox Code Playgroud)