Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it common to set objects to nil?

Tags:

ruby

I am building an app and wonder if setting an unused object to nil is a common practice in production level coding.

I understand that it is a mere hint for the garbage collector and won't always dispose of an object.

like image 781
user1000232 Avatar asked Jan 01 '13 02:01

user1000232


People also ask

What is a nil object?

Well, nil is a special Ruby object used to represent an “empty” or “default” value. It's also a “falsy” value, meaning that it behaves like false when used in a conditional statement. Now: There is ONLY one nil object, with an object_id of 4 (or 8 in 64-bit Ruby), this is part of why nil is special.

What does setting an object to null do?

The value null represents the intentional absence of any object value. It is one of JavaScript's primitive values and is treated as falsy for boolean operations.

Is nil an object in Ruby?

In Ruby, nil is—you've guessed it—an object. It's the single instance of the NilClass class. Since nil in Ruby is just an object like virtually anything else, this means that handling it is not a special case.


2 Answers

According to this thread

If you are done using a member object setting it to nil will provoke the referenced object to be garbage collected. If it is a local variable the method exit will do the same thing.

That said I would question your design if you require a member to be explicitly set to nil.

like image 109
Trent Earl Avatar answered Oct 01 '22 08:10

Trent Earl


No, it is not common practice. There are only rare cases, where you explicitly set object to nil.

For example, in the implementation of some data structures it makes sense to set objects to nil. Let's say you implement a cache and you provide an method to delete a key. Let us further assume that the cache internally uses an array that holds references to the deleted object. Then it is recommended to delete all references to the deleted object by setting them to nil.

However, in practice, these situations do not occur very often.

like image 42
Philipp Claßen Avatar answered Oct 01 '22 10:10

Philipp Claßen