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

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.

See also  Essential Measures for Safeguarding Your Digital Data

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist