Android Programming The Big Nerd Ranch Guide by Bill Phillips, Chris Stewart, Kristin Marsicano (z-lib.org)

(gtxtreme123) #1

Chapter 2  Android and Model-View-Controller


Figure 2.5 shows the flow of control between objects in response to a user event, like a press of a
button. Notice that model and view objects do not talk to each other directly; controllers sit squarely in
the middle of everything, receiving messages from some objects and dispatching instructions to others.


Figure 2.5  MVC flow with user input


Benefits of MVC


An application can accumulate features until it is too complicated to understand. Separating code into
classes helps you design and understand the application as a whole; you can think in terms of classes
instead of individual variables and methods.


Similarly, separating classes into model, view, and controller layers helps you design and understand
an application; you can think in terms of layers instead of individual classes.


Although GeoQuiz is not a complicated app, you can still see the benefits of keeping layers separate. In
a moment, you are going to update GeoQuiz’s view layer to include a NEXT button. When you do that,
you will not need to remember a single thing about the Question class you just created.


MVC also makes classes easier to reuse. A class with restricted responsibilities is more reusable than
one with its fingers in every pie.


For instance, your model class, Question, knows nothing about the widgets used to display a true-false
question. This makes it easy to use Question throughout your app for different purposes. For example,
if you wanted to display a list of all the questions at once, you could use the same object that you use
here to display just one question at a time.

Free download pdf