tyWe will now move into a more advanced aspect of VB - OOP. But don't worry, Object Oriented Programming is quite simple, in fact it is probably simpler for those who have never programmed before than for those with long experience of traditional Fortran/Basic/Pascal (pick your favourite imperative language). You should be familiar with VB's event-driven programming style by now. However I'll explain it again. When you're doing general VB programming, your thoughts should go in this pattern: "If the user does this, what should happen? How would I make it happen?" Then you would write the program to fit the answers to these questions. That is event-driven programming. You program according to what events the user would trigger. Dragging a picture, clicking a button, and typing a word are all events. You, being the brave coder that you are, would ask: "WHY do I HAVE to think like that??" Well here's an alternative way for you to think: Object Oriented Programming(OOP). In the world of OOP, you break a problem down into small parts and solve them individually. If you are to program in an object oriented style, you would think of every variable or functions as a property of an object, and everything would seem like an object to you. OOP is hard to explain so you'll have to experience it in the following examples. Imagine that you have a bottle of juice. What properties does it have? What events does it have?(What can it do?) Here's a list I could think of:
Private Colour As String 'What colour? Private Fruit As String 'What kind of fruit? Private Volume As Single 'How much? Public Sub MakeJuice(c As String, f As String, v As Single) 'Make some Colour = c Fruit = f Volume = v End Sub
Public Sub Evaporate() 'Well, that's the only thing I could think of Volume = Volume - 10 End Sub
Behold. That's our first class. Don't worry about anything right now. I will go over those later. Anyway, let's assume that this class is named, "Juice". Think of it as a general description of a bottle of juice. Now we can create an actual bottle of apple juice:
Private AppleJuice As Juice 'Define Set AppleJuice = New Juice 'Create a new instance of Juice AppleJuice.MakeJuice "brown", "apple", 30
Watch:
AppleJuice.Evaporate '20 units left AppleJuice.Evaporate '10 left AppleJuice.Evaporate 'Yes!!
"Wait", you interrupted my rant once again, "but why do I have to use OOP? Just because you hate apple juice?" OOP is good for large-scale programming - As your code grows large, there are going to be more and more procedures/functions to your program, and your code is going to be so cluttered that one more look at it, you'd scream. That is why I'm teaching you OOP! (So instead of looking at hundreds of scattered procedures/functions, you look at organized Objects.)