如果过多的if-then-else使得代码不可读,那么如何遵循“不重复自己(DRY)"原则? [英] how to adhere to the Don't-Repeat-Yourself (DRY) principle when there will be too many if-then-else making the code unreadable?

查看:161
本文介绍了如果过多的if-then-else使得代码不可读,那么如何遵循“不重复自己(DRY)"原则?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想坚持不要重复自己"的原则,但是有时候当我将HTML和CSS一起编写PHP时,如果我在不同情况下重复使用同一代码,那么我的代码很快就会做到这一点.许多if-then-else代码不容易维护.

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.

如果使用模板引擎Smarty,这可能是一个更大的问题,因为大多数代码编辑器不会匹配{if} {else} {/if},因此程序员需要在视觉上寻找匹配的标签,并且当嵌套{if} {else} {/if}有3或4个级别时,这并不容易.

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}.

在这种情况下,有没有办法坚持使用DRY,但仍然具有良好的可维护代码?

In such situation, is there a way to stick to DRY, but still have good maintainable code?

推荐答案

完整框架的简短内容,我倾向于对内容(即使包含逻辑)进行分离到文件中并使用另一个逻辑求值将它们合并在一起(合并它们),然后再评估模板逻辑.这会分块您的内容,并使分块在普通状态下可共享/重用.

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:

<h1>{{insert:shared_page_header}}</h1>

使用shared_page_header.txt可以使事情分开.这也迫使您即使在模板中嵌入的逻辑中也要注意关注点的分离. 任何事物(无论是否动态)的可管理,可重用的块始终是必经之路.您的模板只是字符串,直到经过评估,因此将它们视为合并的共享组件放入big-dirty-string(TM)中,然后进行评估.

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.

祝你好运

这篇关于如果过多的if-then-else使得代码不可读,那么如何遵循“不重复自己(DRY)"原则?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