School Assignment? Project Due Tomorrow? Chat LIVE With A Programming Expert!

Welcome to Dream.In.Code
Become an Expert!

Join 300,461 Programmers for FREE! Get instant access to thousands of experts, tutorials, code snippets, and more! There are 1,668 people online right now. Registration is fast and FREE... Join Now!




Understanding object handling for beginners

 
Reply to this topicStart new topic

> Understanding object handling for beginners, Some object oddities explained for beginners.

Rating  5
jens
Group Icon



post 12 Dec, 2008 - 01:18 PM
Post #1


A small tutorial for the beginner on how to handle objects.

So, you're working in VB2005 or VB2008 (or any object oriented language) and would like to know a little more about why you sometimes get strange results...

What I mean by strange results? Well look at this code and run it:

CODE

Option Strict On
Option Explicit On

Public Class Form1

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim theFirstObject As New aSmallClass
        Dim theSecondObject As New aSmallClass

        theFirstObject.name = "Jens"
        theSecondObject.name = "Jenny"
        theSecondObject = theFirstObject
        theFirstObject.name = "John"
        MsgBox(theFirstObject.name)
        MsgBox(theSecondObject.name)
        Me.Close()
    End Sub

End Class

Public Class aSmallClass
    Public name As String
End Class


If you find the result obvious then this tutorial is not for you.

Still reading? Ok, what's happening here?

We declare two object variables and assign two separate objects to them. We do theSecondObject = theFirstObject, thinking that we will make a copy of the first object and its data. Then we change what's inside theFirstObject and after that we show what's inside both objects. I was very confused by the result; both objects contain the string "John".

The reason for this confusion is that there is a misconception regarding what is happening above. To explain this I'll be a little lengthy but bear with me...

Suppose you have two signs, shaped like arrows and containing text, furthermore you have two houses. In the first house there's a guy named Jens living and in the second house there's a gal named Jenny living. The first sign points at Jens' house, the second at Jennys house. Suppose that you turn the second sign so it points at Jens' house and then Jens moves out and John moves in.

Now, ask yourself: If I look at the firs sign; whose house does this point at? Then ask yourself: If I look at the second sign; whose house does this point at? The result is - of course - both signs point at Johns house.

Here comes a leap of the mind!

Look at the code above while thinking of theFirstObject and theSecondObject as signs specialized in pointing at houses of the aSmallClass type! Can you see what's happening? We create two signs and two houses in the Dim-statements, then Jens moves in to the first house theFirstObject.name = "Jens" and Jenny moves in to the second house theSecondObject.name = "Jenny", after this we turn Jennys sign so it points at Jens house theSecondObject = theFirstObject and by now Jens moves out and John moves in theFirstObject.name = "John". After all this pointing, turning and moving we print out who lives in the house pointed out by the first and second sign respectively.

What have we learned?

The objects them self are containers for data (as a matter of speech at least) and the variables we associate with the objects are in fact pointers (signs) that only point out objects. This means that when we think we are working with objects we are in fact often working with pointers. This sometimes leads to confusion.

By now I hope that you will be less confused and have enough knowledge about objects and their associated variables to have an idea about what's wrong when you get weird results.

Ok?!! Do I have to care, besides this obscure example, what does it matter?

Suppose you have an object and you want to copy it together with all its content and associate it with a variable. Maybe because you want to update an object with new info and compare the original to what is stored in a database before updating the database. This to make sure that no one has updated the database from somewhere else while your user is updating her object. In this case you could make a copy of the original object and let the user update the copy. Before updating the database you compare the database with the original object and if they are the same it's ok to update, otherwise you'll have to inform your user that a change has occurred while she was working and inhibit the update, showing the user the new info.

So, there is a reason to copy an object with all it's content. How do we do this? Actually there are several methods and some mumbo jumbo talk pertaining to this but I'll use the above code - slightly modified - for a simple example of an unsofisticated method.

CODE

Option Strict On
Option Explicit On

Public Class Form1

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim theFirstObject As New aSmallClass
        Dim theSecondObject As New aSmallClass

        theFirstObject.name = "Jens"
        theSecondObject.name = "Jenny"
        theSecondObject = theFirstObject.CopyMe    'Changed here
        theFirstObject.name = "John"
        MsgBox(theFirstObject.name)
        MsgBox(theSecondObject.name)
        Me.Close()
    End Sub

End Class

Public Class aSmallClass
    Public name As String

    Public Function CopyMe() As aSmallClass    'Added
        Dim aNewSmallClass As New aSmallClass    
                        
        aNewSmallClass.name = Me.name        
        Return aNewSmallClass            
                        
    End Function                

End Class


