Task: I get xml from external API. Demarchal it into a chain of inherited objects. I work with these objects. At a certain stage, I need to check in which objects the changes were made, and send back to api xml only from the modified objects.

What ideas came to mind: Working with hashcode - save object hashes at the time of their generation from xml. And before sending, again, take the hash of objects, and check if it has changed. But while I see the problem that if the hash of the child changes, then the parent hash also changes, and as a result I’ll throw back the entire tree of the inherited objects.

To do some sort of object marker. If in one of the object fields the new value is changed, then change the marker to true. In this case, is there a universal way or template for the implementation of this idea? Hardcoding it all in all setreters seems like a bad idea.

Question: What is the best way to track changes in objects? Can someone share their experience or link?

  • use AOP. suspend the aspect of the object-changing methods. When they are called, add an object to the collection of changed objects. There is an option to do the same but through the decorator pattern. - Artem Konovalov
  • As an option - to make objects immutable and, after modifications, sranivat them through == with the original. - etki

1 answer 1

On the pattern does not pull, of course, but the recipe is suitable:

In my case, there was a set of JSON / XML objects that were translated into Java beans that were displayed on the UI. When switching to the UI mode, a copy of the Java object fell out on the UI and after returning from editing I stupidly compared the copy after editing and before the edition if there was a difference, the isChanged() flag was isChanged() , then all the objects isChanged()==true were written to the database as XML / Json.

In my opinion, an attempt to implement this whole story by students is useful if there are few fields, and if the number of fields exceeds at least a dozen, then you are tormented by putting listeners on each field or writing a highly intelligent listener who tracks changes. In addition, even the presence of a listener will not save much, because the user can return back corrections - so in fact the output object will not differ from the original one.

The point is that changing objects is better to catch in Java bins, and not at the level of XML / JSON objects.

Something like this.