Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The State Pattern seems to use a circular reference. Why is that okay?

I'm still trying to understand the dangers of circular references. I often read that they should only be used in rare cases. But, in the canonical State Pattern, the "state" objects need to reference the "context" object in order to cause a transition and the "context" object needs to reference the "state" objects in order to trigger their behaviors.

Isn't this a circular reference? If not, how does it relate to circular references? If so, why is this acceptable?

http://en.wikipedia.org/wiki/State_pattern

http://sourcemaking.com/design_patterns/state

like image 449
Pup Avatar asked Jul 22 '12 05:07

Pup


People also ask

Is it okay to have circular dependency?

and, yes, cyclic dependencies are bad: They cause programs to include unnecessary functionality because things are dragged in which aren't needed. They make it a lot harder to test software. They make it a lot harder to reason about software.

What is wrong with circular references?

The circular reference error message "There are one or more circular references where a formula refers to its own cell either directly or indirectly. This might cause them to calculate incorrectly. Try removing or changing these references, or moving the formulas to different cells."

What is circular reference explain with example?

A circular reference is a type of pop-up or warning displayed by Excel that we are using a circular reference in our formula and the calculation might be incorrect. For example, in cell A1, if we write a formula =A1*2, this is a circular reference as inside the cell A1 we used the cell reference to A1 itself.

Are all circular dependencies bad?

Cyclic dependencies between components inhibit understanding, testing, and reuse (you need to understand both components to use either). This makes the system less maintainable because understanding the code is harder. Lack of understanding makes changes harder and more error-prone.


1 Answers

Two objects can operate on each other without necessarily referring to each other. In general a circular reference is a case where Class A and B both have a member variable that refers to the other. As implemented in the Wikipedia article there is no circular reference because while the Context stores a reference to the State, the Context is passed into the State as a parameter to a method, and it falls out of scope when the method finishes executing without the State having stored a reference to it.

like image 50
cmsjr Avatar answered Sep 18 '22 20:09

cmsjr