Pensieri di un lunatico minore

9 February 2006 Smalltalk

Class extensions rock

Earlier, I wrote about extending classes, I wanted to give a clear example of what I personally think is a good use for this. I’m working on some time-travel stuff. As I’m writing some tests to talk about what I want to the code I’m working on to do, I get to this:

TimeTravelTest>>testToday
    | stock version |
    stock := Stock new.
    version := StockVersion price: 12.25.
    stock versionAt: (Date readFromString: '1/12/2006') put: version.
    self assert: (stock versionAt: (Date readFromString: '1/12/2006')) price = 12.25.

That works just fine, but it doesn’t really read very well. So, I created a class extension, and added a new message asDate to CharacterArray that just looks like this:

CharacterArray>>asDate
    ^Date readFromString: self.

so that I can do this instead:

TimeTravelTest>>testToday
    | stock version |
    stock := Stock new.
    version := StockVersion price: 12.25.
    stock versionAt: '1/12/2006' asDate put: version.
    self assert: (stock versionAt: '1/12/2006' asDate) price = 12.25.

That, to my mind, reads much better, and is a clear example of how extending a class can be a “good thing,” if used correctly. It actually creates a situation where the flow of the code is clearer and more explicit about what you are trying to do. I haven’t actually introduced any new dependency between the two classes, but simply made one more expressive.

I would love to use the Chronos Smalltalk library, but as of yet it is not capable of parsing strings, as near as I can determine, even though it can do everything else, including dealing with leap-seconds. Converting from the VisualWorks Date class to a Chronos class seems silly at this point.

This entry was posted at 11:33 am on 9 February 2006 and is filed under Smalltalk. You can follow any responses to this entry through the post-specific RSS 2.0 feed.

I would love to use the Chronos Smalltalk library, but as of yet it is not capable of parsing strings, as near as I can determine

Correct. But that feature will be available in a month or so.
—Alan

Awesome. I look forward to that capability. Unfortunately, there’s a lot of ways to express date and time, especially when you move into relative times. It would be nice if Avi and Andrew would share some of their code for Dabble, which seems to handle a lot of relativistic dates.

[...] In an earlier post, I had mentioned that I wanted to use the Chronos library for some work, but was hamstrung because it didn’t support parsing of text strings. Well, now that has changed, and it looks like it can handle most things you throw at it. [...]

how about “23 jun: 2006” ?

all you have to do is define 12 methods like:

SmallInteger>>jun: aNumber
^Date newDay: self monthNumber: 6 year: aNumber

Responses are currently closed, but you can trackback from your own site.