TweetFollow Us on Twitter

The Road to Code: Patterns in the Sky

Volume Number: 24 (2008)
Issue Number: 08
Column Tag: The Road to Code

The Road to Code: Patterns in the Sky

The Model-View-Controller Design Pattern

by Dave Dribin

Welcome Back

We've come a long way since the first Road to Code. We've covered Foundation and AppKit, the basic frameworks of Mac OS X, and we can write GUI applications. While we've covered the Objective-C language and classes that make up an application, we've glossed over a bit of history. How did Mac OS X applications evolve the way they have? Why did Apple's (and NeXT's) engineers create classes like NSApplication, NSView, and NSControl? The search for these answers takes us down a path the computing history.

Design Patterns

Ever since the dawn of computing, programmers have been trying to make their lives easier and more productive. Today we take high-level languages like Objective-C, C++, Java, Ruby, and Python for granted. Back in the day, programmers had to code in assembly language directly. Grace Hopper wrote the very first compiler in the 1950s to alleviate the pain of writing assembly language. In the 1970s, when the Unix operating system was originally being developed, the designers created their own language, called C, to help make Unix easier to port to new computer systems. C was one of the first and, in retrospect, is arguably the most successful high-level language. The benefit of C over assembly language was two-fold. First, the programmer could write code once that would run on multiple computer systems. All she had to do was recompile the C code for the target system and it would, if written properly, run without modifications. The other benefit of C code is that it was a lot more readable and understandable to the programmer. Both of these benefits greatly simplified the programmer's job.

C is still in active use today, either directly or in one of its derivatives forms, such as C++ and Objective-C. C also brought with it the ability to put commonly used code into libraries. Code - such as displaying text to the user and receiving input to the user and manipulating strings - can be re-used by many programmers and applications. The benefit is that each developer can spend their time writing their own application instead of having to re-invent the wheel, so to speak. Reusing code through libraries is also a big boon for the programmer.

But as good as reusing code through libraries is, it does have limitations. Sometimes, different applications perform many common tasks that may not be codified into libraries. Or sometimes these common tasks transcend the particular language you are using and apply to, say, any object-oriented programming languages. These higher-level reusable tasks are called design patterns. Design patterns are not unique to software development. The term "pattern" as a reusable idea originated from an architect named Christopher Alexander.

Software design has some similarities to traditional architecture and engineering, and design patterns are one of these similarities. The term design pattern in the software industry was popularized by the seminal book Design Patterns: Elements of Reusable Object-Oriented Software. The book was written in 1995 by four authors: Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides - now infamously known as the "Gang of Four". The Gang of Four (GoF) patterns book cataloged and described many design patterns that the authors used, or had observed in object-oriented applications. While the examples are in C++, the patterns themselves are still relevant to this day. In fact, there are now many books covering design patterns in specific languages, but the concepts are generally the same.

Aside from providing solutions to common software design problems, the benefit of using patterns is to create a common language and vocabulary that all programmers can use to help describe these problems. By providing a common vocabulary, anyone familiar with it will understand when someone says, for example, "this object implements the Adapter pattern to interface with the legacy database" or "you should use the Factory pattern to ensure future flexibility." The GoF book describes the Adapter pattern and Factory pattern in detail.

Obviously design patterns are a large topic and not something that I could do justice to in a single magazine article. I highly recommend you pickup (or borrow) a copy of the GoF book and read it. Even though it may be a little dated and does not apply directly to Objective-C, it will provide you with knowledge that will benefit you for years to come.

The Model-View-Controller Design Pattern

One common design pattern for developing GUI applications called the model-view-controller pattern or MVC pattern for short. The MVC pattern, while not described directly in the GoF book, is an old pattern with roots in Smalltalk from the early 1980s. It has proven such a successful pattern that it is prominent not only in modern Mac OS X applications in Cocoa, but also in Ruby on Rails web applications, and now in native iPhone applications, as just a few examples.

The MVC pattern breaks objects in an application into three roles: model objects, view objects, and controller objects. Objects in each role serve a particular function, and a single object should not perform multiple roles. The idea is to reduce dependencies, or coupling, between the components of an application. This loose coupling promotes reusability of each of the individual components.

