Home > Archive > Visual Basic > May 2004 > Class fog in my brain
You are viewing an archived Text-only version of the thread.
To view this thread in it's original format and/or if you want to reply to
this thread please [click here]
| Author |
Class fog in my brain
|
|
| Tom_OM 2004-05-28, 6:30 am |
| I've read in MSDN and in VB books about the usefulness of using class
modules. However, I haven't really grapsed everything deep down.
Thus far the idea of classes seems esoteric and theoretical; I'm
having difficulty getting my brain to comprehend the nuts and bolts of
it. I've yet to have that little bell in my head go "ping" as I
realize how useful this VB feature is and how it will benefit me in
the programs I write, and which of my own oft-used code would be best
to convert to a classes. So far a simple module (*.BAS) has always
sufficed for subs that will be reused over and over.
I have no doubt that class modules are useful; I'm just not getting
them yet. Does anyone know of a good online article about classes,
preferably one that specifically shows some working structured code
and how it can be converted to class-module code? It would be really
helpful if the article pointed out how such an approach can improve my
efficiency. I'm just not fully grasping why classes are better in
some cases than simple BAS modules for reusing code.
| |
| Larry Serflaten 2004-05-28, 8:30 am |
|
"Tom_OM" <dontspamme@junkmailstinks.com> wrote
>
> I have no doubt that class modules are useful; I'm just not getting
> them yet.
It is quite simple, really. Beginning with the basics:
You have variables that hold your data, and modules that hold your code.
On the variable side, you can create variables of different types, you can
create arrays of those different types, or, you can create a User Defined
Type that is a mixture of different data types, and finally you can have
arrays of those UDTs.
On the modules side, you have a BAS module that contains variables
and code, and you have forms that contain variables and code. The
form is a special case in that it is bound to a visible representation of
different windows (form, controls, etc... are 'windows') and other
windowless controls (Line, Shape, Lable).
OK, you know about those.
Consider, then, what the button is. It is a control that has properties,
methods, and events. When you put one on the form, the designer
shows the visible representation of it, and the code module will show
its events. You can set its properties in the Property window, and can
respond to its events in the code module.
But, if you add a second button to the form, you get a completely new
button, that has its own properties, methods, and events. How is that done?
For a second example, suppose you have a UDT that has data pertaining
to an employee in your latest HR manager program. Now suppose the
UDT has an a array of StartTimes, and EndTimes to help calculate the
w ly pay of that employee. Also suppose that the company has workers
that work in shifts, such that they can run 24/7 using 3 teams working
8 hour shifts and anyone who works outside of their designated shift
gets overtime pay.
Now consider you use this same employee data in your HR program,
and your accounting program, and your resource management program
plus a few others. Should all these different program supply their own
BAS module to calculate wages or to report work hours outside of their
regular shift schedule?
What if you could include a method in with the employee data that would
return the w ly pay amout, or total overtime hours worked. Wouldn't
that make it easier for the HR, and accounting, and CRM (etc.) programs
that need to handle employee data?
The problem is, if you update the HR program to say the new rule is that
not only is overtime outside of the regular shift, but it also can only be
applied when the employee has worked over 40 hours that w . So, you now
have a new rule that has to go into your accounting, and CRM, and any
other programs, right?
If you could keep that rule with the data, it would make things easier
because you would update the employee code, and every program that
uses the employee would automatically see the change.
But what is that employee code? Thats where classes fit in. They
extend the UDT to allow you to add methods and properties to your
data. Like a UDT you can store all sorts of data in a class, and like the
button, you can create as many as you need, and they each get their own
data, methods, and events. And, a bit like control arrays, you only have
to write code in one area to effect all the objects of that type.
The beauty is that you only write the code in one class, and at runtime that
class is created as an object, where you can make as many copies as you
need.
So now, all your programs use the employee object, that has an OverTimeHours
function that returns the employee's current overtime hours. When the rules
change, as they were changed above, you only make a change to the employee
object, and that gets propogated out to all the users of the employee object
without the need to add code and recompile those programs to add the new
rule. (Versioning your objects is a topic of another discussion...)
That is about it, in a nutshell, a class is an extention of the UDT in that, in
addition to data, (properties) you can add methods and events to that
group of data. You maximize code re-use (those other programs don't
need to include the BAS module to calculate overtime because it is provided
in the employee object) which is going to help maintain the whole suite of
programs by reducing and encapsulating the required code.
For a simple example, add a class to a new project, and give it two
public (string) properties: FirstName and LastName.
Then give it a public function called FullName:
Public Function FullName() As String
FullName = FirstName & " " & LastName
End Function
And another called SortingName
Public Function SortingName() As String
SortingName = LastName & ", " & FirstName
End Function
This is a ficticious example, but just to get used to the idea,
try it out, and use it in code, just to play with it a little:
Private People(0 To 2) As Class1 ' < Default name of your class
Private Sub Form_Load()
Dim i
For i = 0 To 2
Set People(i) = New Class1
People(i).FirstName = Array("Tom", "Dick", "Harry")(i)
People(i).LastName = Array("Ott", "Dan", "Arms")(i)
Next
Debug.Print People(0).FullName
Debug.Print People(0).SortingName
End Sub
(For reference, consider this Class1 code:)
Option Explicit
Public FirstName As String
Public LastName As String
Private mAge As Integer
Public Function SortingName() As String
SortingName = LastName & ", " & FirstName
End Function
Public Function FullName() As String
FullName = FirstName & " " & LastName
End Function
Public Property Get Age() As Integer
Age = mAge
End Property
Public Property Let Age(ByVal Value As Integer)
If Value < 1 Then
Err.Raise vbObjectError + 1, Me, "Too young to work!"
End If
mAge = Value
End Property
There are two parts to a property; the Let and Get parts:
Let part : Class1.Age = 45 ' Assignment to the class
Get part : X = Class1.Age ' Returned value from the class
If you single step through your code, you'd see the different parts
get called for the different assignment lines above.
Do you see how a rule was added to the Age property? You can't do that
with a UDT can you? Yet another reason why they are useful....
FYI: if the property is supposed to be an object, (As Textbox, for example)
then the parts are Set and Get (When using objects, always expect to use Set).
LFS
| |
| AustinMN 2004-05-28, 10:30 am |
| Tom_OM:
<snip>
> I have no doubt that class modules are useful; I'm just not getting
> them yet.
I'm going to give an example from a Genealogy program I wrote. I won't post
code because the amount of code is huge.
In this genealogy program, I have a class called clsIndividual, that
represents everything about that individual. When I want to work with a
particular person, I create an instance of the clsIndividual class and load
the new instance with the person's data. (Actually, it's more complicated
because generally you don't want more than one instance referring to the
same person, so I have to check to see if I already have an instance before
creating a new instance, but this isn't important to the discussion at
hand.)
Once I have the instance, I can pass it as a parameter, use it as a property
for other classes, or execute any of it's methods - anywhere I have a
reference to the instance.
Now suppose I have a routine that displays data about the person. If I was
using standard code, I would have to know when I wrote the routine what data
I was going to display. If I decide to add a parameter to what is
displayed, I need to add that to the list of parameters for the sub. I also
have to add it each place the sub is called. And I have to add it to those
routines (if not already there). If my call is nested 5 levels deep, adding
a brand new parameter to a routine can mean a lot of coding. Pretty soon,
you have some routines that have dozens of parameters. If you want to
change a value, you have to make sure that new value gets changed properly
everywhere it's used, and that it passes up and down the call stack like it
should. The alternative is a bunch of global variables, and that can get
mighty ugly when each person has a hundred properties and you are working
with an entire extended family. Imagine the amount of data to pass when
working with an individual's entire family. There may be parents/step
parents, siblings, step siblings, children, step children, spouse(s),
marriages, lots of dates (birth, death, baptism, burial, etc.) places
(birthplace, marriage place, death place, burial place, baptismal place),
sources (birth certificates, grave stones, publications, oral histories,
etc.), notes, military service data, and the list goes on and on.
But using the object, that's all I have to pass. If I decide I need an
additional parameter, I already have it because I have the object that
contains it. If I want to add a brand new parameter, I only need to add it
in the class. All the routines that use the object still work. If I want
to change a value, I only need to change the value in the object, and the
new data is immediately available to all other routines that use the object.
Another benefit with classes is when performing actions. In ordinary code,
I might have Individuals, Marriages, and Places. I could write three
routines for saving them (SaveIndividual, SaveMarriage, and SavePlace),
which I could then execute, but only in specific places (I need to be able
to pass all the parameters to the save routine [over 100 pieces of info. for
an individual], so if I'm in a routine that doesn't have all the parameters,
I can't save the data). If I add a new parameter, every place that calls
the save routine needs to be changed (and needs to have the new value, so
all of it's calling routines also need to be changed, etc.).
The alternative to this is to have a hundred save routines
(SaveIndividualBirthDate, SaveIndividualDeathDate, SaveIndividualBirthPlace,
etc.) Now, of course, whenever you execute one of these routines, you need
to make sure all your code gets the new value. And you need to make sure
every one of them gets executed when appropriate. If you add a new value,
you need to write a new routine and make sure it's called in all the
appropriate places (and that each of them has the new parameter).
But with objects, I can write one save routine in each class. As long as I
have a reference to the object, I can save it. In addition, I can have the
same syntax whether the object is an Individual, a marriage, or a place. It
doesn't matter that the routines are different or that the parameters are
different, because the object contains all the parameters needed to save
itself. All I need to do is say Father.Save or NewPlace.Save. If there are
new parameters that need to be saved, the only place I need to change
anything is in the class's Save method. All of the places I execute the
..Save method still work without modification.
I really hope this helps. I know OOP has transformed the way I think about
programming and made my life so much simpler.
Austin
| |
|
| Don't listen to Larry Serflaten, he's an american loon.
Basically, BAS modules are good for storing generic
*code* in one place. Great.
Class modules are for storing a mish-mash of
different *data* relating to a particular thing in one place,
*together with the code that operates on that data*.
Or they can be used to leverage events, which is basically
calling something back up the hierarchy,
i.e. child telling parent to do something rather than
parent telling child, with the difference that the parent
doesn't actually have to listen if it doesn't want.
For instance, say I've got a long operation that I want
to put in a generic code module. It doesn't have any
particular state data (that needs to persist outside of
the procedure level) that I might want to have multiple
instances of, so I could use a BAS module in that sense.
But supposing I want to implement a progress bar in the
form that calls this code, and
I want to have the long operation make a call to update
the progress bar at certain intervals. But I may also want
to use the long operation code in an application that doesn't
have a progress bar. Easy - with a class, I just use an event.
"Tom_OM" <dontspamme@junkmailstinks.com> wrote in message
news:v81eb0tv2gtanuq5kaapso22kb39lijd9g@
4ax.com...
> I've read in MSDN and in VB books about the usefulness of using class
> modules. However, I haven't really grapsed everything deep down.
> Thus far the idea of classes seems esoteric and theoretical; I'm
> having difficulty getting my brain to comprehend the nuts and bolts of
> it. I've yet to have that little bell in my head go "ping" as I
> realize how useful this VB feature is and how it will benefit me in
> the programs I write, and which of my own oft-used code would be best
> to convert to a classes. So far a simple module (*.BAS) has always
> sufficed for subs that will be reused over and over.
>
> I have no doubt that class modules are useful; I'm just not getting
> them yet. Does anyone know of a good online article about classes,
> preferably one that specifically shows some working structured code
> and how it can be converted to class-module code? It would be really
> helpful if the article pointed out how such an approach can improve my
> efficiency. I'm just not fully grasping why classes are better in
> some cases than simple BAS modules for reusing code.
| |
| Mike D Sutton @ Work 2004-05-28, 11:30 am |
| > I've read in MSDN and in VB books about the usefulness of using class
> modules. However, I haven't really grapsed everything deep down.
> Thus far the idea of classes seems esoteric and theoretical; I'm
> having difficulty getting my brain to comprehend the nuts and bolts of
> it. I've yet to have that little bell in my head go "ping" as I
> realize how useful this VB feature is and how it will benefit me in
> the programs I write, and which of my own oft-used code would be best
> to convert to a classes. So far a simple module (*.BAS) has always
> sufficed for subs that will be reused over and over.
>
> I have no doubt that class modules are useful; I'm just not getting
> them yet. Does anyone know of a good online article about classes,
> preferably one that specifically shows some working structured code
> and how it can be converted to class-module code? It would be really
> helpful if the article pointed out how such an approach can improve my
> efficiency. I'm just not fully grasping why classes are better in
> some cases than simple BAS modules for reusing code.
In addition to the other replies here, there are a couple of articles about classes in VB on my site which may be of interest to
you.
Hope this helps,
Mike
- Microsoft Visual Basic MVP -
E-Mail: EDais@mvps.org
WWW: Http://www.mvps.org/EDais/
| |
| Larry Serflaten 2004-05-28, 12:31 pm |
|
"B0nj" <b12@nj> wrote
> Don't listen to Larry Serflaten, he's an american loon.
Did you know the loon is the state bird of Minnesota?
I'd think that is somewhat better than developing a
reputation as the local troll....
http://dictionary.reference.com/search?q=troll
Troll:
2. An individual who chronically trolls in sense 1;
regularly posts specious arguments, flames or personal attacks to a
newsgroup, discussion list, or in email for no other purpose than to
annoy someone or disrupt a discussion. Trolls are recognizable by
the fact that the have no real interest in learning about the topic
at hand - they simply want to utter flame bait. Like the ugly
creatures they are named after, they exhibit no redeeming
characteristics, and as such, they are recognized as a lower form of
life on the net, as in, "Oh, ignore him, he's just a troll."
LFS
| |
| Ken Halter 2004-05-28, 12:31 pm |
| Larry Serflaten wrote:
> "B0nj" <b12@nj> wrote
>
>
>
> Did you know the loon is the state bird of Minnesota?
> I'd think that is somewhat better than developing a
> reputation as the local troll....
>
> http://dictionary.reference.com/search?q=troll
> Troll:
That definition should include "constantly changes user id to make it
impossible for people to block their posts"
>
> LFS
--
Ken Halter - MS-MVP-VB - http://www.vbsight.com
Please keep all discussions in the groups..
| |
| AustinMN 2004-05-28, 8:30 pm |
| Ken Halter wrote:
>
> That definition should include "constantly changes user id to make it
> impossible for people to block their posts"
You're giving most trolls too much credit.
Austin
| |
| Tom_OM 2004-05-29, 1:30 am |
| Many thanks to those who offered such outstanding and helpful advice.
I have all the info I need now to finally attain a solid understanding
of this important topic. And to Mike, your tutorial looks excellent;
I will be reading and applying every bit of it. And, Larry, I'm sorry
someone personally attacked you. That was unprofessional of the
person. You're advice on VB has been consistently top notch, earning
you respect. I know you will give no credence to the insults of a
troll.
cheers,
Tom
On Fri, 28 May 2004 09:22:09 GMT, Tom_OM
<dontspamme@junkmailstinks.com> wrote:
>I've read in MSDN and in VB books about the usefulness of using class
>modules. However, I haven't really grapsed everything deep down.
>Thus far the idea of classes seems esoteric and theoretical; I'm
[snip]
| |
| Bob O`Bob 2004-05-29, 1:30 am |
| Tom_OM wrote:
>
> And, Larry, I'm sorry
> someone personally attacked you. That was unprofessional of the
> person. You're advice on VB has been consistently top notch, earning
> you respect. I know you will give no credence to the insults of a
> troll.
Or perhaps he should wear it proudly as a badge of accomplishment.
Bob
--
On those thankfully rare occasions when my news killfile misses one, I cherish the
barbs and insults hurled personally at me by that particular troll ... though only
for whatever miniscule fraction of a second it takes to hit ^B (block sender) again.
| |
|
|
Definition of Loon
Pronunciation: lOn
n. 1. A sorry fellow; a worthless person; a rogue.
"Larry Serflaten" <serflaten@usinternet.com> wrote in message
news:%233mptbMREHA.904@TK2MSFTNGP12.phx.gbl...
>
> "B0nj" <b12@nj> wrote
>
> Did you know the loon is the state bird of Minnesota?
> I'd think that is somewhat better than developing a
> reputation as the local troll....
>
> http://dictionary.reference.com/search?q=troll
> Troll:
>
> 2. An individual who chronically trolls in sense 1;
> regularly posts specious arguments, flames or personal attacks to a
> newsgroup, discussion list, or in email for no other purpose than to
> annoy someone or disrupt a discussion. Trolls are recognizable by
> the fact that the have no real interest in learning about the topic
> at hand - they simply want to utter flame bait. Like the ugly
> creatures they are named after, they exhibit no redeeming
> characteristics, and as such, they are recognized as a lower form of
> life on the net, as in, "Oh, ignore him, he's just a troll."
>
>
> LFS
| |
|
| Yes, but it prevents you from forgetting I exist.
Others have the same attitude as you, but aren't
as determined not to read my posts.
"Bob O`Bob" <filterbob@yahoogroups.com> wrote in message
news:40B8176C.1A10@yahoogroups.com...
> Tom_OM wrote:
>
> Or perhaps he should wear it proudly as a badge of accomplishment.
>
>
>
> Bob
> --
> On those thankfully rare occasions when my news killfile misses one, I
cherish the
> barbs and insults hurled personally at me by that particular troll ...
though only
> for whatever miniscule fraction of a second it takes to hit ^B (block
sender) again.
| |
| Bob Butler 2004-05-29, 12:30 pm |
| "B0nj" <b123@nj> wrote in message
news:%23qZwlXXREHA.3660@tk2msftngp13.phx.gbl
> Yes, but it prevents you from forgetting I exist.
> Others have the same attitude as you, but aren't
> as determined not to read my posts.
That is simultaneously the most honest and the most pathetic post I've ever
seen.
| |
| Stefan Berglund 2004-05-31, 4:30 pm |
| On Sat, 29 May 2004 13:08:57 +0100, "B0nj" <b12@nj> wrote:
in <OwrqaWXREHA.2876@TK2MSFTNGP09.phx.gbl>
>
>Definition of Loon
>Pronunciation: lOn
> n. 1. A sorry fellow; a worthless person; a rogue.
Uhh, pot, kettle, black
---
Stefan Berglund
first shift-minus last a t m s n d o t c o m
| |
| Jim Carlock 2004-05-31, 7:30 pm |
| Funny.
A rogue is typically a thief or a muskateer on the dark side,
( Darth Rogue ? ) , and therefore cannot be all that worthless
if he is a good thief. I guess however Bill Gates could be a
Loon. In fact, I think he tries out to for the role of various
Loony Tunes characters. IE, the pie in the face, the blue
screen of death at the introduction of a new product, et al.
Name calling though, originates from self guilt. You can't
really call a person a loon or a troll unless you are one
yourself. So I take back my comment. Bill Gates is not a
Loon.
Although he cetainly looks like he's applying for the position
at times. ;-)
--
Jim Carlock
http://www.microcosmotalk.com/
Post replies to the newsgroup.
"B0nj" wrote:
Definition of Loon
Pronunciation: lOn
n. 1. A sorry fellow; a worthless person; a rogue.
"Larry Serflaten" <serflaten@usinternet.com> wrote in message
news:%233mptbMREHA.904@TK2MSFTNGP12.phx.gbl...
>
> "B0nj" <b12@nj> wrote
>
> Did you know the loon is the state bird of Minnesota?
> I'd think that is somewhat better than developing a
> reputation as the local troll....
>
> http://dictionary.reference.com/search?q=troll
> Troll:
>
> 2. An individual who chronically trolls in sense 1;
> regularly posts specious arguments, flames or personal attacks to a
> newsgroup, discussion list, or in email for no other purpose than to
> annoy someone or disrupt a discussion. Trolls are recognizable by
> the fact that the have no real interest in learning about the topic
> at hand - they simply want to utter flame bait. Like the ugly
> creatures they are named after, they exhibit no redeeming
> characteristics, and as such, they are recognized as a lower form of
> life on the net, as in, "Oh, ignore him, he's just a troll."
>
>
> LFS
|
|
|
|
|