Separating view and model
Why the model knows nothing about the view, the model, view and controller roles in a graphical application, notification through an observer, and what it buys: tests without a window and several views of one model.
- 25 cards
- 5 topics
- Free
The outline, topic by topic
Each topic is weighted the way the exam weighs it.
- Concepts
- Questions
- Sort and link
- Scenarios
- Understand
A few cards from the deck
Model: what is it?
Show the answer
The part of an application that holds the data and the business rules, knowing nothing of how they are displayed.
A cart total, a discount rule or a validation live here: they can be tested without opening a window.
What design flaw does this class have?
```java
public class Panier {
private final Label total = new Label();
private double montant;
public void ajouter(double prix) {
montant += prix;
total.setText(montant + " €");
}
}`- The model writes into the view itself: it depends on it and cannot be tested alone
totalisfinal: the label can never change its text- The
ajoutermethod changes a field instead of returning a value - The controller should call
setTextbefore the model calculates
Show the answer
The model writes into the view itself: it depends on it and cannot be tested alone
Labelis a graphical component: the model owns it and updates it. The fix is to notify observers at the end ofajouter; the view registers and writes into its own label.finalfreezes the reference to the label, not its text.In an MVC architecture, the … does not know the …: the view registers with the model to be notified.
Show the answer
In an MVC architecture, the model does not know the view: the view registers with the model to be notified.
The dependency goes one way, from the view to the model. If the model imported graphical classes, a window would be needed to test it.
View: what is it?
Show the answer
The part that shows the state of the data on screen and picks up the user's input, without deciding the business rule.
It reads the model's state to display it; writing into a label, choosing a colour or showing an error message are its business.
An application shows sales in a table and in a chart, two views of the same model. After a new sale, the table updates but the chart stays frozen. What is the most likely cause?
- The model forgot to recompute the sale after receiving it
- The table and the chart should share the same view instance
- The controller must call the chart in addition to the table view
- The chart is not registered as an observer of the model
Show the answer
The chart is not registered as an observer of the model
The table gets the state because it is registered; the chart, never notified, keeps the old display. The fix is to register the chart, not to wire the controller to every view.