Model-View-Presenter
In MVP, the Presenter contains the UI business logic for the View. All invocations from the View delegate directly to the Presenter. The Presenter is also decoupled directly from the View and talks to it through an interface. This is to allow mocking of the View in a unit test. One common attribute of MVP is that there has to be a lot of two-way dispatching. For example, when someone clicks the "Save" button, the event handler delegates to the Presenter's "OnSave" method. Once the save is completed, the Presenter will then call back the View through its interface so that the View can display that the save has completed.
MVP tends to be a very natural pattern for achieving separated presentation in WebForms. The reason is that the View is always created first by the ASP.NET runtime. You can find out more about both variants.
Two primary variations
Passive View: The View is as dumb as possible and contains almost zero logic. A Presenter is a middle man that talks to the View and the Model. The View and Model are completely shielded from one another. The Model may raise events, but the Presenter subscribes to them for updating the View. In Passive View there is no direct data binding, instead, the View exposes setter properties that the Presenter uses to set the data. All state is managed in the Presenter and not the View.
- Pro: maximum testability surface; clean separation of the View and Model
- Con: more work (for example all the setter properties) as you are doing all the data binding yourself.
Supervising Controller: The Presenter handles user gestures. The View binds to the Model directly through data binding. In this case, it's the Presenter's job to pass off the Model to the View so that it can bind to it. The Presenter will also contain logic for gestures like pressing a button, navigation, etc.
- Pro: by leveraging data binding the amount of code is reduced.
- Con: there's a less testable surface (because of data binding), and there's less encapsulation in the View since it talks directly to the Model.
Model-View-Controller
In the MVC, the Controller is responsible for determining which View to display in response to any action including when the application loads. This differs from MVP where actions route through the View to the Presenter. In MVC, every action in the View correlates with a call to a Controller along with an action. In the web, each action involves a call to a URL on the other side of which there is a Controller who responds. Once that Controller has completed its processing, it will return the correct View. The sequence continues in that manner throughout the life of the application:
Action in the View
-> Call to Controller
-> Controller Logic
-> Controller returns the View.
One other big difference about MVC is that the View does not directly bind to the Model. The view simply renders and is completely stateless. In implementations of MVC, the View usually will not have any logic in the code behind. This is contrary to MVP where it is absolutely necessary because, if the View does not delegate to the Presenter, it will never get called.
Presentation Model
One other pattern to look at is the Presentation Model pattern. In this pattern, there is no Presenter. Instead, the View binds directly to a Presentation Model. The Presentation Model is a Model crafted specifically for the View. This means this Model can expose properties that one would never put on a domain model as it would be a violation of separation-of-concerns. In this case, the Presentation Model binds to the domain model and may subscribe to events coming from that Model. The View then subscribes to events coming from the Presentation Model and updates itself accordingly. The Presentation Model can expose commands which the view uses for invoking actions. The advantage of this approach is that you can essentially remove the code-behind altogether as the PM completely encapsulates all of the behavior for the view. This pattern is a very strong candidate for use in WPF applications and is also called Model-View-ViewModel.
There is a MSDN article about the Presentation Model and a section in the Composite Application Guidance for WPF (former Prism) about Separated Presentation Patterns
Maybe a bit of example code will help: Notice the difference in the call signatures of foo
, class_foo
and static_foo
:
class A(object):
def foo(self, x):
print(f"executing foo({self}, {x})")
@classmethod
def class_foo(cls, x):
print(f"executing class_foo({cls}, {x})")
@staticmethod
def static_foo(x):
print(f"executing static_foo({x})")
a = A()
Below is the usual way an object instance calls a method. The object instance, a
, is implicitly passed as the first argument.
a.foo(1)
# executing foo(<__main__.A object at 0xb7dbef0c>, 1)
With classmethods, the class of the object instance is implicitly passed as the first argument instead of self
.
a.class_foo(1)
# executing class_foo(<class '__main__.A'>, 1)
You can also call class_foo
using the class. In fact, if you define something to be
a classmethod, it is probably because you intend to call it from the class rather than from a class instance. A.foo(1)
would have raised a TypeError, but A.class_foo(1)
works just fine:
A.class_foo(1)
# executing class_foo(<class '__main__.A'>, 1)
One use people have found for class methods is to create inheritable alternative constructors.
With staticmethods, neither self
(the object instance) nor cls
(the class) is implicitly passed as the first argument. They behave like plain functions except that you can call them from an instance or the class:
a.static_foo(1)
# executing static_foo(1)
A.static_foo('hi')
# executing static_foo(hi)
Staticmethods are used to group functions which have some logical connection with a class to the class.
foo
is just a function, but when you call a.foo
you don't just get the function,
you get a "partially applied" version of the function with the object instance a
bound as the first argument to the function. foo
expects 2 arguments, while a.foo
only expects 1 argument.
a
is bound to foo
. That is what is meant by the term "bound" below:
print(a.foo)
# <bound method A.foo of <__main__.A object at 0xb7d52f0c>>
With a.class_foo
, a
is not bound to class_foo
, rather the class A
is bound to class_foo
.
print(a.class_foo)
# <bound method type.class_foo of <class '__main__.A'>>
Here, with a staticmethod, even though it is a method, a.static_foo
just returns
a good 'ole function with no arguments bound. static_foo
expects 1 argument, and
a.static_foo
expects 1 argument too.
print(a.static_foo)
# <function static_foo at 0xb7d479cc>
And of course the same thing happens when you call static_foo
with the class A
instead.
print(A.static_foo)
# <function static_foo at 0xb7d479cc>
Best Answer
MVC is not a universal solution and most of the time it's done wrong and can't keep its promises: in practice modifying a model will require modifications in the controller as well, because it's done wrong. If you really want loose coupling between Model and Controller then - and people usually ignore that - you have to use a service pattern (open as image). Which almost nobody actually does.
Instead of blindly adhering to the MVC fuss/pseudo-pattern in the PHP world, Django takes a pragmatic approach. Because in the common reality of software development, the developer programs things for the user to see. Then the user (your boss, client, customers ...) will "see" your work, and eventually give his opinion about how he wants to "see" it in the end. By using Django, the developer can take a more "view oriented" development pattern and guess what: it makes deadlines easier to respect and users more satisfied. If you think about it, it has its "nosql-ish" idea that the view (general view, not django view) should be the boss of what's going on behind the scenes.
I'd like to thank Django for not doing MVC wrong, unlike 99% of the PHP MVC implementations out there.
On the other hand, Django is the only framework that allows proper isolation between applications. Each application can have:
So even if your models/views/templates will be tied, your project can be relevantly divided in small (also reads: easy to maintain) and loosely coupled applications. Only related models/views/templates/stuff are tied together. A big fat models script with a big fat views and urls script is not what you want in Django. For example, you don't want two model classes like
Article
andFootballMatch
to live together, you want to make an "articles"/"blog" app and a "sport" app which can live independently. Of course sometimes they must be tied, in that case it's doable at the project level in 90% of the cases (you'd make another app, "blog_sport" if you happened to need to tie in models or templatetags).For example, it's a super common practice to define a
get_absolute_url()
method in the Model class. Yes, your model class which in theory has to contain only business logic, is now tied with your urls definition. How bad is this in practice ?!! Well actually it's brilliant because it takes two seconds to add this method and you can then use it anywhere you use a model: be it in views or templates. Also, other applications (e.g.django.contrib.admin
) will use it.Another slightly more complicated example of Django brilliance is that queries are lazily evaluated. Which means, your view function/class will define a query like
blog_list = Blog.objects.all()
, but the query will actually be executed in the template if it calls like{% for blog in blog_list %}
. So business logic happens in the template in that case, and if something fails before the rendering of the template: you saved a query. But that's not all, if your template just displays a count{{ blog_list.count }}
, the select query will not be spawned at all and just a count query will be executed. The "general view" decides what business logic is needed. That's far from the promises of MVC but be honest: how practical is that ?My point is that you can apply theory the wrong way, do it right (which reduces your choice to like 5 web frameworks all languages included), or just get to the point in an elegant and pragmatic way to get your job done the Zen way in no time: that's Django's choice.