A shiny silver gun is drawn and stuck in the back of the perpetrator. “I thought I told you to leave my property. What are you still doing here?” A brief pause and the criminal responds “Leave? I thought you meant implement some properties, so I implemented three of them… a name, an age, and a phone number where you can reach me.” Martyr2 becomes puzzled. To get a better look at the man he pulls down his hood and…. IT WAS VB.NET! “VB, what the heck are you talking about?” A smile came across his face and he responds “Put down the gun and I will show you, and the rest of your readers, all you need to know about properties here on the Programming Underground!”
VB.NET sat Martyr2 down and began to explain the idea of properties….
Object oriented programming languages try to mimic real life objects so that humans can better understand systems and mimic systems after what they see around them. At its fundamental level, an object has properties which describe the object’s appearance or attributes and methods which describe an object’s behaviors. Consider a person for a minute. A person is an object with attributes such as a name, a height, a weight, an eye color.
In OOP languages, these attributes are described through internal variables such as personsName, personsHeight, personsWeight, and eyecolor. These variables are not for others to change. They are encapsulated to that person and each person has their own values for these attributes. They define the person. But what if that person allowed other people to have some control over these features? Such as how much they were fed to define their weight, or allowed someone to alter their eye color by putting contact lenses in their eyes. These are where properties come in. Properties allow access to an object’s internal variables through a public interface… a public access function.
Why can’t the person just let others get direct access to these variables? Well does it make sense to have a person give direct access to your weight? No. Instead you establish ground rules of how your weight will be modified or how your eye color can be changed. Perhaps you don’t like green eyes. So you establish a rule that others can change your eye color, but not allow them to change them to green. No green contacts for you!
Programming books often use the words “public interface” when they talk about properties. They say interface because if one object wants to change another object’s data, they interface through its public properties to do so. A textbox has a “text” property so you can change the text. That textbox control probably has a variable under the hood that keeps the string used to give the textbox its text value. You edit it through the property and have to follow the rule that you can’t set the text value to an object of type “MyObject”. It only takes strings.
Lets show you an example of properties and their use in VB.NET. Below is an example of an object we created called “Contact”. A contact is a person which will have a name, age and a phone number on how to get a hold of them… just in case we go out for a wild night of coding, binge drinking, brief nudity and need a ride home. You could have these contacts in a contact manager. Think of it as a virtual Rolodex.
The contact will internalize the name, age, and phone number and provide a public interface to those variables through properties. Through the properties we can then establish rules on access to those variables so that no one can simply go in and change the contact’s age to -2.
Public Class Form1 Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load ' Now lets create our contact person... Me Dim Martyr2 As New Contact("Martyr2", "231", "1-800-DAMNDIC") ' Notice how we can access properties of our contact object just like you would ' access the "text" property of a button or edit box. MessageBox.Show("Hi, my name is " & Martyr2.Name) MessageBox.Show("I am " & Martyr2.Age & " years old.. yeah yeah I know I am old") MessageBox.Show("Give me a call at: " & Martyr2.Phone & " no n00bs plz!") ' Will work Martyr2.Age = 88 Try ' Will fail and cause the exception catching to fire Martyr2.Age = -1 Catch ex As Exception ' Will show our custom message MessageBox.Show(ex.Message) End Try ' Will fail because it is a Readonly property ' Martyr2.Name = "Martyr3" Try ' Will fail and cause the exception catching to fire because we are not ' specifying a value for Phone Martyr2.Phone = "" Catch ex As Exception ' Will show our custom message again about providing a phone number MessageBox.Show(ex.Message) End Try End Sub End Class ' Specify our class called "Contact" that will setup a contact person ' They will have a name, age and phone number. Public Class Contact Private pName As String Private pAge As Integer Private pPhone As String ' Here is our constructor. Now notice how it uses Me.Age and Me.Phone to access ' The class' properties. This is good practice because now we can validate in each ' property definition (like making sure they specify an age over 0) ' We could have done that in the constructor, but using a property gives us the ' check in two places, the constructor as well as the property itself for other classes ' to use. This is our "public interface" Public Sub New(ByVal Name As String, ByVal Age As Integer, ByVal Phone As String) pName = Name Me.Age = Age Me.Phone = Phone End Sub ' Notice this is read only. In this case we can't use contactObj.Name = "string" ' We can only use... string = contactObj.Name Public ReadOnly Property Name() As String Get Return pName End Get End Property ' Here is our property for age. Notice that upon setting, if the value is less than ' or equal to zero, we are going to throw an exception for our program to catch. Public Property Age() As Integer Get Return pAge End Get Set(ByVal value As Integer) If value > 0 Then pAge = value Else Throw New Exception("Sorry, need to specify an age greater than 0!") End If End Set End Property ' Here is the property for phone. Notice we check to see if the phone is not empty ' before we attempt to set it. This essentially requires that they provide something ' for phone. Public Property Phone() As String Get Return pPhone End Get Set(ByVal value As String) If Not String.IsNullOrEmpty(value) Then pPhone = value Else Throw New Exception("Sorry, you must specify a phone number!") End If End Set End Property End Class
The in code comments describe a lot of what is going on here. We have three properties, one for each of the internal variables. We have two which can be read from and written to. The name however can only be set at the time the contact object is created. It can’t be set at a later time. Two of the properties establish rules. The age establishes the rule that no value less than 0 can be put in for the contact’s age. If a programmer using this object attempts to do something like Martyr2.Age = -2 it will violate the rule and an exception will be thrown telling the programmer that they can’t specify an age less than zero. A similar rule is in place for the phone, making sure that they can’t pass in an empty or null value for the phone.
By establishing rules on our properties, and controlling access to the variables of our object, we can help keep the object in a particular state. We can prevent the variables from being corrupted with values that make no sense… like the age being -2.
Most new programmers can get the property concept pretty quickly, but miss one great advantage. They can be used in tandem with a constructor. Our contact object has a constructor which takes the name, age and phone as parameters when the object is first created. In the constructor we use our properties to make sure that no invalid values taint our age or phone values. This makes sure that our object is initialized [i]in a valid state[/i]. These properties are local to the object, so we can access them through the “Me” reference. “Me” representing the current version of the object. The same thing as you would see with the “this” keyword in C++.
We could have set these internal variables through the constructor directly, but by putting them through the properties like we have, we can enforce the rules we established in the properties instead of having to check and repeating validation in the constructor. This reduces code and also centralizes the validation to the properties so if we have to make a correction, we fix it in one place.
In the main form class of our example, through the form_load event, we create a simple driver test program which creates a contact, initializes it to Martyr2’s contact data and shows you how we can then get access to the values through the contact object’s properties. Just like we would do using the text property of the textbox or button control.
We also demonstrate what happens when we try to violate our rules and trigger the exceptions. We can catch these exceptions (in our try catch error handling) and print an appropriate error message.
Properties can be readonly or writeonly or more often than not are readable/writable. We can have properties call private functions, other properties and then often trigger custom events. They are one of the great building blocks of object oriented programming and are great places to provide documentation that can be generated from since they describe how to use the object.
Feel free to use the contact object as you see fit in your next blockbuster user manager program that will net you the millions of dollars you have been looking for. I will just consider it another contribution to the other 100+ million dollar projects I helped spark.
… Putting the gun down Martyr2 looks at VB.NET and says “Ok, I can see where we might have misunderstood one another. Now can you please put down the TV and simply walk off the premises?” Looking down at the TV in his arms and then back up he replies “Ummm… I guess I can do that.”. VB.NET sets the TV down and then quickly replies “Have you heard of my story on shared variables?” “VB, just leave!” Martyr2 said. “Ok Ok… geesh, don’t get your panties up in a bunch”. VB.NET Then walks away and disappears into the night which is the CLR. Gone, but not forgotten…. he will be back!
Thanks for reading.