程序员修炼之道
一 资源的配平:有始有终,
对于多种资源需求
1 释放的顺序与分配的顺序相反,以防止资源浪费。
2 总是以相同的顺序分配资源,防止死锁。
二 配平与异常:
异常会打乱程序的正常执行逻辑,从而打乱资源配平原。如何处理取决于语言。
在c++中:
try {
//....
Node *n= new Node;
}catch {
delete n;
throw ;
}
delete n;
重复删除 违反DRY,so 利用局部对象退出包含块时会被自动清除,you can change it to be a object contain a point .
在java 有GC,and finally ,but i don't know why GC can't fix it alone?is it necessary to add the finally statement ?
三 无法配平
程序中确实需要某一块长期存在的动态内存块,SO HOW TO FIX ?
there must be a top block to manage the memory,then we have 3 choices to free it.
3 choices:
1 make a recursion to free it from top to bottom.
2 just free itself ,and disert its children rudely.
3 free itself ,and chilldren manage itself.
answer to prectice.
in c++ and java when you free a point ,why make p = null ? is there differences between them?
1 c++ in case of wild point.p == null is a running error,so it is possible to be checked.
2 java :it is convenience for garbage collection, p = null means the count of the object which p point at --,when p = 0,gc begint to finish it;
二
how to make couple minimize between modules?
(Principal of) Least Knowledge,(The) Law of Demeter。
what is exactly it ?
don't talk with stranger .in the method you just access method directly by stack/heap object created inside it,the member of class ,and arguments .
if you wanna use the method in the third class ,you can access it by the second class .of cause you need to package the interface in the second one.