I'm writing a class library with a class called Application
. The Application
class contains a collection of Document
objects. I want the Application
class to be solely responsible for "creating" (constructing) Document
objects when appropriate. I do not want myself or other our developers to be able to construct new Document
objects arbitrarily.
I've tried to come up with some robust way to enforce this, but I've only come up with a couple possibilities, and they both have drawbacks.
The first way would be to nest the Application
class within the Document
class, and make the Document
constructor private such that only the Application
class can access it. But this makes no sense structurally, and is in fact the opposite of the true relationship. Not to mention that public nested classes are generally discouraged.
The other way I tried was to make the Document
constructor private, but give it a public "factory method" that does some checking to try and make sure it really was called by the Application
. But this became very convoluted as I tried to implement it.
Am I over-complicating this? Surely it's a common thing for a codebase to be built such that developers could do something that they shouldn't? Should I just expect our developers (and myself) to use discretion and common-sense and not go around constructing new Document
objects, when they should be getting them from the Application
instead?
Or am I correct in trying to enforce this? Am I correct in my pursuit for classes to only be usable as intended? After all, this is what access levels are for in the first place -- to enforce usage of entities only in the correct context. If this is a reasonable pursuit, does anyone have any suggestions for how to do so in this circumstance?
Note: I found this similar thread: java - make class only instantiable from specific class. But the proposed solution was nested classes, which aren't a good option for the reasons I gave above.