Apple chose the MVC pattern as the basis for all Cocoa applications based on the success of the MVC pattern in Smalltalk and lessons learned in classic Mac OS. Apple used this experience to make programming for Mac OS X as easy as possible. They created the classes in AppKit and Foundation based on this collective experience, and these classes are now available for your use.

The Model

Model classes and objects are the core of your application. Think of them as your application, without a user interface. If, for example, you were developing an address book application, you would probably have objects to represent each contact, as well as objects to represent groups of contacts. Often, model objects are saved to disk and loaded in future invocations. Again, for an address book application, you would want to store all the contacts and groups on disk somewhere, so they could be loaded when your application next runs.

Ideally, model classes are completely independent of the user interface. This allows these classes to be reused in other applications and with other user interfaces. For example, you could use the same classes in a GUI, command line, and iPhone application. Or, you may be writing automated unit tests to ensure that the model objects work as desired. The reason these objects can be used in so many different situations is because they have no ties to the user interface. In technical terms, the model objects are not coupled to the user interface.

In our previous applications, the Rectangle class would be considered a model object. In fact, we have already reused this class in multiple applications. We started out using it in a command line application, and then used the exact same class when we started writing GUI applications.

The View

View objects and classes are at the other end of the spectrum. They represent the user interface and display information to the user. However, they are not responsible for storing the data they display. For GUI applications, we've already seen a number of view classes. For example, NSButton, NSTextField, and NSWindow are view classes. The NSApplication class is also considered part of the view as it represents the hub of a GUI application. Again, the main purpose of making generic view classes is to make them reusable in many applications. You could say that much of the AppKit framework is comprised of view classes, and the fact that AppKit provides so many pre-made view classes is one reason why it is easy to develop GUI applications for Mac OS X.

By designing AppKit using the MVC pattern, Mac OS X applications get to stand on the shoulders of giants. As programmers, we get to build on Apple's wealth of experience creating and designing GUI applications.

The Controller

Controller objects sit between the model and view classes and shuffles data back and forth. The GoF book describes a Mediator pattern where an object works like a real-world mediator communicating between two separate parties. The controller objects often follow this Mediator pattern.

One of the controller's responsibilities is to keep the model and view in sync. Figure 1 shows how the models, views, and controllers interact with each other. You can see the user interaction from the view goes through the controller. This user interaction is often in the form of targets and actions. For example, when a user clicks a button, the action method is on a controller class. The controller class is responsible for taking data out of the view and updating the model class. Conversely, if the model object changes without user interaction, it notifies the controller. It then updates the view accordingly. The controllers also generally act as the delegate and data source for views.


Figure 1: Model-View-Controller interaction

Hello World as MVC

Let's look at some of our programs through the MVC prism. The GUI from our original HelloWorld rectangle application is shown in Figure 2. The user interface is made up of standard Cocoa controls: a window, some text fields, and a button. These are all considered part of the view.


Figure 2: Rectangle application window

The rest of the application was implemented in two classes: HelloWorldController and Rectangle. As I mentioned above, the Rectangle class is considered a model class. The name I chose for HelloWorldController may not have made sense back then, as we didn't know about MVC, but it should be clear now. Since it performs the role of a controller class, I named it accordingly. Let's take a quick look at the interface for HelloWorldController in Listing 1.

Listing 1: HelloWorldController.h

#import <Cocoa/Cocoa.h>
@class Rectangle;
@interface HelloWorldController : NSObject
{
    IBOutlet NSTextField * _widthField;
    IBOutlet NSTextField * _heightField;
    IBOutlet NSTextField * _areaLabel;
    IBOutlet NSTextField * _perimiterLabel;
    
    Rectangle * _rectangle;
}
- (IBAction) calculate: (id) sender;
@end

This controller class has outlets to the text field, a calculate: action, and a _rectangle instance variable. Outlets and actions are generally how controllers and views are hooked up. Actions are used by views to notify the controller of a user's action. The controller uses outlets to get current values from the view and update the view to new vales of the model.

When the button is clicked and the action method is performed, the controller updates the _rectangle instance variable from the width and height text fields, and finally it updates the area and perimeter text fields:

