Since I’m working on a rather small project, I decided to implement a simple version of the Model-View-Controller pattern. Here’s the basic idea:
: |_ app.py
: |_ data.py
: |_ res
: |_ view.py
In the package
model there are two modules:
data, which knows relevant data (e.g. letter codes), and
app, which contains logic. The class
app.App should be used for requests from other modules.
Code related to the look of individual views can be found in
view.view. Image resources are saved in the subfolder
The program is started by executing
main.py, which contains the
Controller. It loads
view, instantiates classes and connects Observers with Observables.
The Observer Pattern
In general, this architecture is much more efficient when combined with the Observer Pattern. I’m so glad I learnt that one!
For example, statistics need to be displayed correctly at all times. Normally, I would try to pass data to the view object whenever it should be displayed. This works, but it is very hard to read. Also, a lot of extra code is needed.
Instead, the view should observe the statistics object. Whenever data is updated, the view is notified automatically. That’s it! No additional code is required.
But how does the statistics object get new data? You might have guessed it: It observes quiz terminations. Those need to be observed by result views anyway, so there’s no need to rewrite anything at all.
As a side note, python supports passing methods around. There’s no need for an Observer class; Observables simply call stored callback functions instead. In my opinion, this might be the most pythonic solution.