dtdvbf37193 2009-06-01 22:59
浏览 83
已采纳

当有太多if-then-else使代码不可读时,如何坚持自我重复(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?

  • 写回答

6条回答 默认 最新

  • dousi7919 2009-06-01 23:03
    关注

    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>
    

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(5条)

报告相同问题?

悬赏问题

  • ¥15 请问如何在openpcdet上对KITTI数据集的测试集进行结果评估?
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路
  • ¥15 phython读取excel表格报错 ^7个 SyntaxError: invalid syntax 语句报错