r/visualbasic • VB Guru • Feb 14 '14

Tips & Tricks How Classes work. Part 1 - a beginner’s primer on using classes in your projects.

In an effort to bring content to the Visual Basic subredit I am going to start posting VB thoughts and learned tidbits from 20 plus years programming in VB. If you have a different opinion on something please let us know. Discussion is healthy and I want this to be fun for everybody.

Back in the day of VB4 (and earlier for that matter) we used to create a module file that maintained all functions that a program would use application wide. This became a nightmare to manage (let alone work out scope of variables) and you would start breaking them up into many modules trying to maintain some sort of organization. When trying to fix a bug 6 Months later you had to remember where a function was and spend a bunch of time tracing your code path with the F8 key (now F10 in VB.net) to remember what you were thinking in your last update the customer needed in 5 minutes.

We had classes in VB4 but they were a nightmare unto themselves and it wasn't until VB5 that they finally got to a point that I started using them regularly. Having said that they were not true OOP (Object Oriented Programming) Classes. It was not until .Net that we received true Classes.

I am going to show you a "file cabinet approach to code" using classes. In a later post I will explain Inheritance. I believe that showing people how classes help organize and manage code makes it easier to understand.

I like to think of classes as a place to store and organize code. In today’s world that is referred to as an Object. A chunk of code that has things and does stuff.

Here is an Example of an empty class

Public Class Car
	'Properties, Methods and Functions go here.
End Class

If you want to create an empty class in vb.net right click you project in the solution explorer and click on ADD > Class. Give it a name that represents what the class is going to be. and hit save. I am going to use "Car" as my example. Why? because I like cars...

NOTE: This a good time to talk about code organization. Create a folder called Classes and put all of your classes in it. Create subfolders if you have many classes, organize your folders by Intent. People bitch at my old school approach and say Namespaces are the way to organize code, but time and time again folder structures have helped me figure out some source control fubar or another. You do use source control don’t you?

Classically (no pun intended) a Class Object consists of Properties, Functions and Methods. It was explained to me using a car metaphor;

A car has options, it can have a colour, engine, and a stereo. These are the Cars Properties. They describe information about the car. Let’s take our code above and a new property called Colour;

Public Class Car

#Region "Properties"

	Private _Colour As String
	Public Property Colour() As String
		Get
			Return _Colour
		End Get
		Set(ByVal value As String)
			_Colour = value
		End Set
	End Property

#End Region

End Class

NOTE: #Region is your friend! use it to organize your code in your classes, I use "properties" and "methods" as my main two regions. You can also break up your code further, but a good rule of thumb is that if you have a class that has so many functions and properties that it is difficult to navigate you probably need another class.

Shortcut Alert: Adding properties in VB.Net is supper fast type "prop" and press the tab twice it will template in a property which you can edit by just clicking the coloured areas and it modifies the whole property to match.

Code Tip: I use _ to indicate a private variable some people use Upper and Lower case but I always found that it was hard to read. If it has an underscore in front of it, it's easier to see what is going on in your code base.

In the code above I have created a space that stores information about a Cars colour. I store it as a string, but you could set the type of the property to another class or object. You could put a control type into the property and pass a whole control into your class if you wish. We will get into that in another post I think.

A property consist of an internal private variable, a Get and A Set. to make a useable copy of this class (Instantiate the class) you need to create a variable for it and set the type to the class name.

Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load

    Dim myCar As New Car
    myCar.Colour = "Blue"

    Dim myCarColour As String = myCar.Colour
    Debug.Print(myCarColour)

End Sub

Now we have a car and that car is blue. The normal notation for this property is myCar.Colour. When you give the property a value you are using the SET portion of the property to assign the value to the internal private variable. When you retrieve the value of a property you are using the GET to retrieve the value from the private internal variable. if you run the program at this point you will get in the debug window

Now some people will tell you that all you need to do is create a public variable in your class and it will be exposed when you instantiate it. While this is true coming from an old timer don’t do this it will come back to haunt you later.

There are two reasons you should always use a get set;

1. You can remove either the get or the set to stop a programmer from either retrieving information about a variable or changing that variable.
2. you can modify the get or set to Validate, or modify the value passed in or out (Don’t do this, more further in)

Let’s look at these two things closer.

A property can be, Read/Write (Get and Set), Read (Get only), or Write (Set only). Most of the time you will want the programmer using your class to be able to do what they need with the property thus Read/Write. In certain cases you will only want them to retrieve the value. You do this with the ReadOnly parameter when creating your property.

Here is the code that we would add in our Properties region to add the property "Running"

Private _Running As Boolean
Public ReadOnly Property Running() As Boolean
    Get
        Return _Running
    End Get
End Property

The WriteOnly parameter does the opposite and only allows a programmer to assign a value to the property.

Private _RadioStation As Integer
Public WriteOnly Property RadioStation() As Integer
    Set(ByVal value As Integer)
        _RadioStation = value
    End Set
