This time, I will be looking at another question that has been posed in the Real Studio forums on more than one occasion. The question is how to determine the last day of any given month.
At it's simplest, I could just write a single method to accomplish this, and it would be perfectly valid. However, RealBasic is an object orientated language and I want to explore a true object orientated approach method for solving the problem.
As I already have a Date class which handles most of the time and date functions, it seems only right that I use this as my base. But, this time, I shall not be creating a subclass of the Date class, this time I shall be extending the class. Extending a class allows me to add methods to an existing class and then use them as if they are defined in the class definition. The advantage of this over a subclass, is that I can still continue to use the Date class with existing classes and methods, with no modifications.
Hopefully, this will become clearer as I progress.
To extend a class, I need only create a new method, in a module. However, the first parameter of that method must be of the class type that I am extending and use the keyword Extends.
First step then, is to create a new module in our project. In the screen shot, I have renamed this module to DateExtensions.
So, to create a method that adds to the Date class and returns the last day of the current month, I declare my new method in DateExtensions thus:
Function LastDayOfMonth(Extends d As Date) As Integer
The declaration of this method is:
Function IsLeapYear(Extends d As Date) As Boolean
Before I do add the code, I ought to mention something about extending a class. When a method is added to an existing class, by using the Extends keyword, the program can refer to the instance of the class with the first parameter in the parameter list. Hopefully, this will demonstrate.
Therefore, if the year stored in the object is a leap year, then IsLeapYear will return True, otherwise it will return False.
Now I can determine if the year is a leap year, I can now insert the code into LastDayOfMonth:
I use a simple Select Case condition on the month of the Date object.
If the month is 2 (February), then I know that I need to check if I am in a leap year, so I use the new IsLeapYear method to test this. If I am in a leap year, then return 29, otherwise, February only has 28 days.
The next Case statement tests if the month is one of the following: January, March, May, July, August, October or December. These months all have 31 days, so that is what is returned.
Finally, if neither of the above two Case statements are True, then the month must have 30 days.
That is it. The Date class has now been extended to include two new methods. The methods are used like any other method of the Date class. For Example, the following code creates a For...Next loop for everyday of the current month:
No comments:
Post a Comment