Are you injecting the same MutableObject instance every time? I'd inject a new instance every time and forgo the unnecessary extra copy. Or you could add a copy() method to ImmutableObject itself (or override clone to make a deep copy, return ImmutableObject and not throw an exception).
On Jan 31, 2009 12:27 PM, "Matt G" <[email protected]> wrote: Hi, Pre dependency injection, to ensure a class was immutable when it takes a mutable object into its constructor, you would create a new version of the object before assigning it internally, something like... class ImmutableObject { private final MutableObject mutObj; ImmutableObject(MutableObject mutObj) { this.mutObj = new MutableObj(mutObj); } ... } How would this translate to the world of dependency injection? Viewing the above class in terms of dependencies; there is clearly a dependency on the MutableObject itself, and also a dependency on an object that can create a new MutableObject. Assuming we have some sort of MutableObjectFactory class, we would write the class as follows: class ImmutableObject { private final MutableObject mutObj; private final MutableObjectFactory mutObjFac; @inject ImmutableObject(MutableObject mutObj, MutableObjectFactory mutObjFac) { this.mutObj = mutObjFac.create(mutObj); } } Would this be the recomended way of acheiving Immutablility with dependency injection? The problem is particularly apparent when injecting collections of objects. As whenever you do this you must always copy the contents of the collection to a new collection to ensure immutability. Thanks, Matt. --~--~---------~--~----~------------~-------~--~----~ You received this message because you are subscribed to the Google Groups "google-guice" group. To post to this group, send email to [email protected] To unsubscribe from this group, send email to [email protected] For more options, visit this group at http://groups.google.com/group/google-guice?hl=en -~----------~----~----~----~------~----~------~--~---
