<p>I'm writing a structural modeling tool for a civil enginering application. I have one huge model class representing the entire building, which include collections of nodes, line elements, loads, etc. which are also custom classes. </p>

<p>I have already coded an undo engine which saves a deep-copy after each modification to the model. Now I started thinking if I could have coded differently. Instead of saving the deep-copies, I could perhaps save a list of each modifier action with a corresponding reverse modifier. So that I could apply the reverse modifiers to the current model to undo, or the modifiers to redo. </p>

<p>I can imagine how you would carry out simple commands that change object properties, etc. But how about complex commands? Like inserting new node objects to the model and adding some line objects which keep references to the new nodes.</p>

<p>How would one go about implementing that?</p>

[{'answer_id': 49758, 'author': 'Mendelt', 'author_id': 3320, 'author_profile': 'https://Stackoverflow.com/users/3320', 'pm_score': 8, 'selected': True, 'text': '<p>Most examples I\'ve seen use a variant of the <a href="http://en.wikipedia.org/wiki/Command_pattern" rel="noreferrer">Command-Pattern</a> for this. Every user-action that\'s undoable gets its own command instance with all the information to execute the action and roll it back. You can then maintain a list of all the commands that have been executed and you can roll them back one by one.</p>\n'}, {'answer_id': 49761, 'author': 'Dave Arkell', 'author_id': 4002, 'author_profile': 'https://Stackoverflow.com/users/4002', 'pm_score': 3, 'selected': False, 'text': '<p>Just been reading about the command pattern in my agile development book - maybe that\'s got potential?</p>\n\n<p>You can have every command implement the command interface (which has an Execute() method).  If you want undo, you can add an Undo method.</p>\n\n<p>more info <a href="http://en.wikipedia.org/wiki/Command_pattern" rel="nofollow noreferrer">here</a></p>\n'}, {'answer_id': 49764, 'author': 'Adam Davis', 'author_id': 2915, 'author_profile': 'https://Stackoverflow.com/users/2915', 'pm_score': 3, 'selected': False, 'text': '<p>You might want to refer to the <a href="http://www.getpaint.net/download.html" rel="nofollow noreferrer">Paint.NET code</a> for their undo - they\'ve got a really nice undo system.  It\'s probably a bit simpler than what you\'ll need, but it might give you some ideas and guidelines.</p>\n\n<p>-Adam</p>\n'}, {'answer_id': 49775, 'author': 'Eric Z Beard', 'author_id': 1219, 'author_profile': 'https://Stackoverflow.com/users/1219', 'pm_score': 3, 'selected': False, 'text': '<p>This might be a case where <a href="http://www.lhotka.net/" rel="nofollow noreferrer">CSLA</a> is applicable.  It was designed to provide complex undo support to objects in Windows Forms applications.</p>\n'}, {'answer_id': 49781, 'author': 'Bill the Lizard', 'author_id': 1288, 'author_profile': 'https://Stackoverflow.com/users/1288', 'pm_score': 2, 'selected': False, 'text': '<p>I had to do this when writing a solver for a peg-jump puzzle game.  I made each move a Command object that held enough information that it could be either done or undone.  In my case this was as simple as storing the starting position and the direction of each move.  I then stored all these objects in a stack so the program could easily undo as many moves as it needed while backtracking.</p>\n'}, {'answer_id': 49877, 'author': 'Andy Whitfield', 'author_id': 4805, 'author_profile': 'https://Stackoverflow.com/users/4805', 'pm_score': 4, 'selected': False, 'text': '<p>If you\'re talking GoF, the <a href="http://en.wikipedia.org/wiki/Memento_pattern" rel="noreferrer">Memento</a> pattern specifically addresses undo.</p>\n'}, {'answer_id': 49918, 'author': 'Agnel Kurian', 'author_id': 45603, 'author_profile': 'https://Stackoverflow.com/users/45603', 'pm_score': 0, 'selected': False, 'text': "<p>I once worked on an application in which all changes made by a command to the application's model (i.e. CDocument... we were using MFC) were persisted at the end of the command by updating fields in an internal database maintained within the model. So we did not have to write separate undo/redo code for each action. The undo stack simply remembered the primary keys, field names and old values every time a record was changed (at the end of each command).</p>\n"}, {'answer_id': 50009, 'author': 'Omer van Kloeten', 'author_id': 4979, 'author_profile': 'https://Stackoverflow.com/users/4979', 'pm_score': 2, 'selected': False, 'text': '<p>I\'m with <a href="https://stackoverflow.com/questions/49755/design-pattern-for-undo-engine#49758">Mendelt Siebenga</a> on the fact that you should use the Command Pattern. The pattern you used was the Memento Pattern, which can and will become very wasteful over time.</p>\n\n<p>Since you\'re working on a memory-intensive application, you should be able to specify either how much memory the undo engine is allowed to take up, how many levels of undo are saved or some storage to which they will be persisted. Should you not do this, you will soon face errors resulting from the machine being out of memory.</p>\n\n<p>I would advise you check whether there\'s a framework that already created a model for undos in the programming language / framework of your choice. It is nice to invent new stuff, but it\'s better to take something already written, debugged and tested in real scenarios. It would help if you added what you\'re writing this in, so people can recommend frameworks they know.</p>\n'}, {'answer_id': 50050, 'author': 'Patrik Svensson', 'author_id': 936, 'author_profile': 'https://Stackoverflow.com/users/936', 'pm_score': 2, 'selected': False, 'text': '<p>Most examples I\'ve read do it by using either the command or memento pattern. But you can do it without design patterns too with a simple <a href="http://en.wikipedia.org/wiki/Deque" rel="nofollow noreferrer">deque-structure</a>.</p>\n'}, {'answer_id': 50117, 'author': 'Aardvark', 'author_id': 3655, 'author_profile': 'https://Stackoverflow.com/users/3655', 'pm_score': 1, 'selected': False, 'text': '<p>We reused the file load and save serialization code for “objects” for a convenient form to save and restore the entire state of an object. We push those serialized objects on the undo stack – along with some information about what operation was performed and hints on undo-ing  that operation if there isn’t enough info gleaned from the serialized data. Undo and Redoing is often just replacing one object with another (in theory).</p>\n\n<p>There have been many MANY bugs due to pointers (C++) to objects that were never fixed-up as you perform some odd undo redo sequences (those places not updated to safer undo aware “identifiers”). Bugs in this area often ...ummm... interesting.</p>\n\n<p>Some operations can be special cases for speed/resource usage - like sizing things, moving things around.</p>\n\n<p>Multi-selection provides some interesting complications as well. Luckly we already had a grouping concept in the code. Kristopher Johnson comment about sub-items is pretty close to what we do.</p>\n'}, {'answer_id': 50160, 'author': 'Greg Whitfield', 'author_id': 2102, 'author_profile': 'https://Stackoverflow.com/users/2102', 'pm_score': 3, 'selected': False, 'text': "<p>I've implemented complex undo systems sucessfully using the Memento pattern - very easy, and has the benefit of naturally providing a Redo framework too. A more subtle benefit is that aggregate actions can be contained within a single Undo too.</p>\n\n<p>In a nutshell, you have two stacks of memento objects. One for Undo, the other for Redo. Every operation creates a new memento, which ideally will be some calls to change the state of your model, document (or whatever). This gets added to the undo stack. When you do an undo operation, in addition to executing the Undo action on the Memento object to change the model back again, you also pop the object off the Undo stack and push it right onto the Redo stack.</p>\n\n<p>How the method to change the state of your document is implemented depends completely on your implementation. If you can simply make an API call (e.g. ChangeColour(r,g,b)), then precede it with a query to get and save the corresponding state. But the pattern will also support making deep copies, memory snapshots, temp file creation etc - it's all up to you as it is is simply a virtual method implementation.</p>\n\n<p>To do aggregate actions (e.g. user Shift-Selects a load of objects to do an operation on, such as delete, rename, change attribute), your code creates a new Undo stack as a single memento, and passes that to the actual operation to add the individual operations to. So your action methods don't need to (a) have a global stack to worry about and (b) can be coded the same whether they are executed in isolation or as part of one aggregate operation. </p>\n\n<p>Many undo systems are in-memory only, but you could persist the undo stack out if you wish, I guess.</p>\n"}, {'answer_id': 50190, 'author': 'Torlack', 'author_id': 5243, 'author_profile': 'https://Stackoverflow.com/users/5243', 'pm_score': 4, 'selected': False, 'text': '<p>As others have stated, the command pattern is a very powerful method of implementing Undo/Redo.  But there is important advantage I would like to mention to the command pattern.</p>\n\n<p>When implementing undo/redo using the command pattern, you can avoid large amounts of duplicated code by abstracting (to a degree) the operations performed on the data and utilize those operations in the undo/redo system.  For example in a text editor cut and paste are complementary commands (aside from the management of the clipboard).  In other words, the undo operation for a cut is paste and the undo operation for a paste is cut.  This applies to much simpler operations as typing and deleting text.</p>\n\n<p>The key here is that you can use your undo/redo system as the primary command system for your editor.  Instead of writing the system such as "create undo object, modify the document" you can "create undo object, execute redo operation on undo object to modify the document".  </p>\n\n<p>Now, admittedly, many people are thinking to themselves "Well duh, isn\'t part of the point of the command pattern?"  Yes, but I\'ve seen too many command systems that have two sets of commands, one for immediate operations and another set for undo/redo.  I\'m not saying that there won\'t be commands that are specific to immediate operations and undo/redo, but reducing the duplication will make the code more maintainable.</p>\n'}, {'answer_id': 558641, 'author': 'Peter Turner', 'author_id': 1765, 'author_profile': 'https://Stackoverflow.com/users/1765', 'pm_score': 0, 'selected': False, 'text': '<p>The first section of Design Patterns (GoF, 1994) has a use case for implementing the undo/redo as a design pattern.</p>\n'}, {'answer_id': 558733, 'author': 'Jeff Kotula', 'author_id': 1382162, 'author_profile': 'https://Stackoverflow.com/users/1382162', 'pm_score': 5, 'selected': False, 'text': "<p>I think both memento and command are not practical when you are dealing with a model of the size and scope that the OP implies. They would work, but it would be a lot of work to maintain and extend.</p>\n\n<p>For this type of problem, I think you need to build in support to your data model to support differential checkpoints for <em>every object</em> involved in the model. I've done this once and it worked very slick. The biggest thing you have to do is avoid the direct use of pointers or references in the model.</p>\n\n<p>Every reference to another object uses some identifier (like an integer). Whenever the object is needed, you lookup the current definition of the object from a table. The table contains a linked list for each object that contains all the previous versions, along with information regarding which checkpoint they were active for.</p>\n\n<p>Implementing undo/redo is simple: Do your action and establish a new checkpoint; rollback all object versions to the previous checkpoint.</p>\n\n<p>It takes some discipline in the code, but has many advantages: you don't need deep copies since you are doing differential storage of the model state; you can scope the amount of memory you want to use (<em>very</em> important for things like CAD models) by either number of redos or memory used; very scalable and low-maintenance for the functions that operate on the model since they don't need to do anything to implement undo/redo.</p>\n"}, {'answer_id': 663524, 'author': 'Tomas Andrle', 'author_id': 35440, 'author_profile': 'https://Stackoverflow.com/users/35440', 'pm_score': 2, 'selected': False, 'text': '<p>For reference, here\'s a simple implementation of the Command pattern for Undo/Redo in C#: <a href="http://www.catnapgames.com/blog/2009/03/19/simple-undo-redo-system-for-csharp.html" rel="nofollow noreferrer">Simple undo/redo system for C#</a>.</p>\n'}, {'answer_id': 1061973, 'author': 'Kirill Osenkov', 'author_id': 37899, 'author_profile': 'https://Stackoverflow.com/users/37899', 'pm_score': 2, 'selected': False, 'text': '<p><a href="https://learn.microsoft.com/en-us/archive/blogs/kirillosenkov/new-codeplex-project-a-simple-undoredo-framework" rel="nofollow noreferrer">Codeplex project</a>:</p>\n<p>It\'s a simple framework to add Undo/Redo functionality to your applications, based on the classical Command design pattern. It supports merging actions, nested transactions, delayed execution (execution on top-level transaction commit) and possible non-linear undo history (where you can have a choice of multiple actions to redo).</p>\n'}, {'answer_id': 3814670, 'author': 'NativeBreed', 'author_id': 460810, 'author_profile': 'https://Stackoverflow.com/users/460810', 'pm_score': -1, 'selected': False, 'text': '<p>I don\'t know if this is going to be of any use to you, but when I had to do something similar on one of my projects, I ended up downloading UndoEngine from <a href="http://www.undomadeeasy.com" rel="nofollow">http://www.undomadeeasy.com</a> - a wonderful engine and I really didn\'t care too much about what was under the bonnet - it just worked. </p>\n'}, {'answer_id': 25685586, 'author': 'danza', 'author_id': 393758, 'author_profile': 'https://Stackoverflow.com/users/393758', 'pm_score': 2, 'selected': False, 'text': '<p>A clever way to handle undo, which would make your software also suitable for multi user collaboration, is implementing an <a href="http://en.wikipedia.org/wiki/Operational_transformation" rel="nofollow">operational transformation</a> of the data structure.</p>\n\n<p>This concept is not very popular but well defined and useful. If the definition looks too abstract to you, <a href="https://github.com/share/ShareJS" rel="nofollow">this project</a> is a successful example of how an operational transformation for JSON objects is defined and implemented in Javascript</p>\n'}, {'answer_id': 37024062, 'author': 'Antonín Procházka', 'author_id': 4100001, 'author_profile': 'https://Stackoverflow.com/users/4100001', 'pm_score': 1, 'selected': False, 'text': '<p>You can try ready-made implementation of Undo/Redo pattern in PostSharp. <a href="https://www.postsharp.net/model/undo-redo" rel="nofollow">https://www.postsharp.net/model/undo-redo</a></p>\n\n<p>It lets you add undo/redo functionality to your application without implementing the pattern yourself. It uses Recordable pattern to track the changes in your model and it works with INotifyPropertyChanged pattern which is also implemented in PostSharp.</p>\n\n<p>You are provided with UI controls and you can decide what the name and granularity of each operation will be.</p>\n'}, {'answer_id': 37073691, 'author': 'Parthasarathy SRINIVASAN', 'author_id': 5520060, 'author_profile': 'https://Stackoverflow.com/users/5520060', 'pm_score': -1, 'selected': False, 'text': '<p>In my opinion, the UNDO/REDO could be implemented in 2 ways broadly.\n1. Command Level (called command level Undo/Redo)\n2. Document level (called global Undo/Redo)</p>\n\n<p>Command level: As many answers point out, this is efficiently achieved using Memento pattern. If the command also supports journalizing the action, a redo is easily supported. </p>\n\n<p>Limitation: Once the scope of the command is out, the undo/redo is impossible, which leads to document level(global) undo/redo</p>\n\n<p>I guess your case would fit into the global undo/redo since it is suitable for a model which involves a lot of memory space. Also, this is suitable to selectively undo/redo also. There are two primitive types</p>\n\n<ol>\n<li>All memory undo/redo</li>\n<li>Object level Undo Redo</li>\n</ol>\n\n<p>In "All memory Undo/Redo", the entire memory is treated as a connected data (such as a tree, or a list or a graph) and the memory is managed by the application rather than the OS. So new and delete operators if in C++ are overloaded to contain more specific structures to effectively implement operations such as a. If any node is modified, b. holding and clearing data etc., \nThe way it functions is basically to copy the entire memory(assuming that memory allocation is already optimized and managed by the application using advanced algorithms) and store it in a stack. If the copy of the memory is requested, the tree structure is copied based on the need to have a shallow or deep copy. A deep copy is made only for that variable which is modified. Since every variable is allocated using custom allocation, the application has the final say when to delete it if need be. \nThings become very interesting if we have to partition the Undo/Redo when it so happens that we need to programatically-selectively Undo/Redo a set of operation. In this case, only those new variables, or deleted variables or modified variables are given a flag so that Undo/Redo only undoes/redoes those memory\nThings become even more interesting if we need to do a partial Undo/Redo inside an object. When such is the case, a newer idea of "Visitor pattern" is used. It is called "Object Level Undo/redo"</p>\n\n<ol start="2">\n<li>Object level Undo/Redo: When the notification to undo/redo is called, every object implements a streaming operation wherein, the streamer gets from the object the old data/new data which is programmed. The data which is not be disturbed is left undisturbed. Every object gets a streamer as argument and inside the UNDo/Redo call, it streams/unstreams the data of the object. </li>\n</ol>\n\n<p>Both 1 and 2 could have methods such as \n1. BeforeUndo()\n2. AfterUndo()\n3. BeforeRedo()\n4. AfterRedo(). These methods have to be published in the basic Undo/redo Command ( not the contextual command) so that all objects implement these methods too to get specific action.</p>\n\n<p>A good strategy is to create a hybrid of 1 and 2. The beauty is that these methods(1&amp;2) themselves use command patterns </p>\n'}, {'answer_id': 38582614, 'author': 'Matthias', 'author_id': 590534, 'author_profile': 'https://Stackoverflow.com/users/590534', 'pm_score': 0, 'selected': False, 'text': '<p>You can make your initial idea performant.</p>\n\n<p>Use <a href="https://en.wikipedia.org/wiki/Persistent_data_structure" rel="nofollow">persistent data structures</a>, and stick with keeping a <a href="http://bakins-bits.com/wordpress/?p=7" rel="nofollow">list of references to old state around</a>.  (But that only really works if operations all data in your state class are immutable, and all operations on it return a new version---but the new version doesn\'t need to be a deep copy, just replace the changed parts \'copy-on-write\'.)</p>\n'}, {'answer_id': 49245926, 'author': 'Thilo', 'author_id': 6554924, 'author_profile': 'https://Stackoverflow.com/users/6554924', 'pm_score': 0, 'selected': False, 'text': '<p>I\'ve found the Command pattern to be very useful here. Instead of implementing several reverse commands, I\'m using rollback with delayed execution on a second instance of my API. </p>\n\n<p>This approach seems reasonable if you want low implementation effort and easy maintainability (and can afford the extra memory for the 2nd instance).</p>\n\n<p>See here for an example:\n<a href="https://github.com/thilo20/Undo/" rel="nofollow noreferrer">https://github.com/thilo20/Undo/</a></p>\n'}]
['https://Stackoverflow.com/questions/49755', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/976/']