Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where did variable = null as "object destroying" come from?

Tags:

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;     }  } 

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.

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

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?

like image 553
Paul Turner Avatar asked Jun 28 '10 12:06

Paul Turner


1 Answers

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".

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.

like image 158
Aaron Digulla Avatar answered Oct 29 '22 07:10

Aaron Digulla