4

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?

3 Answers 3

4

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.

1
  • @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. Jan 8, 2010 at 18:18
4

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.

3

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.

4
  • 1
    "better served by model to communication interaction" what does this mean? thanks...still new to this Jan 5, 2010 at 21:53
  • 1
    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
    Jan 5, 2010 at 21:56
  • @julson...so in my example of Authentication class talking to User class...doesn't really fit that philosophy? Jan 5, 2010 at 21:58
  • 1
    @jonnietheblack: It fits the philosophy as the Authentication class in that example will only work with the user class.
    – Aaron M
    Jan 5, 2010 at 22:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.