Glorp Wisdom (pt. 312): Don’t reuse objects in exclusive relationships!

There are days when you hunt for a bug and almost are close to giving up. On some of these, it’s best to go home, play with your kids or watch a good movie and start again the next day.

On some, however, you finally find out teh whole problem was just a case of programmer’s stupidity at work.

I won’t tell you what kind of day today is for me, but I’ll share some words of wisdom with you:

Don’t use objects in an exclusive OneToManyRelationship and move them into another collection. You won’t like the results.

Want more details? Okay, my friend, let’s sit down and I’ll tell you all about it.

In Glorp, you can define a 1:m relationship to #beExclusive. This makes a lot of sense (that’s why many other ORM Frameworks have the same ability, maybe named a bit differently). What it means is that if an object that holds on to an exclusive relationship (or better: a collection of related objects) and gets deleted, all these objects will be deleted as well. Exclusive in that context means: the objects in this collection cannot exist withou the objext that holds them.

There is, however another way to look at it: it also means that if the programmer removes an object from this collection, it is not going to exist on its own any more. At least not after a commitTransaction.

So far, all of this makes sense.

Enter Joachim (you may guess right now which kind of day I had today).

Because all of this also means that there is aboslutely no sense in moving this object into another exclusive collection. Because you said it’s doomed. It’s gonna be doomed, no matter what. The object may be reachable from other collections or stuff, but an exclusive collection says: if you leave me, you die. It really is that simple. Glorp is gonna delete it, and never going to update it to reflect its membership of another collection. That would make sense if the object wasn’t coming from an exclusive collection, but, hey, it does!

So if you use exclusive collections (and I do because it makes sense in my business case), always take care what you do with your business objects. Moving it to another object’s collections won’t be reflected by updating it’s foreign keys, even if you do all backpointering and stuff correctly. Glorp’s answer will ALWAYS be a DELETE statement.

So moving an object from one exclusive collection to another always has to be done by removing the original object from the first collection and creating a new one for the other. You may copy references and attributes, even non-exclusive OneToMany collections to this new instance, but the object itself has to be a new one.


One thought on “Glorp Wisdom (pt. 312): Don’t reuse objects in exclusive relationships!

Comments are closed.