views:

70

answers:

3

Having the Observer pattern, we all know that based on its class diagram, the SUBJECT uses a reference to the OBSERVER. Meanwhile, the OBSERVER has a reference to SUBJECT in order to register or remove itself.

Is this a "Circular Reference"?

+1  A: 

Sure, it's a circular reference. It's a cycle in the graph of references.

Using the term "circular references" sometimes occurs when talking about more harmful things though, particularly when you have circular dependencies (e.g. A needs B to compile, but B needs A to compile).

A circular reference in itself isn't harmful (e.g.: a circular linked list).

Mark Peters
A: 

No, this is not a circular reference.

A circular reference occurs when you separate portions of code rely on each other to complete their own task. Since neither piece can execute before the other finishes, the code becomes invalid and useless. Here is a verbal example from Wikipedia :

Function A will show the time the sun last set based on the current date. Function B will calculate the date based on the number of times the moon has orbited the earth since the last time Function B was called. So, Function B asks Function C just how many times that is. Function C doesn't know, but can figure it out by calling Function A to get the time the sun last set.

DJ Quimby
That is a circular dependency, not a circular reference.
Svante
Or indirect recursion in fact.
Péter Török
+1  A: 

As you describe it, it is a case of circular reference. However, note that in the full pattern, Observer is an abstract class / interface, which has one or more concrete implementations. Observer in some variations knows nothing about Subject (although its subclasses may refer to it), in other variations it may depend on an Observable interface or directly on Subject. However, Subject knows only about Observer, not its concrete subclasses.

So the reference is not (necessarily) circular.

Péter Török
"Reference" is way too overloaded a term. Even in the pure form of the pattern, a cycle in the object references typically exists (unless the observer tosses the reference to the subject, which usually doesn't happen in practice).
Mark Peters
@Mark, the term is indeed overloaded. IMO here we are talking about dependencies between interfaces/classes. In this context I maintain that there is no circularity in Observer per se.
Péter Török