- (void) updateAreaAndPerimeter
{
    [_areaLabel setFloatValue: _rectangle.area];
    [_perimiterLabel setFloatValue: _rectangle.perimeter];
}
- (IBAction) calculate: (id) sender
{
    _rectangle.width = [_widthField floatValue];
    _rectangle.height = [_heightField floatValue];
    [self updateAreaAndPerimeter];
}

You can see even in this simple example how the model view controller works. Data flows from the view to the model and vice versa through the controller. The controller receives a user action and updates both the model and the view to keep them in sync.

Model-View-Controller in Cocoa

You are highly encouraged to follow the MVC design pattern when writing your own applications. If you do, you will find that the Cocoa environment will help you get your job done faster. Apart from providing a rich set of view classes, there are some other benefits to following MVC. Some of the more advanced Cocoa technologies rely on MVC:

Document Architecture - Document-based applications follow the MVC pattern with your NSDocument subclass playing a controller role. When we changed our single window application to a document-based application that could save and open rectangle documents, we modified the Rectangle to implement the NSCoding protocol. By giving the Rectangle class the ability to convert itself to and from a sequence of bytes, it stays consistent with the role of a model class. However, it was the controller class that interacted with the view to perform the actual saving and loading to and from a file.

Cocoa Bindings - Bindings is a technique that allows you to remove a lot of repetitive code from of your controller classes. This is an advanced technique that in turn relies on key value coding (KVC) and key value observing (KVO). We will cover these topics in due time.

Core Data - Core Data allows you to easily create complex model objects and save them to disk. This allows you to remove a lot of repetitive code from your model classes. Again, we will cover Core Data in a future article.

Conclusion

The Model-View-Controller design pattern was identified as a way to design GUI applications that promotes loose coupling and reusability of its components. Apple chose the MVC pattern as the foundation for AppKit based on its previous success in Smalltalk. Because of this, you should design your Mac OS X applications with the MVC pattern in mind. It ensures your code is as reusable as possible, which is always a good thing, as you never know when you may need to use your model classes in another application. You will be glad you followed the MVC pattern when you do. As we will see in upcoming articles, Cocoa also rewards those following the MVC pattern.

Bibliography

Gamma, Erich; Richard Helm, Ralph Johnson, and John Vlissides. Design Patterns: Elements of Reusable Object-Oriented Software. 1995.


Dave Dribin has been writing professional software for over eleven years. After five years programming embedded C in the telecom industry and a brief stint riding the Internet bubble, he decided to venture out on his own. Since 2001, he has been providing independent consulting services, and in 2006, he founded Bit Maki, Inc. Find out more at http://www.bitmaki.com/ and http://www.dribin.org/dave".

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

Tokkun Studio unveils alpha trailer for...
We are back on the MMORPG news train, and this time it comes from the sort of international developers Tokkun Studio. They are based in France and Japan, so it counts. Anyway, semantics aside, they have released an alpha trailer for the upcoming... | Read more »
Win a host of exclusive in-game Honor of...
To celebrate its latest Jujutsu Kaisen crossover event, Honor of Kings is offering a bounty of login and achievement rewards kicking off the holiday season early. [Read more] | Read more »
Miraibo GO comes out swinging hard as it...
Having just launched what feels like yesterday, Dreamcube Studio is wasting no time adding events to their open-world survival Miraibo GO. Abyssal Souls arrives relatively in time for the spooky season and brings with it horrifying new partners to... | Read more »
Ditch the heavy binders and high price t...
As fun as the real-world equivalent and the very old Game Boy version are, the Pokemon Trading Card games have historically been received poorly on mobile. It is a very strange and confusing trend, but one that The Pokemon Company is determined to... | Read more »
Peace amongst mobile gamers is now shatt...
Some of the crazy folk tales from gaming have undoubtedly come from the EVE universe. Stories of spying, betrayal, and epic battles have entered history, and now the franchise expands as CCP Games launches EVE Galaxy Conquest, a free-to-play 4x... | Read more »
Lord of Nazarick, the turn-based RPG bas...
Crunchyroll and A PLUS JAPAN have just confirmed that Lord of Nazarick, their turn-based RPG based on the popular OVERLORD anime, is now available for iOS and Android. Starting today at 2PM CET, fans can download the game from Google Play and the... | Read more »
Digital Extremes' recent Devstream...
If you are anything like me you are impatiently waiting for Warframe: 1999 whilst simultaneously cursing the fact Excalibur Prime is permanently Vault locked. To keep us fed during our wait, Digital Extremes hosted a Double Devstream to dish out a... | Read more »
The Frozen Canvas adds a splash of colou...
It is time to grab your gloves and layer up, as Torchlight: Infinite is diving into the frozen tundra in its sixth season. The Frozen Canvas is a colourful new update that brings a stylish flair to the Netherrealm and puts creativity in the... | Read more »
Back When AOL WAS the Internet – The Tou...
In Episode 606 of The TouchArcade Show we kick things off talking about my plans for this weekend, which has resulted in this week’s show being a bit shorter than normal. We also go over some more updates on our Patreon situation, which has been... | Read more »
Creative Assembly's latest mobile p...
The Total War series has been slowly trickling onto mobile, which is a fantastic thing because most, if not all, of them are incredibly great fun. Creative Assembly's latest to get the Feral Interactive treatment into portable form is Total War:... | Read more »

