Skip to main content

Encapsulate Field

  • 2 minutes to read

Encapsulates a field into a read-write property and replaces occurrences of this field throughout the class with the newly declared property.

#Purpose

Changing and accessing data directly (through fields) may lead to a separation of the algorithms that process the data from their actual storage. Data encapsulation (data storage and processing in one place) makes code management easier than the alternate where data changing and validation routines can appear in multiple different places throughout the code. So if you have a field that requires data validation in assignments and / or additional processing while access data, the Encapsulate Field refactoring will give you the first step in better organization of your data access interface.

#Availability

Available from the context menu or via shortcuts:

  • This refactoring is available for .NET property declarations only and won’t work with native C++ constructs.
  • when the edit cursor, or caret is on a field declaration.
  • when the name is selected within the field declaration statement.

Note

If the selected field is already used to store a property’s value, then Encapsulate Field will be unavailable.

#Notes

  • You can choose the newly declared property’s location using the target picker (see Settings below).
  • Encapsulate Field creates a private field instead of the selected one and a public read-write property that accesses this field’s value.
  • All references to the source field are replaced with a reference to the newly declared public property.
  • Rename is automatically invoked for the newly declared field and property so you can give the meaningful names.

#Options

  • You can control whether the newly declared property should be located at the top of the type, right below the source field or at the location you choose with the target picker.

#Example

Public TestString As String
Public Function AddString(ByRef SrcString As String) As String
    Return String.Format("{0}{1}", SrcString, TestString)
End Function

Result:

Private TestString As String
Public Function AddString(ByRef SrcString As String) As String
    Return String.Format("{0}{1}", SrcString, TestString1)
End Function
Public Property TestString1() As String
    Get
        Return TestString
    End Get
    Set(ByVal value As String)
        TestString = value
    End Set
End Property

#Animation

EncapsulateFieldVB