Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: VB4,VB5,VB6
Expertise: beginner
Dec 4, 1999

Implement Write-Once Read-Many Properties

Creating a read-only property or a write-only property isn't difficult, as you probably know: just omit the Property Let (or Set, if dealing with objects) or the Property Get procedure, respectively.

There are cases, however, when you want to implement a write-only-read-many property, that is, a property that can be assigned just once and be read any number of times. For example, the ID property of an object should never change after it has been assigned, so you should make it a WORM property. More in general, any property that is then used to retrieve additional information about an object from a database should be a WORM property.

Visual Basic doesn't offer a built-in mechanism for implementing a write-once read-many property, but it's easy to do it yourself, using a Static variable, as in the following code snippet:


Private m_ID As Long

Property Get ID() As Long
    ID = m_ID
End Property

Property Let ID(newValue As Long)
    Static initialized As Boolean
    If initialized Then
        Err.Raise 1001, , "Can't assign this property more than once"
    End If
    m_ID = newValue
    ' remember that the property has been set
    initialized = True
End Property
If the property has some special or invalid value, you don't even need to declare an additional Static variable. For example, suppose that the ID property can't take negative values:


Private m_ID As Long

Private Sub Class_Initialize()
    ' initialize ID with an invalid value
    m_ID = -1
End Sub

Property Get ID() As Long
    ID = m_ID
End Property

Property Let ID(newValue As Long)
    If m_ID <> -1 Then
        Err.Raise 1001, , "Can't assign this property more than once"
    ElseIf newValue < 0 Then
        Err.Raise 1002, , "Invalid value for the ID property" 
    End If
    m_ID = newValue
End Property
Francesco Balena
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date