Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: Visual Basic
Expertise: Intermediate
Aug 7, 2001



Building the Right Environment to Support AI, Machine Learning and Deep Learning

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

      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.



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