美文网首页
💻 6.005.1x - Week 2 part.a

💻 6.005.1x - Week 2 part.a

作者: 秋衣队长 | 来源:发表于2019-01-07 17:16 被阅读0次

目录:

  • I. Assertion —— 关于assert的写法和指南
  • II. Scope Minimization —— 如何控制scope来减少debug的困难

I. Asserstion

1. Fail fast

point out bug as soon as possible

public double sqrt(double x){
        if (! (x >= 0) ) throw new AssertionError();
}
2. defensive checks
assert (x >= 0) : "x is " + x // the error message ;
3. What to assert:
  1. argument 方法调用参数的限制
  2. return value 返回值的合理性
  3. covering all cases 不合法的cases,比如,method要求是aeiou的元音,其他的字母就是illegal cases.
4. What not to assert:
  1. runtime assertion 合理使用assertion,它会污染你的代码。比如,👇💩

     // don't do this:
     x = y + 1;
     assert x == y+1;
    
  2. external conditions 代码外部的东西,比如file是否存在、网络能不能用、user输入是否正确。这些external failures不该使用assertion,而是使用exception。

  3. release。通常assertions只有testing和debugging阶段才会使用,正式release给用户时,assertions会被关闭。


II. Scope Minimization

1. Modularity

就是模块化,它的反面就是monolithic,比如一个超长的main()

2. Encapsulation

把一个module围起来,控制它的作用范围,所以这个module只会影响其内部的行为,不会干扰到其他module。

access control就是一种encapsulation:用 publicprivate

另一种encapsulation就是variable scope:下面两个例子的差别,第一个i是global variable,第二个i是local variable,所以第二个更好。

public static int i;
for (i =0; i < 100; ++i) {
    doSomeThings();
}

for (int i = 0; i < 100; ++i) {
    doSomeThings();
}
3. Tips for minimizing variable scope
  1. 在loop initializer中宣告变量:case 2 比 case 1好。

     // case 1
     int i; // don't do this
     for (i = 0; i < 100; ++i) {
    
     // case 2
     for (int i = 0; i < 100; ++i) {
    
  2. { ... }中宣告变量

  3. 避免使用global variables


自学第二个礼拜,感觉蛮好的。上礼拜天偷懒了一天,拖延到了这礼拜一。
不过,之前关于spec和testing的知识点其实还是要梳理过,然后关于class和OOP的东西,还需要看更多doc来熟悉java。
Ronn Liu 🙋‍♂️
2019/01/07 - 2019/01/013 📌

相关文章

网友评论

      本文标题:💻 6.005.1x - Week 2 part.a

      本文链接:https://www.haomeiwen.com/subject/bptprqtx.html