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: Visual Basic
Expertise: Intermediate
Aug 6, 2001

Encapsulate Member Objects


Objects frequently contain member objects that need to be exposed. Often, these are not correctly encapsulated, which could lead to problems that are difficult to track down.

Consider a Circus object, which has a private collection of the names of its clowns. We could expose this Collection with a public property:
 
   Public Property Get GetAllClowns() As Collection
      set GetAllClowns = m_colClowns
   End Property

This passes a pointer to the private collection to the caller. This private collection might as well have been declared public, because the caller can get a reference to the private object and do whatever it wants with it. Therefore, the code above does NOT encapsulate its clowns. A better way to get our clowns would be to return a new collection:
 
   Public Property Get GetAllClowns() As Collection
      Dim colClowns   As Collection
      Dim sClown      As String

      Set colClowns = New Collection
      For Each sClown In m_colClowns
         colClowns.Add sClown
      Next

      Set GetAllClowns = colClowns
   End Property

If you are dealing with your own objects, rather than Collections, you could provide a Clone method in the object you will be exposing through a property. Clone() should return a copy of its object. Then, instead of returning a member object in the Property Get, simply Clone it and return the clone.
Chris McCann
 
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