Thursday, August 22, 2013

Programming 101: Model View Controller and Object Class

A few people have asked me to briefly explain to them what the MVC design pattern is and what classes are in object oriented programming so here is a very simple description for each one which hopefully will help you understand what they are and how they work

Model View Controller:

MVC is a design pattern which helps define the different aspects of an application by separating it into 3 parts.

  • View: This is the composite layer. It represents the user interface, what they see and what they are able to interact with. Here you have your labels, text-boxes, buttons, images and other elements.
  • Model: This is the observer layer. It represents the back end code which performs all the functionalities and calculations. Here you have all your classes, methods, data connections and object references.
  • Controller: This is the strategy layer. It represents the connection between the View and the Model. This is where you determine for example, which method should be called when a user selects a specific button on the UI. It is also in charged of updating the UI based on a response from the model layer. 
A class is a construct which we use to define objects in object oriented programming languages. A class (or object) is composed of two pieces:

  • Structure: This is what defines the attributes, fields or properties of a class. For example when you think of a contact on your phone some of the attributes it has are a picture, a name, a phone number, an email address. 
  • Behavior: This is what defines the different actions your object can do or that you can do with your object. These actions is what we call methods. Again following the example of a contact on your phone, some of these actions could be calling, sending an email, sharing contact information. 
Classes can be used in a hierarchical way which allows you to re-use certain attributes for different objects:

  • Superclass: This is also referred to as a parent or base class. Any attributes or methods defined in this class will carry over to all subclasses. 
  • Subclass: This is derived from a superclass and is often called a child class or sub class. It contains specific methods and attributes for it. 
Attributes and methods for any class can be further separated into 3 different types which define their accessibility:

  • Private: This means that the specific method or attribute is only accessible within the given class.
  • Protected: This means that the specific method or attribute is only access by the given class or any subclasses derived from it.
  • Public: This means that the specific method or attribute can be accessed by any other class within the application as long as the original class is being referenced.