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

Top Mobile Game Discounts
Every day, we pick out a curated list of the best mobile discounts on the App Store and post them here. This list won't be comprehensive, but it every game on it is recommended. Feel free to check out the coverage we did on them in the links... | Read more »
Price of Glory unleashes its 1.4 Alpha u...
As much as we all probably dislike Maths as a subject, we do have to hand it to geometry for giving us the good old Hexgrid, home of some of the best strategy games. One such example, Price of Glory, has dropped its 1.4 Alpha update, stocked full... | Read more »
The SLC 2025 kicks off this month to cro...
Ever since the Solo Leveling: Arise Championship 2025 was announced, I have been looking forward to it. The promotional clip they released a month or two back showed crowds going absolutely nuts for the previous competitions, so imagine the... | Read more »
Dive into some early Magicpunk fun as Cr...
Excellent news for fans of steampunk and magic; the Precursor Test for Magicpunk MMORPG Crystal of Atlan opens today. This rather fancy way of saying beta test will remain open until March 5th and is available for PC - boo - and Android devices -... | Read more »
Prepare to get your mind melted as Evang...
If you are a fan of sci-fi shooters and incredibly weird, mind-bending anime series, then you are in for a treat, as Goddess of Victory: Nikke is gearing up for its second collaboration with Evangelion. We were also treated to an upcoming... | Read more »
Square Enix gives with one hand and slap...
We have something of a mixed bag coming over from Square Enix HQ today. Two of their mobile games are revelling in life with new events keeping them alive, whilst another has been thrown onto the ever-growing discard pile Square is building. I... | Read more »
Let the world burn as you have some fest...
It is time to leave the world burning once again as you take a much-needed break from that whole “hero” lark and enjoy some celebrations in Genshin Impact. Version 5.4, Moonlight Amidst Dreams, will see you in Inazuma to attend the Mikawa Flower... | Read more »
Full Moon Over the Abyssal Sea lands on...
Aether Gazer has announced its latest major update, and it is one of the loveliest event names I have ever heard. Full Moon Over the Abyssal Sea is an amazing name, and it comes loaded with two side stories, a new S-grade Modifier, and some fancy... | Read more »
Open your own eatery for all the forest...
Very important question; when you read the title Zoo Restaurant, do you also immediately think of running a restaurant in which you cook Zoo animals as the course? I will just assume yes. Anyway, come June 23rd we will all be able to start up our... | Read more »
Crystal of Atlan opens registration for...
Nuverse was prominently featured in the last month for all the wrong reasons with the USA TikTok debacle, but now it is putting all that behind it and preparing for the Crystal of Atlan beta test. Taking place between February 18th and March 5th,... | Read more »

Price Scanner via MacPrices.net

AT&T is offering a 65% discount on the ne...
AT&T is offering the new iPhone 16e for up to 65% off their monthly finance fee with 36-months of service. No trade-in is required. Discount is applied via monthly bill credits over the 36 month... Read more
Use this code to get a free iPhone 13 at Visi...
For a limited time, use code SWEETDEAL to get a free 128GB iPhone 13 Visible, Verizon’s low-cost wireless cell service, Visible. Deal is valid when you purchase the Visible+ annual plan. Free... Read more
M4 Mac minis on sale for $50-$80 off MSRP at...
B&H Photo has M4 Mac minis in stock and on sale right now for $50 to $80 off Apple’s MSRP, each including free 1-2 day shipping to most US addresses: – M4 Mac mini (16GB/256GB): $549, $50 off... Read more
Buy an iPhone 16 at Boost Mobile and get one...
Boost Mobile, an MVNO using AT&T and T-Mobile’s networks, is offering one year of free Unlimited service with the purchase of any iPhone 16. Purchase the iPhone at standard MSRP, and then choose... Read more
Get an iPhone 15 for only $299 at Boost Mobil...
Boost Mobile, an MVNO using AT&T and T-Mobile’s networks, is offering the 128GB iPhone 15 for $299.99 including service with their Unlimited Premium plan (50GB of premium data, $60/month), or $20... Read more
Unreal Mobile is offering $100 off any new iP...
Unreal Mobile, an MVNO using AT&T and T-Mobile’s networks, is offering a $100 discount on any new iPhone with service. This includes new iPhone 16 models as well as iPhone 15, 14, 13, and SE... Read more
Apple drops prices on clearance iPhone 14 mod...
With today’s introduction of the new iPhone 16e, Apple has discontinued the iPhone 14, 14 Pro, and SE. In response, Apple has dropped prices on unlocked, Certified Refurbished, iPhone 14 models to a... Read more
B&H has 16-inch M4 Max MacBook Pros on sa...
B&H Photo is offering a $360-$410 discount on new 16-inch MacBook Pros with M4 Max CPUs right now. B&H offers free 1-2 day shipping to most US addresses: – 16″ M4 Max MacBook Pro (36GB/1TB/... Read more
Amazon is offering a $100 discount on the M4...
Amazon has the M4 Pro Mac mini discounted $100 off MSRP right now. Shipping is free. Their price is the lowest currently available for this popular mini: – Mac mini M4 Pro (24GB/512GB): $1299, $100... Read more
B&H continues to offer $150-$220 discount...
B&H Photo has 14-inch M4 MacBook Pros on sale for $150-$220 off MSRP. B&H offers free 1-2 day shipping to most US addresses: – 14″ M4 MacBook Pro (16GB/512GB): $1449, $150 off MSRP – 14″ M4... Read more

Jobs Board

All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.