Hi
In a new Java project I try to apply as much best practices as possible. The one I'm having problems with is immutability. Although I understood the concept and already built some immutable classes I now came to a class where I think it's more appropriate to do it as a mutable class.
The main problem is that I want to hide the mutable parts of the class in some cases so that in my case the view layer of MVC can't directly modify objects but has to go through its controller.
I thought of 2 ways to do it:
Create an interface "Thing" which has all immutable methods in it (read-only) and create an interface "MutableThing" which has the setters.
Put all methods in one interface and restrict access to mutating methods by wrapping the object like the Collections.unmodifiableList(obj) method so that exceptions are thrown when accessing mutating methods.
I would prefer the first one because I think it's cleaner and more well designed but I have one problem with that. I have addListener(l) and removeListener(l) in the "Thing" interface so the view layer can register itself as a listener to some model objects. But with these two methods in the "Thing" interface it just doesn't make sense on its own anymore. Why would an interface have the ability to register listeners which signal data changes if there is no method to actually change data? I could put these methods in the "MutableThing" interface but the view layer only has access to the "Thing" interface and couldn't register itself as listener.
The point why this isn't working is just because of the listeners, is the view layer actually responsible for registering itself as listener on the model? If the controller could do it somehow (which has access to the "MutableThing") then there wouldn't be a problem but I wouldn't know how to realize it.
What would you suggest?
Thanks!