当太多 if-then-else 导致代码不可读时,如何遵守 Don’t-Repeat-Yourself (DRY) 原则?
我想遵守“不要重复自己”的原则,但有时当我将 PHP 与 HTML 和 CSS 一起编写时,如果我在不同的情况下重复使用相同的代码,我的代码很快就会有很多 if-那么-否则代码不容易维护。
如果使用模板引擎Smarty,这可能是一个更大的问题,因为大多数代码编辑器都不会匹配 {if} {else} {/if} 所以程序员需要直观地寻找匹配的标签,这并不容易当有 3 或 4 层嵌套的 {if} {else} {/if} 时。
在这种情况下,有没有办法坚持 DRY,但仍然有良好的可维护代码?
I'd like to adhere to the Don't-Repeat-Yourself principle, but sometimes when I write PHP together with HTML and CSS, if I re-use the same code for different situations, my code soon will have so many if-then-else that the code is not easily maintainable.
This may be a bigger issue if Smarty, the templating engine is used, because most code editor won't match up {if} {else} {/if} So the programmer needs to look for the matching tag visually, and is not easy when there are 3 or 4 levels of nested {if} {else} {/if}.
In such situation, is there a way to stick to DRY, but still have good maintainable code?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
只是为了让我们有更多信息...您使用什么程序来编写代码?
避免重复的提示:
使用某种模板。这样做可以让您不必重复代码来在每个页面中显示内容。 IE 如果您的网站有 20 个页面,并且您决定更改布局,那么您不希望必须遍历然后更改所有 20 个页面。
使用函数。如果您有执行特定任务的代码,请勿在整个程序/页面中多次编写该代码。 创建一个函数,然后在需要执行该任务的每个位置调用它。 这样,如果您需要进行更改,您只需修改该函数,而不必搜索代码来查找执行该任务的每个位置。 如果您了解课程和课程 方法(方法是类中的函数),对于许多任务来说,这甚至更好,因为它为您提供数据封装并允许您将相关函数分组在一起,以便您可以根据需要在将来的项目中包含该类。
如果您在处理大量 if/else 语句和代码可读性不佳时遇到困难,您可以执行以下操作:
1. 考虑尝试新的编辑器。代码折叠是必须的。 有些编辑器还具有垂直线,可以突出显示并匹配缩进的代码,以便您知道什么与什么搭配。 如果你想要一个像样的免费编辑器,我会推荐 Notepad++,因为它具有这两个功能(只需谷歌它,我无法在此处添加链接)。
2. 您可以使用一些技术来减少嵌套 if 语句的数量...
示例(此代码):
也可以展平为:
因此,如果您有 3 或 4 层嵌套 if/else如果您想将它们展平,您可能会发现使用多个参数(例如上面的参数)使您的代码更具可读性。 它做同样的事情,这只是你偏好哪种方式的问题。
尝试不要混合你的逻辑(我假设 PHP)和你的显示(我假设 HTML/CSS)。这并不总是那么容易做到,但是使用模板和 CSS,这是可能的。 让我给您一个实际的示例,说明如何在主页上执行此操作,该主页将用户名显示为欢迎消息。
内联 PHP(尽量避免):
逻辑与显示分离(更好):
^ 将逻辑与视图 (HTML) 分离将有助于您在项目开始变得非常复杂时不会不知所措。 最好不要混合! :)
祝你好运!
Just so we have more info... What program are you using to write your code?
Tips for not repeating yourself:
Use some sort of templates. Doing this keeps you from having to repeat code for displaying content in each of your pages. I.E. If you have a site with 20 pages and you decide to change your layout, you don't want to have to go through and then change all 20 of your pages.
Use functions. If you have code that performs a specific task, DON'T write that code multiple times throughout your program/page. Create a function and then call it in each spot where you need that task performed. That way if you need to make a change you just modify that one function and don't have to search through your code to find every place that you performed that task. If you know about classes & methods (a method is a function in a class), for many tasks, this is even better as it provides you with data encapsulation and allows you to group related functions together so that you can include the class in future projects as needed.
If you are having difficulty with lots of if/else statements and code not being very readable there are a few things you can do:
1. Consider trying a new editor. Code folding is a must. Some editors also have vertical lines that highlight and match up indented code so you know what goes with what. If you want a decent free editor, I would recommend Notepad++ as it has both these features (just google it, I can't add links here).
2. There are techniques you can use to reduce the number of nested if statements that you have...
Example (this code):
Can also be flattened out into:
So if you have 3 or 4 levels of nested if/elses and you want to flatten them out, you may find your code more readable to use multiple arguments such as above. It does the same thing, it's just a matter of preference for which way you do it.
Try and not mix your logic (I'm assuming PHP) and your display (I'm assuming HTML/CSS). This is not always easy to do, but using templates and css, it is possible. Let me give you a practical example of how you can do this on a home page that displays a users name as a welcome message.
Inline PHP (try to avoid):
Logic separate from display (better):
^ Keeping your logic separate from your view (HTML) will help you not get overwhelmed when your project starts getting really complex. It's best just not to mix! :)
Good luck man!
在缺乏完整框架的情况下,我倾向于对内容(即使它包含逻辑)进行将其分离到文件中,并使用另一个逻辑评估将它们合并在一起(破坏它们),然后评估之后的模板逻辑。 这会将您的内容分块,并使块在公共状态下可共享/可重用。
这样,每个最终模板缓冲区都是离散可重用内容块的扁平树,您可以将其存储在磁盘或数据库上。 即使是像一个小解析器这样简单的东西替换:
With
shared_page_header.txt
也有助于保持事物的独立性。 它还迫使您考虑关注点的分离,即使是在模板中嵌入的逻辑中也是如此。 可管理、可重用的任何内容块(动态或非动态)始终是最佳选择。 您的模板在评估之前只是字符串,因此请将它们视为合并到到 big-dirty-string(TM) 中的共享组件,然后进行评估。祝你好运
Short of a full framework, what I tend to do for content (even if it contains logic) is separate it out into files and use another logical evaluation to merge them together (mangle them) and then evaluate the templating logic after that. This chunkifies your content and makes chunks sharable / reusable on common state.
This way each final template buffer is a flattened tree of discrete re-usable content nuggets that you can store on disk or a database. Even something as simple as a little parser that replaces:
With
shared_page_header.txt
helps keep things separate. It also forces you to look at separation on concerns even in the logic that is embedded in your templates. Manageable, reusable chunks of anything (dynamic or not) are always the way to go. Your templates are just strings until evaluated, so treat them as shared components merged into a big-dirty-string(TM) and then evaluated.Good Luck
IMO,你问题的第一句话就是问题所在。 您确实不应该将代码与视图(即 HTML 和 CSS)混合在一起。 有几个 PHP MVC 框架可以帮助您避免这样做。 Zend 框架相当不错,但还有其他框架。
如果您不想使用框架,那么我建议重构您的页面,不要使用这样的代码并在后端调用对象。 混合代码和视图很快就会在任何语言中变得难以维护,而不仅仅是 PHP。
The first sentence of your question is the problem, IMO. You really shouldn't be mixing code with your view (i.e. HTML and CSS). There are several PHP MVC frameworks that will help you not do this. The Zend framework is pretty decent but there are others as well.
If you don't want to use a framework, then I'd suggest refactoring your pages to not use code like this and call objects on the back end. Mixing your code and view quickly becomes unmaintainable in any language, not just PHP.
现在我可能不太熟悉使用 PHP 实现 OOP 概念,但是重构那些嵌套的 if-else 语句并将它们放置在一个命名良好的函数中有助于遵循 DRY 原则。 此外,坚持 DRY 原则确实可以使您的代码易于维护。
Now I may not be that familiar with implementing OOP concepts using PHP, but refactoring those nested if-else statements and placing them in a well-named function helps a lot in keeping up with the DRY principle. And besides, sticking with the DRY principle does make your code maintainable.
通过示例脚本文件,我们可以更容易地指出您出错的地方,但是有些事情可能会或可能不会帮助您,具体取决于您想要实现的目标:
看看控制结构的替代语法。 有些人在编写主要包含 HTML 的文件时更喜欢使用这种风格,而 PHP 仅用于决定输出哪些 HTML 部分。
将可重用的代码部分分割成稍后可以包含的文件,即。 header.php、footer.php 等。
使用支持代码折叠的 IDE
祝你好运
With an example script file it would be a lot easier for us to point out where you are going wrong, however some things which may or may not help you depending on what you are trying to achieve:
Taking a look at alternative syntax for control structures. Some people prefer to use this style when writing files which mainly contain HTML, with PHP being used only to decide which HTML sections to output.
Split up the reusable sections of code into files which you can later include, ie. header.php, footer.php etc.
Using an IDE which supports code folding
Good luck
如果语句被认为是逻辑语句,则应在视图中尽可能避免它们,因为它们违反了 MVC 原则。
切换到视图助手,例如:
此代码是可重用的、可测试的,将使您的代码保持干燥:)
If statements are considered to be logic statements, they should be avoided in views as much as possible as they violate MVC principles.
Switch to view helpers instead, for example:
This code is reusable, testable, will keep your code dry :)