我正在编写一些 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_yourself 和 http://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/