tags:

views:

83

answers:

3

Simple question: in MVC, is it okay for one model to interact with another? For example, with an Auth model...can it interact with the User model - or is there a better way to go about it?

Should the middle man be the controller?

+2  A: 

Different Model classes interacting is just fine. Most complex objects aren't completely standalone. As with any good OO code, the classes should use public methods and not expose their implementation to each other, but beyond that, it's all good.

dj_segfault
what do you mean by "expose their implementation"? thanks!
johnnietheblack
@johnnietheblack: If ClassA calls ClassB, ClassA should know what ClassB is supposed to do, but not exactly how it does it. If, for instance, someone modifies an internal variable of ClassB from a Hashtable to a HashMap or TreeMap for some reason, ClassA shouldn't be affected at all. In practical terms, that means using public getters and setters to private attributes instead of accessing protected or public attributes directly. ClassB needs to have control of changes to its attributes.
dj_segfault
+2  A: 

It really depends on the specifics of what you are trying to accomplish. On the surface, one model can interact with another model if it needs to. Just make sure that the reason why the model has to interact with another model is well thought out, and that the model to model interaction would'nt be better served by model to communication interaction instead.

Aaron M
"better served by model to communication interaction" what does this mean? thanks...still new to this
johnnietheblack
He probably means that models that directly talk to one another should have a direct relationship with each other. Like one model being a component of another. Completely unrelated models are best served using a mediator such as a controller.
Julson Lim
@julson...so in my example of Authentication class talking to User class...doesn't really fit that philosophy?
johnnietheblack
@jonnietheblack: It fits the philosophy as the Authentication class in that example will only work with the user class.
Aaron M
sweett...thanks buds
johnnietheblack
+2  A: 

They can certainly know about each other, and utilize each other's functions. Often, best practices will keep this one-way, but not always. Like dj_segfault said, this interaction should be through public methods. Be sure to read up on Dependency injection; changing the internal workings of one class should not break the other, as long as all public methods still behave the same.

keithjgrant