Notice how I create a new object of the aSmallClass type in the CopyMe function, then I copy the original objects data field (name) to the new object. Now I'm done creating an object and copying the original data to the new object so I return a variable of type aSmallClass to the outside world: The variable named theSecondObject is hereby "turned" and pointed to the new object that was returned by the CopyMe function.

After all this we have theFirstObject pointing at an object containing "Jens" and theSecondObject pointing at (hear hear!!) a completely different object - but - this second object is also populated by "Jens". On the next row we let John move in to the first object while Jens still lives in the second.

Since this pretty much concludes this tutorial I hope you now understand why the result is two message boxes, the first one displaying "John" and the second displaying "Jens".

A final word:
When talking to hard core programmers you might come across the expressions "deep copy" and "shallow copy", a slight knowledge of the difference may come in handy.
* A deep copy completely copies one object to another. See below; both the "identity" and the "innerClass" will be completely copied, change anything in the copy and the original will be unaffected.
* A shallow copy copies only data that are not objects (strings are, or may be, an exception), i.e. all variables. Stuff like integers are copied and variables associated to objects are copied but inner objects are not copied. See below: A shallow copy of an object of type aSmallClass will have its own identity, change it in the copy and the original is unaffected. However, both the original and the copy will have their innerClass variable pointing at the same object. Change something in the copys inner object and it will show in the original too.

CODE

Public Class aSmallClass
    Public identity As Integer
    Public innerClass as anotherSmallClass    'Variable for other class
End Class


Thanks for today class, ave a nice afternoon! smile.gif

...but hey?!!! Wait! What happened to the first object that was pointed out by the theSecondObject variable, the one containing "Jenny"?

When we re-associate the variable theSecondObject from Jennys object to a copy of Jens' object there is no sign pointing out Jennys object any more. With no variable pointing to it we can not find it again. It is lost for ever in the voids of cyberspace smile.gif

This leads on to the subject of memory management in VB. There is a thing called "garbage collector" (GC) that runs in the background whenever VB is executing a program. The GC roams the memory of the computer looking for abandoned objects. When it finds an object that has no associated variables (no signs pointing at it) it grimly kills the object and lets the previously occupied memory free for other use.

This really concludes my little tutorial. I hope I've helped at least one person to understand more than before. Thank you for reading. smile.gif

Regards
/Jens
Go to the top of the page
+Quote Post


Register to Make This Ad Go Away!

jens
Group Icon



post 16 Dec, 2008 - 12:21 PM
Post #2
I'd really appreciate some feedback on the tutorial. I'm thinking about one more but I'm unsure if my style is acceptable. Critisism is also appreciated since I'll learn. Thanks. /Jens

This post has been edited by jens: 19 Dec, 2008 - 05:17 AM
Go to the top of the page
+Quote Post

n0c0d3
*



post 21 Dec, 2008 - 07:24 AM
Post #3
Jens, I'm new to VB, but you made it well clear to me.
I like your style, it's nice and loose.
Keep it up and coming as far as I'm concerned.

n0c0d3
Go to the top of the page
+Quote Post

mineeric123
*



post 25 Dec, 2008 - 11:55 PM
Post #4
Jens,

Great tutorial. I would like to see more.

Eric
Go to the top of the page
+Quote Post

Kiljoy
*



post 5 Jan, 2009 - 11:07 PM
Post #5
icon_up.gif 10 out of 10 for style and presentation smile.gif

thank you for the help please please please keep up the Awesome work smile.gif

Regards
Super VB NOOB
Reuben
Go to the top of the page
+Quote Post

sam.adams61
**



post 29 Jan, 2009 - 03:54 PM
Post #6
Of all the books...all the tutorials...all the thinking and the pondering, and WHAM! You, Jens, present to wee me an explanation that a 10year old could grasp! Excellent...fantastic...super...bravo, keep em coming wink.gif ...I'll be watching and waiting.
Go to the top of the page
+Quote Post

wtfnix
*



post 8 Apr, 2009 - 01:45 PM
Post #7
Heck keep them coming Jens, you write very well, and I have to concur with sam.adams61 above:

QUOTE
that a 10year old could grasp


So if you can keep them coming, and I'll keep learning! As for me, you have taught me so much in the begging world of .NET smile.gif
Go to the top of the page
+Quote Post


Fast ReplyReply to this topicStart new topic
1 User(s) are reading this topic (1 Guests and 0 Anonymous Users)
0 Members:

 


Lo-Fi Version Time is now: 11/8/09 02:19AM

Live Help!

Be Social

Dream.In.Code RSS Feed Dream.In.Code LinkedIn Group Follow Us On Twitter Fan Us On Facebook

Tutorials

Programming

Web Development

Reference Sheets

Code Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month