0

In the following code I have two classes. When the Nation class is instantiated to an object, it also instantiates an object for the Population class with a reference to the nation object.

class Nation

  def initialize(name)
    @name = name
    @population = Population.new(self)
  end

end

class Population

  def initialize(nation)
    @nation = nation
  end

end 

pry(main)> n = Nation.new("Germany")
=> #<Nation:0x0000000b3179e0 @name="Germany", @population=#<Population:0x0000000b3179b8 @nation=#<Nation:0x0000000b3179e0 ...>>>

Is this the case of circular reference?

Is it something that should be avoided?

Why is the Ruby interpreter not giving any errors? Isn't this leading to a kind of infinite recursion? When I create object n, it comes with a reference to object p, which comes with a reference to object n, which comes with a reference to object p... so how is the interpreter not going is some kind of infinite loop, as when you have a recursive function, which eventually terminates with a stack too deep error?

How could I refactor code like this where objects need to know about each others?

0

3 Answers 3

1

It's an old question, but I didn't see a good answer, so taking a crack at it.

Having two objects reference each other is not a problem, just like having two people point finger at each other is not a problem. However, if somebody tries to follow these pointers, never realizing that they are going back and forth, then it's a problem.

When you ran this code:

pry(main)> n = Nation.new("Germany")

You created 2 objects that point at each other, there is no problem. However, because you wrote the above line in an pry session, ruby tried to output the resulting object for you to see…

=> #<Nation:0x0000000b3179e0 @name="Germany", @population=#<Population:0x0000000b3179b8 @nation=#<Nation:0x0000000b3179e0 ...>>>

… and this is a problem. When ruby renders and object like that, it traverses all the instance variables in the object recursively, and prints them out. Since your variables have a circular reference, this traversing could make ruby go back and forth forever. That is, if ruby never realizes that it's going back and forth.

So why did it stop?

Ruby's inspect can realize it's going back and forth. When ruby recursively traverses objects, it keeps track of objects it's already seen. As soon as it encounters the same object twice, it stops and outputs the ... to prevent any further looping.

Are circular references to be avoided?

It depends on what you're doing, and with which libraries. The most common reason to traverse objects recursively (besides inspecting them) is serialization into JSON, YAML, etc.

If you are going to serialize objects, it's best to avoid circular references. There are some libraries out there that have clever techniques to serialize circular references, but if you can help it, avoid additional complexity. Serialization is complex enough as it is.

Bottom line: circular references are good for runtime convenience, and bad for recursively traversing or serializing objects. Use it like a sharp knife, with extra care.

3
  • In your sentence "The most common reason to traverse objects recursively is serialization", did you mean to say: "the most common reason to NOT traverse objects recursively is serialization"? I'm asking because in the very next paragraph you contradict yourself by saying "If you are going to serialize objects, it's best to avoid circular references".
    – Redoman
    Jul 22, 2022 at 14:51
  • 1
    @Redoman Oh, no that wasn't a mistake. "Traversing objects recursively" just means going through all variables, sub-variables, sub-sub-variables, etc. It's a normal thing to do for all serialization. The problem is when there is a circular reference in those variables. Then it's bad. "Traversing recursively" is not the same as "traversing circularly". :) Jul 22, 2022 at 23:29
  • thanks for the clarification! Had to wait 6 years for that but now I finally have a clearer picture :) Will mark your answer as the right one!
    – Redoman
    Jul 23, 2022 at 1:13
0

Isn't this leading to a kind of infinite recursion?

Nope, there's no infinite loop/recursion. You create a nation, it creates a population and that's it. However, if, when created, population were to create a nation too, that would lead to an infinite recursion. But in this form, the code is fine.

2
  • I understand that there are only 2 objects involved and not infinite number of objects, but they reference each other, don't they? So isn't this called circular reference? I think this is somehow causing weird problems with my code. For example, in the real code, in the nation object I have an array which contains references to other objects, which in turn have reference to nation. Sometimes I .compact this array (to remove nils), but if I inspect the nation through the array items (which reference nation), they still show a nation object with an array containing some nil values!
    – Redoman
    Nov 26, 2016 at 14:11
  • @jj_: the objects and reference themselves do not cause any problems. But you may encounter some problems, depending on how you walk the references. I couldn't get a clear picture of a problem from your comment. Nov 26, 2016 at 14:26
-1

Is this the case of circular reference?

In most langs, yes, but not in ruby. Why?, ruby is an interpreted lang. Ruby check if a class exist only when it's required, if, for example, when you run one of both initialize. Before run initialize, ruby only check if there is no syntax error only

Is it something that should be avoided?

No IMHO.

2
  • Maybe you're talking about circular dependances in compiled languages (a class requires another class to be compiled first, which in turn requires the first class to be compiled first). Of course that's not the case because Ruby is not a compiled language. However is this still a case of circular reference?
    – Redoman
    Nov 27, 2016 at 7:00
  • I think you are talking about Circular reasoning and not Circular Reference
    – Andrés
    Nov 27, 2016 at 10:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.