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条)

报告相同问题?

悬赏问题

  • ¥30 python代码,帮调试
  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条