I'm implementing an `equals` method for my JsonObj...
# getting-started
d
I'm implementing an
equals
method for my JsonObject library, and had thought: It's possible to have a cycle in the graph. When computing equality of two JsonObjects (or JsonArrays), should detecting a cycle: 1. Throw an exception 2. Return
false
for equals. 3. Keep comparing unless both sides have a cycle. 4. Consider them equal only if they have the same cycle.
s
My instinct would be to follow the behaviour you'd get from the actual JSON. If it'd error when you try to serialize it, make the equality check error too.
d
Yeah, it is an error in actual JSON, and the methods I have that deal with that (writing it out, and deep copy, for instance) do throw an exception. My question is more general though, does the
equals
contract mean it shouldn't ever throw an exception? I vaguely recall reading that once about Java.
I'm thinking of going with option 1, since it's really an invalid state in the first place.
s
A regular map or list will just overflow the stack if it contains cycles. Which isn't really an argument one way or the other, but maybe makes option 1 feel more palatable...
e
kotlinx.serialization.json makes it impossible to create a self-referential JSON object
d
Right, but I’m not using kx ser
e
you could consider designing your API to similarly prevent illegal constructions
d
My api is mutable, which excludes that ability.
e
it is possible even with a mutable API - forcing copies as ktx does, or including parent pointers and detaching on move as DOM does, or scanning to check invariants on mutation. whether it's worth it is a different question of course
d
Yeah, I think for this use-case it’s good enough to just fail when the cycle is directly encountered, rather than check on every mutation that could introduce a cycle.