Peter Jonas
Peter Jonas

Reputation: 21

Very simple MVC question

I have a very simple question for MVC cause it is the first time i use it in my code. I have 3 classes, the model, the view and the controller.

The question is :

Should I instantiate the classes separately and use them that way in my application or I can create a class that inherits this 3 classes and instantiate that class instead ?

Most importantly I don't want to violate the main MVC pattern.

Upvotes: 1

Views: 139

Answers (3)

Alexander
Alexander

Reputation: 387

In the more abstract way, inheritance should not be overused. With inheritance, you couple things together and make it harder to maintain. It contradicts with single resnponsibility principle (SRP) as well: "a class should have only one job".

Also, as any pattern, inheritance had better be only used it is neccessary and fits into the architecture correctly, for example: when there is a class Vehicle, classes Car, Bus and Truck should inherit Car: it is their nature.

So, in this current example, the answer is: It is correct to use model, controller and view classes separately, expecially when MVC pattern itself describes separating of these three parts :)

Upvotes: 0

dafmetal
dafmetal

Reputation: 785

You should instantiate the classes separately.

Moreover, it can pay to separate those classes into interfaces and implementation classes for later extensibility. For instance, if your model now reads date from file and later you need to be able to read the same kind of data from a database, you can then make a second implementation of your model class that implements the model interface. your controller that interacts with the model would then only need a change in how it instantiates its model. The rest of the controller implementation can remain the same (as it is has been written against the model interface).

Upvotes: 1

Edoardo Pirovano
Edoardo Pirovano

Reputation: 8334

Definitely three separate classes. The whole point of MVC is to have three classes that communicate (through the controller, which handles all the logic of the application). Creating a class that has all three in it would defeat the purpose of MVC.

Upvotes: 0

Related Questions