I am only allowed to use private members in the programming course I'm taking, and I was wondering if something like this is ok.
public class View {
private Model object_;
public View(Model object) {
object_ = object;
//blah blah blah
}
//blah blah blah
}
public class Controller {
private Model object_;
public Controller(Model object) {
object_ = object;
//blah blah blah
}
//blah blah blah
}
public class MainClass {
public static void main(String [ ] args) {
Model m = new Model();
Controller c = new Controller(m);
View v = new View(m);
//blah blah blah
}
}
The View and Controller classes both hold the same instance of the Model as private fields. Is this acceptable? It seems like it would violate the concept of private fields. I tried asking my professor, and he said it was ok, but I'm not sure if he understood my question, or if I understood his answer :)
Is this acceptable?
Yes it is.
It seems like it would violate the concept of private fields
It doesn't. The controller cannot change the instance from the view, because it it private.
Consider the following line of code that attempt to change the model in the view:
public class Controller {
private Model object_;
public Controller(Model object) {
object_ = object;
this.object_.view.object_ = new Model(); // doesn't work.
// or view.object_ = ....
//blah blah blah
}
//blah blah blah
}
Well this won't work, 1st because, the model doesn't have a reference to the view, and 2nd, if it had it, the controller
can't change the model
in the view, because it is invisible to him.
Sharing the same object may not be desirable in some situations. For instance if you rely on the state of a given object and that state is change by other object, your code may fail. See Defensive Copying That's why it is recommended to use immutable objects and restrict the access to it.
But particularly in the MVC design pattern sharing an object that's exactly what you need, or at least sharing the state of that object. In MVC what you need is the View
and the Controller
to be aware of the Model
state. Seeing the same object doesn't make them less private ( in the sense that neither of each objects know they are seeing the same thing ) this allows Low Coupling
What would definitely ruin object privacy would have that attribute as non private as:
class View {
public Model m;
}
class Controller {
public Model m;
}
....
public static void main( String ... args ) {
Model m = ...
View v = new View();
Controller c = new Controller();
v.m = m;
c.m = m;
}
Because there won't be any access control that prevents from wild changes to occur.