devxlogo

Encapsulate Member Objects

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

size=3>
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

size=3>
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.

devx-admin

Share the Post: