I've been considering the way to solve this problem for a while, and I'm currently stuck between two options I both feel are suboptimal. Here's an abstract example of what I'm dealing with:
I have a Project class that stores which files are part of the project, as well as dependency information:
class Project { Collection<File> projectFiles; Multimap<File, File> dependencies; } I also have an OpenFile class that represents a file open for editing:
class OpenFile { Project project; File file; StringBuilder contents; } What I want to do is serialize the state of a project, along with the currently opened files. This way, when the project is reopened, all open files are reopened in the same state they were in when closing. The problem is that I need OpenFile.file to always correspond to an entry in Project.projectFiles, so that modifying a file can update its dependencies correctly.
I thought about implementing a FileRef class which is an index into projectFiles:
class FileRef { Project project; int fileId; } Then Project could own the master list of files, and OpenFile could simply own a FileRef. I'm worried that breaks encapsulation, though, since FileRef is dependent on the state of Project to provide its own services - in effect separating data and code.
Is this an acceptable sacrifice, or is there a better way to implement this?
OpenFile.filedoes not correspond to an entry inProject.projectFiles. Why doesn't it? What kind of serialization are you doing which prevents this from being the case?OpenFile.fileto always correspond to an entry inProject.projectFiles" - theOpenFileclass you have already doesn't guarantee that. How areOpenFileinstances constructed? And which entity controls the list of currently open files (that belong to a project)?