Administrators PlausiblyDamp Posted August 21, 2004 Administrators Posted August 21, 2004 (edited) Guide to Object Orientated code in .Net This is a continuation of the series started in here and is preceded by this thread Introduction In the previous articles we have looked at a simple class that contains data and functionality. The data is simply stored as variables within the class for simplicity. The functionality of the class is exposed through three routines the Balance property and the Credit / Debit functions, in this article we will look at a bit of terminology and see how we can take advantage of some more .Net features. Class A class is a piece of code that defines the functionality of an aspect of our code, in the previous articles we have a simple class called BankAccount; this defines how a BankAccount works in our system � the data associated with it, the functionality it offers etc. wrapped up into a single logical unit. A class is really just code that it is written to server a particular purpose. A class can be thought of as a new datatype within .Net. Object Whereas a class is the underlying code, an object is an actual running instance of that class. When you declare a variable of your class and then create a new instance of it � the new instance is an object. An object has resources allocated to it, memory, cpu time etc. One class definition can have many running instances simultaneously with each instance maintaining its own separate copy of the variables. e.g. �The following line declares two variables that can hold a BankAccount Dim acc1, acc2 as BankAccount �the following line creates a new instance of BankAccount and �assigns it to acc1 acc1 = new BankAccount() �the following line creates another new instance of BankAccount and �assigns it to acc2 acc2 = new BankAccount() �Credit some money acc1.Credit(100) acc2.Credit(200) �acc1 and acc2 will each have there own value for the Balance property Methods in OO terminology a Method is simply a function, subroutine or procedure (depending on your languages choice of terminology) that is associated with an object. In our case the two Methods are Credit and Debit. A method will have access to all the class� internal variables as well as being able to call other functionality � either from within this class or other classes on the system. Public methods can be called from anywhere within our program � this includes code outside of the class (as can be seen in the form�s button click code), or they can also be declared Private which means they can only be called from within the same class. This gives us the ability to expose a public interface which other code (consumers or users of our class) can call on to access our functionality but still be able to structure re-usable code into reusable methods for the class� internal use. Overloading A feature of .Net (and most OO languages) is the concept of overloading a function, when used correctly this can result in cleaner, more readable code, typesafe code for users of our class. Overloading allows us to declare the same function name more than once within our class providing the parameters differ. In our current BankAccount implementation Credit and Debit both accept a decimal value, this is a perfectly reasonable datatype to use in this case, and if we are using data retrieved from other parts of the system this is probably a good choice. However if we are also dealing with a User Interface (UI) then we are going to be dealing with strings which will have to be converted decimals before we can call the existing methods; also if we are using decimal.Parse we probably want to allow the string to contain currency formatting - something that we may forget if we are having to do this conversion in several places (note the use of Decimal.Parse in both the Credit and Debit button clicks). One possibility is to create an overloaded function that will accept either a string or a decimal value. Public Sub Credit(ByVal amount As Decimal) _Balance += amount End Sub Public Sub Credit(ByVal amount As String) Credit(Decimal.Parse(amount, Globalization.NumberStyles.Currency)) End Sub Notice both method share the same name but different parameter lists � as long as the type or number of parameters are different then this will work; you cannot overload based on return type though., Also note how the overloaded version that expects a string simply converts the data to the correct format and calls the original version anyway, there is no need to duplicate code using cut and paste etc. In calling this function I can now provide either a decimal variable (actually compatible types like Integer and Long will also be accepted) or a string (note it will accept a string containing anything if it doesn�t contain a valid number then a runtime error will occur � this will be addressed in a later article). Any other datatypes will be rejected by the compiler. e.g. Dim acc As New BankAccount Dim s As String = "1,0000" Dim i As Integer = 100 Dim dt As Date = Date.Now Dim d as Decimal = 1.1 acc.Credit(s) 'Compiles acc.Credit(d) �compiles acc.Credit(i) 'compiles (because integers are compatible with decimals) acc.Credit(dt) 'doesn't compile Note how this removes the need for the calling application to always do the datatype conversion but without introducing a multitude of similar function names all serving a similar purpose (any C programmers out there will be familiar with the whole list of functions like atoi, atof, atol � all convert between a string an a number format � atoi: integer, atof: float, atol: long). Shared Members Notice how all the code written so far has required an instance of a class to work with i.e. we have had to declare a variable and set it to a new instance of the class before we can access functionality. Shared members (both methods and variables) do not require an instance and can be accessed direct from the class itself (e.g. MessageBox.Show, all the Math. methods are shared) This can be a useful way of including functionality into a class when you would be inclined to opt for a more traditional modular approach. As an example: our current system allows us to create a bank account and credit / debit it; the ability to transfer money between accounts would be a useful feature for any bank to have � but how do we implement this? We could provide a TransferTo Method or a TransferFrom method which accept another account as a parameter or alternatively look at the following code sample: Public Shared Sub TransferMoney(ByVal accountTo As BankAccount, ByVal accountFrom As BankAccount, ByVal amount As Decimal) accountFrom.Debit(amount) accountTo.Credit(amount) End Sub �This can be called like Dim acc1, acc2 As BankAccount acc1 = New BankAccount acc1.Credit(1000) acc2 = New BankAccount BankAccount.TransferMoney(acc2, acc1, 250) �Note the ClassName.MethodName syntax This provides a method that can be called without an instance of the class but still keeps the code associated with the BankAccount class � again there is a distinct lack of validation etc but this will be rectified in a later article. Playtime Again find attached a sample project containing working implementations of the above code. I suggest running the app and stepping through in a debugger to see the difference in calling an overloaded method and also how the Shared methods work. Next ConstructorsBankCS.zipBankVB.zip Edited September 22, 2004 by PlausiblyDamp Quote Posting Guidelines FAQ Post Formatting Intellectuals solve problems; geniuses prevent them. -- Albert Einstein
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.