Login | Register   
RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: Visual Basic
Expertise: Beginner
Aug 6, 1997



Full Text Search: The Key to Better Natural Language Queries for NoSQL in Node.js

Using The For-Each Syntax On A Private Collection Object

Creating an object that looks and acts like a collection is a good way to implement a form of inheritance in VB4, where inheritance is not provided by the language. Creating properties for the Count and Item properties of your collection is not difficult. Likewise, creating an Add and Remove method is fairly easy. You can restrict the type of data added to a collection, and you can encapsulate all of the object handling in your class. However, there are two problems. You can expose the Item property, but you can't make the Item the default property. Instead of writing:
 val = MyCollection("Fubar")
you must always write:
 val = MyCollection.Item("Fubar")
There is no way to allow a VB user to use the For-Each syntax and still keep your encapsulation complete. If you are willing to break your encapsulation, you can provide an Items property, like this:
 Property Get Items() As Collection
	Set Items = collMyInternalCollection
End Property
Users can iterate your collection object like this:
 For Each obj in MyCollection.Items
	' Do something
The problem with this method is that your users can now invoke the Add and Remove methods directly on the exposed collection. You have lost control of the data, and your encapsulation is broken. If you are willing to trust that your users will not use either the Add or Remove properties on this object, then this is a possible workaround.
A. Nicklas
Comment and Contribute






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



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