【转】简单设计四原则

来源:互联网 发布:网络产品结构培训班 编辑:程序博客网 时间:2024/05/16 17:05
  1. 代码可以工作;
  2. 沟通、表达业务逻辑;
  3. 没有重复代码;
  4. 没有额外代码

这四条简单设计原则是OO训练营和C训练营的灵魂,我们通过这个标准来衡量每个人的代码。

Four Principles of Simple Design

  • It works
    • At the most basic level the code must do what it is supposed to do. green bar – tests pass.
  • It communicates
    • You should be able to read the code directly. The code itself should express its intent. The best world is where the code reads like english. people have dozens of years of practice understanding english and the closer your code gets to english the easier will be to read. That is why we use full parameter names (‘probability’ instead of ‘p’) and we use method names that clearly express the intent of the method. If your code requires a lot comments then the code itself is not communicating. Seeing comments in your code likely points to an opportunity to improve the way the code communicates and then delete the comments.
    • Short method names are prefered to long method names.
      • Long method names often indicate the method is doing too much and could be broken into simpler methods. for example if your method name has an ‘and’ in it then it is probably doing too much
    • Code should be easily understandable. if there are too many words it becomes harder to read and understand.
  • No duplicate code
    • Duplicate code creates barriers to maintanence and leads to the strong possibility of eventual contradiction. to work with duplicated code you have to know that it is duplicated and make modifications in all locations
    • DRY (don’t repeat yourself)
  • No extra code
    • Cost of ongoing maintanence
    • Having the extra code may inhibit good factoring of your code and hide valuable abstractions
    • You can’t predict the future: your understanding of the system/design changes, requirements change, etc
    • YAGNI (you ain’t gonna need it)
原创粉丝点击