Click to See Complete Forum and Search --> : About classes and their usage and feasibility
Dr_Michael
December 18th, 1999, 07:19 AM
I have 1 year experience with VB (not a lot) and till now, all the projects I have attend have not used any class.
1) Is there a real need of using a class?
2) When do we have to use classes?
3) Which is the feasibility and usage?
4) Where can I find documentation for beginners on classes? (not MSDN please!!!)
5) How can I modify an already existing project to support classes?
6) Which is the first step before creating a class? Maybe the use of an array, or collection, or user-defined type???
Thanx all in advance for your help!
Michael Vlastos
Automation Engineer
Company SouthGate Hellas SA
Development Department
Athens, Greece
Chris Eastwood
December 19th, 1999, 02:56 PM
Classes are the building blocks of OO programming - they are a great way of encapsulating functionality and bring it into use only when you need it.
Here's a quick summary to your questions :
1) Is there a real need of using a class?
Absolutely - a class can represent an 'entity' inside your program. Say for instance you need to deal with an 'employee' - that can be represented as an object. An object is simply and 'instance' of a class, so a simple employee object could be (employee.cls) :
option Explicit
'
private msName as string
private msJobTitle as string
'
public property get Name() as string
Name = msName
End property
'
public property let Name(byval sName as string)
msName = sName
End property
'
public property get JobTitle() as string
JobTitle = msJobTitle
End property
'
public property let JobTitle(byval sJobTitle as string)
msJobTitle = sJobTitle
End property
You then use your employee object in code, such as :
Dim oEmployee as cEmployee
set oEmployee = new cEmployee
oEmployee.Name = "Chris"
oEmployee.JobTitle = "Slacker"
- of course this is a simple example. In a full employee object you'd have methods to read/write the employee away to a data store (either to disk or a database).
2) When do we have to use classes?
- This again depends on how you do your analysis - I'd recommend going through your specifications first and identifying any thing that looks like an 'object' - if something in your spec 'is a....' then it's usually a good candidate for an object, likewise if anthing in your specification 'has a ....' then that usually incorporates another object or at least shows what the properties of it are.
3) Which is the feasibility and usage?
It's never a good idea to have too many objects floating around in memory as they can eat it up. One of the best practises is to only instantiate (ie. set xx = new blah) an object when you really need it.
4) Where can I find documentation for beginners on classes? (not MSDN please!!!)
err.... watch this space! It's something I've been meaning to create for the site for a long time (should get around to writing that book one day). There are plenty of good OO books out there on the market though.
5) How can I modify an already existing project to support classes?
Eeek ! this is usually a bad idea - if the system works at the moment, you don't really want to try and 'play' with objects until you fully understand the concepts behind the usage and design of an OO system. You can't simply drop in an object model into a system and expect to see the benefits. I'd recommend writing some simple programs to play around with the concepts so that you get a feel for their usage and then see how you can apply them to a program.
6) Which is the first step before creating a class? Maybe the use of an array, or collection, or user-defined type???
I suppose you can think of an object as a user-defined-type that supports procedures/functions. The best way is to sit down and look at your design and identify what are the objects and what properties they have - and then see what functions they are expected to 'show' to the rest of the system.
Hope that hasn't confused you too much - if you'd like to give some feedback on what to see in the object tutorial - feel free (I don't really want to do the 'animal' class thing)
Chris Eastwood
CodeGuru - the website for developers
http://codeguru.developer.com/vb
Dr_Michael
December 22nd, 1999, 01:50 AM
Ok, this helped me much but I have a lot of projects done in my 1 year experience with vb and never used classes. For example, I wanted to create a program for Stock Exchange and done it with ADO. Was any reason to do it with classes?
But now, I am enforced to do the same project again (as project for the uni) using only classes and not database! How can I achieve it? The specifications are the following:
"The program should cope with storing the changing values of at least 10 sets
of shares (e.g. Hallifax, BT, Gas etc.). The user would have to enter the new
values for each of the shares periodically and the program should be able to
determine whether the price is up or down compared to the last entry and
compared to the overall average price. The should be able to display or print
a report on each current price, along with an indication or "Up" ,
"Down" or "unchange" for each.
We must use at least three classes and collection(s) "
Thanx a million!
Michael Vlastos
Automation Engineer
Company SouthGate Hellas SA
Development Department
Athens, Greece
Chris Eastwood
December 22nd, 1999, 03:56 AM
>For example, I wanted to create a program for Stock Exchange and done it
>with ADO. Was any reason to do it with classes?
That depends on how you look at the program. There is no reason in the world to use classes - however, if you want to utilize the benefits of OO programming (code-reuse etc) then it makes a lot of sense.
>But now, I am enforced to do the same project again (as project for the
>uni) using only classes and not database! How can I achieve it? The
>specifications are the following:
I'm giving you an outline here (and mailing you the code that I've got) - you don't say how the data is stored, so I'll leave that up to you (in VB6 there's the property bag object that allows you to store / retrieve classes to disk)
The spec to me suggests having a couple of classes and collections, I'd recommend :
Share Price Class
- Price as double
- DateChanged as date
Share Class -
-ShareName as string
-SharePriceHistory as collection (of share price classes)
-ShareDirection as string (a property to say whether shares are up / down / unchanged)
Shares Collection
- private collection as collection
here's my code for the share price object :
option Explicit
'
' Share price object - only has two members
'
private mdblPrice as Double ' current price
private mdteDateChanged as date ' date of change
'
public property let DateChanged(byval dteChange as date)
'
' set date Changed
'
mdteDateChanged = dteChange
End property
'
public property get DateChanged() as date
'
' get date Changed
'
DateChanged = mdteDateChanged
End property
'
public property let Price(byval dblNewPrice as Double)
'
' set Price
'
mdblPrice = dblNewPrice
End property
'
public property get Price() as Double
'
' get Price
'
Price = mdblPrice
End property
It's quite straightforward as you can see. This object would be used to retrieve values / dates from the share object (which holds a collection of these)
The next object would be the share object as follows
option Explicit
'
private Const SHARESUNCHANGED as string = "Unchanged"
private Const SHARESUP as string = "Up"
private Const SHARESDOWN as string = "Down"
'
' private members
'
private mcolSharePriceHistory as Collection ' collection of previous prices
private msShareName as string
private msShareDirection as string
'
public property get ShareDirection() as string
'
' Read only - share direction property
'
ShareDirection = msShareDirection
End property
'
public property let ShareName(byval sName as string)
'
' set the sharename
'
msShareName = sName
End property
'
public property get ShareName() as string
'
' get the sharename
'
ShareName = msShareName
End property
'
public Sub UpdatePrice(byval dblPrice as Double, optional dteDateOfUpdate as date)
'
' Change the shareprice
'
Dim oSharePrice as SharePrice
Dim dblOldPrice as Double
'
' Create new Price Object
'
set oSharePrice = new SharePrice
'
' set Price property of new object
'
oSharePrice.Price = dblPrice
If dteDateOfUpdate = 0 then
dteDateOfUpdate = Now()
End If
'
' set date changed of new object
'
oSharePrice.DateChanged = dteDateOfUpdate
'
' Check direction of prices
'
If mcolSharePriceHistory.Count > 0 then
dblOldPrice = mcolSharePriceHistory(mcolSharePriceHistory.Count).Price
End If
mcolSharePriceHistory.Add oSharePrice, CStr("S" & mcolSharePriceHistory.Count + 1)
If mcolSharePriceHistory.Count > 1 then
'
' Calculate latest change in direction
'
If dblOldPrice > dblPrice then
msShareDirection = SHARESDOWN
ElseIf dblOldPrice = dblPrice then
msShareDirection = SHARESUNCHANGED
else
msShareDirection = SHARESUP
End If
End If
End Sub
'
public property get SharePrice(optional lIndex as Long) as SharePrice
'
' Return the current / specified shareprice object
'
If mcolSharePriceHistory.Count = 0 then
set SharePrice = nothing
else
If lIndex = 0 then lIndex = mcolSharePriceHistory.Count
set SharePrice = mcolSharePriceHistory(lIndex)
End If
End property
'
public property get PriceChangeCount() as Long
PriceChangeCount = mcolSharePriceHistory.Count
End property
'
public property get NewEnum() as IUnknown
'this property allows you to enumerate
'this collection with the for...Each syntax
' go to Tools->Procedure Attributes->Advanced and make sure
' that procedure id = -4
'
set NewEnum = mcolSharePriceHistory.[_NewEnum]
End property
private Sub Class_Initialize()
'
' Create the internal collection
'
set mcolSharePriceHistory = new Collection
'
' Initialise the sharedirection to 'unchanged'
'
msShareDirection = SHARESUNCHANGED
End Sub
private Sub Class_Terminate()
'
' Kill the collection
'
set mcolSharePriceHistory = nothing
End Sub
Again it's quite straight forward. The next object would be the 'Shares' object which is basically a wrapper around a collection :
option Explicit
'
' Shares Collection
'
private mCol as Collection
'
public Function Add(byval sShareName as string) as Share
'
' Wrapper to 'Add' a share to our internal collection
'
Dim oShare as Share
set oShare = new Share
'
oShare.ShareName = sShareName
mCol.Add oShare, sShareName
'
set Add = oShare
set oShare = nothing
'
End Function
'
public property get Item(vntIndexKey as Variant) as Share
set Item = mCol(vntIndexKey)
End property
'
public property get Count() as Long
Count = mCol.Count
End property
'
public Sub Remove(vntIndexKey as Variant)
mCol.Remove vntIndexKey
End Sub
'
public property get NewEnum() as IUnknown
'this property allows you to enumerate
'this collection with the for...Each syntax
' the '-4' property also applies to this class
set NewEnum = mCol.[_NewEnum]
End property
'
private Sub Class_Initialize()
'
' Create our private collection
'
set mCol = new Collection
End Sub
'
private Sub Class_Terminate()
'
' Kill our private collection
'
set mCol = nothing
End Sub
Now that you have all three objects / classes, it's time to start playing with them :
Dim oShares as Shares ' our 'Shares' Collection Object
Dim oMicrosoftShare as Share ' A Share object
Dim oChrisShare as Share ' A Share Object
Dim lCount as Long
Dim oShare as Share ' Another Share Object
Dim oSharePrice as SharePrice ' A SharePrice Object
'
' Create our new collection of shares (Shares Object)
'
set oShares = new Shares ' new collection of shares
'
' add a couple of shares to the collection
'
oShares.Add "Microsoft"
oShares.Add "Chris"
'
' set pointers to those shares - this saves us having to reference them
' as oShares("Microsoft").whatever each time
'
set oMicrosoftShare = oShares("Microsoft")
set oChrisShare = oShares("Chris")
'
' Now do something with the shares
'
With oChrisShare
.ShareName = "Chris Ltd" ' set share price
.UpdatePrice 10.75 ' Update price
Debug.print .ShareName & " Shares Are " & .ShareDirection
.UpdatePrice 15 ' Update Price again
.UpdatePrice 25.99 ' and again
.UpdatePrice 35.55 ' and again !
Debug.print .ShareName & " Shares Are " & .ShareDirection
End With
'
' Now loop through each shareprice in the shares history and print it out
'
for Each oSharePrice In oChrisShare
Debug.print oSharePrice.DateChanged & " " & oSharePrice.Price
next
'
' let's use the M$ share
'
set oMicrosoftShare = oShares("Microsoft")
With oMicrosoftShare
.ShareName = "Micro$oft"
'
' Check if it has a current shareprice (returns an object of type shareprice or nothing)
'
If .SharePrice is nothing then
Debug.print "No Share Price yet"
End If
'
' Give it a new price and the date that it changed
'
.UpdatePrice 25#, #1/4/1999#
Debug.print .ShareName & " Shares Are " & .ShareDirection
.UpdatePrice 35.99, #1/5/1999# ' update it with new price / date
Debug.print .ShareName & " Shares Are " & .ShareDirection
.UpdatePrice 15.99, #1/6/1999# ' update it with new price / date
'
' Another way of looping through all prices in the M$ share
'
for lCount = 1 to .PriceChangeCount
Debug.print .SharePrice(lCount).DateChanged & " " & .SharePrice(lCount).Price
next
Debug.print .ShareName & " Shares Are " & .ShareDirection
End With
'
' Now loop through all shares in our collection
'
for Each oShare In oShares
Debug.print oShare.ShareName & " = " & _
oShare.SharePrice(oShare.PriceChangeCount).Price & " on " & _
oShare.SharePrice.DateChanged & _
" (" & oShare.ShareDirection & ")"
next
Hope this is enough to get you started, I've mailed the project code to your address as on the profile.
Chris Eastwood
CodeGuru - the website for developers
http://codeguru.developer.com/vb
codeguru.com
Copyright Internet.com Inc., All Rights Reserved.