Search code examples
c#.netundocommand-pattern

Command pattern and complex operations in C#


I am writing a program in C# that needs to support undo/redo. For this purpose, I settled on the Command pattern; tldr, every operation that manipulates the document state must be performed by a Command object that knows about the previous state of the document as well as the changes that need to be made, and is capable of doing/undoing itself.

It works fine for simple operations, but I now have an operation that affects several parts of the document at once. Likewise, the Command object must be smart enough to know all the old state it needs to preserve in case it needs to be undone.

The problem is exposing all that state using public interfaces has the potential for misuse if someone attempts to call the interface directly, which can lead to state corruption. My insticts tell me the most OO way of doing this is to expose specialized Command classes -- rather than allowing you to directly manipulate the state of the document, all you can do is ask the document to create a Command object which has access to its internal state and is guaranteed to know enough to properly support undo/redo.

Unfortunately, C# doesn't support the concept of friends, so I can't create a Command class that has access to document internals. Is there a way to expose the private members of the document class to another class, or is there some other way to do what I need without having to expose a lot of document internals?


Solution

  • It depends, if you are deploying a library your Document could declare 'internal' methods to interact with it's internal state, these methods would be used by you Command class, internal methods are limited to the assembly they are compiled.

    Or you could nest a private class to your Document, that way allowing it to access Document's internal state and expose a public interface to it, your Document would then create a command class hidden by that interface.