End Property

This leads me directly into the second reason you should always use a get/set in a class, the capacity to cause something to happen when a value is set.

Private _RadioStation As Integer
Public WriteOnly Property RadioStation() As Integer
    Set(ByVal value As Integer)
        _RadioStation = value
        ChangeRadioStation(_RadioStation)
    End Set
End Property

In the above code I am calling a function that would change the Radio Station of the car when the value for the property is changed. This is used most commonly used when you do not want to expose a methods process to a programmer.

So let me post the full class code so far.

Imports System.ComponentModel
Public Class Car

#Region "Properties"

	Private _Colour As String
	Public Property Colour() As String
		Get
			Return _Colour
		End Get
		Set(ByVal value As String)
			_Colour = value
		End Set
	End Property

	<DefaultValue(0)> _
	Private _Speed As Integer
	Public Property Speed() As Integer
		Get
			Return _Speed
		End Get
		Set(ByVal value As Integer)
			_Speed = value
		End Set
	End Property

	Private _Running As Boolean
	Public ReadOnly Property Running() As Boolean
		Get
			Return _Running
		End Get
	End Property

	Private _RadioStation As Integer
	Public WriteOnly Property RadioStation() As Integer
		Set(ByVal value As Integer)
			_RadioStation = value
			ChangeRadioStation(_RadioStation)
		End Set
	End Property

#End Region

#Region "Methods"

	Public Function ChangeSpeed(SpeedChange As Integer) As Integer
		_Speed = _Speed + SpeedChange
		Return _Speed
	End Function

	Public Sub TurnKey()
		_running = Not _running
		' this line does the work of this chunk of code.
                    'If _Running = False Then
		'	_Running = True
		'ElseIf _Running = True Then
		'	_Running = False
		'End If
	End Sub

	Private Sub ChangeRadioStation(stationID As Integer)
		' Set the value of the radio station by doing what needs to be done here.
		' Psedocode
		' if StationID is RadioStation then 
		'   TuneRadio(StationID)
		' else 
		'   raise error not radio station
		' endif
	End Sub
#End Region

End Class

NOTE: One thing of that I just noticed I did automatically was import the System.Componentmodel namespace. I did this so I could set a default value for the Speed property as 0. It has a lot more capacity than that but we will get into that another time.

I consider this Purely Functional programming, and is not meant to be a guide on class design. This is for programmers who want to code and not know the nitty-gritty behind the scenes. All of you CS majors out there that are rolling your eyeballs, get over it. I you want the university computer science explanation I recommend Introduction to Object Oriented Programming Concepts by Nirosh over on CodeProject.com

In the next post we will start talking about Inheritance, Encapsulation, and the dreaded Polymorphism.

9 Upvotes

4 comments sorted by

2

u/candyforlunch VB.Net Master Feb 14 '14

Pretty cool so far. There's a few minor things I would change

  • Auto Properties, solely because writing boilerplate code completely sucks, no matter if you're a beginner or advanced. That way the properties Speed (assuming for the time being there's no validation required) and Colour can become: Public Property Speed As Integer

    Public Property Colour As String

  • It's probably a bit early to introduce the System.Componentmodel, especially since A) it has all sorts of stuff that flies over the head of many, B) integers have a default value of 0 to begin with, and C) with auto-properties it's possible to include a default value - Public Property Colour As String = "Red", Public Property Speed As Integer = 5 etc

  • The TurnKey() method doesn't actually do anything! Probably should implement it like

    Public Sub TurnKey()

     ` _Running = Not _Running`
    
      `' Console.Writeline(If(Running, "You started the car", "You stopped the car"))`

    End Sub

Keep it up. I like seeing content like this in the sub, it should help the newbies a lot :)

1

u/Bonejob VB Guru Feb 14 '14

I agree with you on AutoProperties, I wanted to make sure that people understood how the operated before I short cirvuited the path for them. I was going to put it in my Next post at the top as "Now you know how it works, do it the easy way"...

I did the system.componentmodel without thinking about it. I agree its early and I should have waited.

The turnkey method has both ways of doing the code, I was weighing which version I wanted to use, and left both in by mistake I have commented out the extra code. Thanks for noticing :)

1

u/no1name Feb 15 '14

The problem now days with teaching properties is that that with the shortcut version you don't need your getters and setters. That means that new programmers don't get it drilled into their heads as much as those of us who had to write them out fully earlier.

As a result I always do it the long winded way first like here.

I recommend "The Object orientated thought process" as a great book for any language. http://www.amazon.com/The-Object-Oriented-Thought-Process-Edition/dp/0672330164

1

u/Vectronic Feb 25 '14

There's also a drawback (AFAIK) to auto-properties, you can't do:

Public X As Integer
Public Y As Single

Public WriteOnly Property Stuff() As Integer
    Set(value As Integer)
        X = value
        Y = value * 3.14
    End Set
End Property