Price Scanner via MacPrices.net

Early Black Friday Deal: Apple’s newly upgrad...
Amazon has Apple 13″ MacBook Airs with M2 CPUs and 16GB of RAM on early Black Friday sale for $200 off MSRP, only $799. Their prices are the lowest currently available for these newly upgraded 13″ M2... Read more
13-inch 8GB M2 MacBook Airs for $749, $250 of...
Best Buy has Apple 13″ MacBook Airs with M2 CPUs and 8GB of RAM in stock and on sale on their online store for $250 off MSRP. Prices start at $749. Their prices are the lowest currently available for... Read more
Amazon is offering an early Black Friday $100...
Amazon is offering early Black Friday discounts on Apple’s new 2024 WiFi iPad minis ranging up to $100 off MSRP, each with free shipping. These are the lowest prices available for new minis anywhere... Read more
Price Drop! Clearance 14-inch M3 MacBook Pros...
Best Buy is offering a $500 discount on clearance 14″ M3 MacBook Pros on their online store this week with prices available starting at only $1099. Prices valid for online orders only, in-store... Read more
Apple AirPods Pro with USB-C on early Black F...
A couple of Apple retailers are offering $70 (28%) discounts on Apple’s AirPods Pro with USB-C (and hearing aid capabilities) this weekend. These are early AirPods Black Friday discounts if you’re... Read more
Price drop! 13-inch M3 MacBook Airs now avail...
With yesterday’s across-the-board MacBook Air upgrade to 16GB of RAM standard, Apple has dropped prices on clearance 13″ 8GB M3 MacBook Airs, Certified Refurbished, to a new low starting at only $829... Read more
Price drop! Apple 15-inch M3 MacBook Airs now...
With yesterday’s release of 15-inch M3 MacBook Airs with 16GB of RAM standard, Apple has dropped prices on clearance Certified Refurbished 15″ 8GB M3 MacBook Airs to a new low starting at only $999.... Read more
Apple has clearance 15-inch M2 MacBook Airs a...
Apple has clearance, Certified Refurbished, 15″ M2 MacBook Airs now available starting at $929 and ranging up to $410 off original MSRP. These are the cheapest 15″ MacBook Airs for sale today at... Read more
Apple drops prices on 13-inch M2 MacBook Airs...
Apple has dropped prices on 13″ M2 MacBook Airs to a new low of only $749 in their Certified Refurbished store. These are the cheapest M2-powered MacBooks for sale at Apple. Apple’s one-year warranty... Read more
Clearance 13-inch M1 MacBook Airs available a...
Apple has clearance 13″ M1 MacBook Airs, Certified Refurbished, now available for $679 for 8-Core CPU/7-Core GPU/256GB models. Apple’s one-year warranty is included, shipping is free, and each... Read more

Jobs Board

Seasonal Cashier - *Apple* Blossom Mall - J...
Seasonal Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Seasonal Fine Jewelry Commission Associate -...
…Fine Jewelry Commission Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) Read more
Seasonal Operations Associate - *Apple* Blo...
Seasonal Operations Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Read more
Hair Stylist - *Apple* Blossom Mall - JCPen...
Hair Stylist - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom Read more
Cashier - *Apple* Blossom Mall - JCPenney (...
Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom Mall Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.