While the previous section on Controllers offered a nice example with
the Faren application, it does present some issues. First, the interface
could use some extra niceness (deleting text from the entry does
nothing!). Second, the controller has to invoke methods on its view's
instance variables (self.view.celsius.set_text()
for example),
which is a sign of high coupling. One good way to solve these issues is
to provide a subclass of GladeView that does some extra setup and
provides an API for the Controller (faren2.py):
This (much longer, sure, but with a nicer division) example shows us using a separate View class, which presents an API for manipulating the View interface widgets, consisting of the following methods:
get_temp()
: Gets the temperature from the GtkEntry in the
interface, and returns it. Returns None if the entry is empty.
update_temp()
: Updates the contents of the two labels that
represent the temperature (in farenheit and in celsius).
clear_temp()
: Clears the contents of the two labels that
represent the temperature.
The Controller also uses changed
instead of insert_text
,
so it supports both insertion and deletion. Note that, following the
suggestion in section 2.7, we don't use the parameters
sent to our handlers; the View's API methods are based on its widgets
attached as instance variables (this is why we use
self.temperature
, self.farenheit
and self.celsius
).
This is basically what you need to know about the controller. While it is useful in a number of applications, if your interface has a number of widgets and rich interaction, you will notice that your View API will start looking like a exact copy of the widget methods. This is highly undesirable (as are accessor functions, for the same reason): it means the Controller is tightly coupled to the View, which is not what we want. And herein lies the main problem with the View/Controller split: if your interface is simple (as it is in our example), it's a nice way to separate things; however, if your interface is complex and has lots of widgets (I'd say a good rule of thumb is over 5 interactive widgets) you will end up with a lot of low-level View/Controller message passing.
(Another potential problem with the split is that neither the Controller nor the View are very reusable, which defeats part of the goals of modularity). The next section describes UI Delegates, which are combinations of View and Controller that simplify things somewhat.