Sunday, February 10, 2013

MVC in Matlab

Some time ago I started to make use of Matlab's object oriented capabilities.  (In true Matlab style, inheritance is notated with a 'less than' sign:  dog < animal)  The application I refactored has a GUIDE front end.  I had used GUIDE to make user interfaces before; and forged ahead using what I had learned from the user's guide.  While I have been really pleased with the benefits of OO, I was struggling to figure out how to apply patterns to my program, specifically MVC.  Well, last weekend I cracked that nut; and moreover, while watching the Grammys I made a little demo app to share.

Model View Controller (MVC) is a compound pattern whose goal is to separate responsibilities into modular pieces that can be interchanged relatively easily.  If you didn't need a user interface, all you'd have to worry about is the model.  Why should you have to burden the model with user interface code?  Obviously you shouldn't, thus the model view separation.  Introduction of a controller loosens the coupling between the model and the view and, if done well, allows the behavior of the system to be modified by replacing the controller with a different one.  After the jump, I'll show you how to apply the pattern to a traditional Matlab GUI.

Model View Controller