哪里变量= null作为"对象毁坏"来自?变量、对象、null、QUOT

2023-09-03 05:40:08 作者:-追梦少年*

工作的若干写​​在各种版本的.NET的遗留系统,在许多不同的公司,我一直在寻找的以下模式的例子:

Working on a number of legacy systems written in various versions of .NET, across many different companies, I keep finding examples of the following pattern:

public void FooBar()
{
    object foo = null;
    object bar = null;

    try
    {
       foo = new object();
       bar = new object();

       // Code which throws exception.
    }
    finally
    {
       // Destroying objects
       foo = null;
       bar = null;
    }

}

要有人懂得如何内存管理可以在.NET中,这种code是不必要的痛苦;垃圾收集器不需要你手动分配来告诉大家,旧的对象可以被收集,也没有指定指示GC立即收集的对象。

To anybody that knows how memory management works in .NET, this kind of code is painfully unnecessary; the garbage collector does not need you to manually assign null to tell that the old object can be collected, nor does assigning null instructs the GC to immediately collected the object.

此模式仅仅是噪音,使其难以明白什么是code要达到的目的。

This pattern is just noise, making it harder to understand what the code is trying to achieve.

那么,为什么做我一直在寻找这种模式?有一所学校,教这种做法?有没有一种语言中指定值,以局部范围变量需要正确地管理内存?是否有明确分配了一些附加的价值,我没有percieved?

Why, then, do I keep finding this pattern? Is there a school that teaches this practice? Is there a language in which assigning null values to locally scoped variables is required to correctly manage memory? Is there some additional value in explicitly assigning null that I haven't percieved?

推荐答案

这是 FUD 货物邪教编程(感谢丹尼尔埃里克)谁是用来免费资源,坏的GC实现开发者和糟糕的API。

It's FUDcargo cult programming (thanks to Daniel Earwicker) by developers who are used to "free" resources, bad GC implementations and bad API.

有些地方选区没有与循环引用妥善应付。要摆脱他们,你必须打破这一循环的地方。哪里?那么,如果有疑问,则随处可见。做了一年,它的移动到你的指尖。

Some GCs didn't cope well with circular references. To get rid of them, you had to break the cycle "somewhere". Where? Well, if in doubt, then everywhere. Do that for a year and it's moved into your fingertips.

另外设置字段设置为为您提供了做什么,因为作为开发者,我们总是害怕来忘记的事的想法。

Also setting the field to null gives you the idea of "doing something" because as developers, we always fear "to forget something".

最后,我们的API,必须明确地关闭,因为没有真正的语言支持,说关闭这个时候我用它受够了,并让计算机的数字出来,就像用GC。所以,你必须有一个API,你必须调用清理code和API,你不知道。这吸引并鼓励模式,如上述。

Lastly, we have APIs which must be closed explicitly because there is no real language support to say "close this when I'm done with it" and let the computer figure it out just like with GC. So you have an API where you have to call cleanup code and API where you don't. This sucks and encourages patterns like the above.