php - 功能与重复代码

标签 php function code-generation

我正在编写一些 PHP 代码以使用 FPDF 库创建 PDF。我基本上使用相同的 4 行代码来打印文档的每一行。我想知道哪个更有效率,一遍又一遍地重复这 4 行,或者将它变成一个函数会更好?我很好奇,因为感觉函数会有更大的开销,因为函数只有 4 行长。

我质疑的代码如下所示:

$pdf->checkIfPageBreakNeeded($lineheight * 2, true);
$text = ' label';
$pdf->MultiCell(0, $lineheight, $text, 1, 'L', 1);
$text = $valueFromForm;
$pdf->MultiCell(0, $lineheight, $text, 1, 'L');
$pdf->Ln();

最佳答案

这应该回答它: http://en.wikipedia.org/wiki/Don%27t_repeat_yourselfhttp://www.codinghorror.com/blog/2007/03/curlys-law-do-one-thing.html

Curly's Law, Do One Thing, is reflected in several core principles of modern software development:

  • Don't Repeat Yourself

    If you have more than one way to express the same thing, at some point the two or three different representations will most likely fall out of step with each other. Even if they don't, you're guaranteeing yourself the headache of maintaining them in parallel whenever a change occurs. And change will occur. Don't repeat yourself is important if you want flexible and maintainable software.

  • Once and Only Once

    Each and every declaration of behavior should occur once, and only once. This is one of the main goals, if not the main goal, when refactoring code. The design goal is to eliminate duplicated declarations of behavior, typically by merging them or replacing multiple similar implementations with a unifying abstraction.

  • Single Point of Truth

    Repetition leads to inconsistency and code that is subtly broken, because you changed only some repetitions when you needed to change all of them. Often, it also means that you haven't properly thought through the organization of your code. Any time you see duplicate code, that's a danger sign. Complexity is a cost; don't pay it twice.

关于php - 功能与重复代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3388166/

相关文章:

java - 为什么外部类在泛型类型名称中出现两次?

php - 检测到意外导航时显示验证码以防止流量滥用

c++ - 初始化指针传递的数组

c - 使用函数填充 C 中的数组

javascript - 如何确保 parseInt() 函数不返回意外结果

scala - 如何从 AutoPlugin 修改 Compile 中的 sourceGenerators?

visual-studio-2010 - 如何从 PowerShell 脚本触发 T4 模板

php - isset 函数不适用于表单提交和数据库插入语句

php - 在 PHP 中声明一个类的 ctor 'final' 是不好的做法吗?

php - Codeigniter 包含在 View 中