CodeRush encapsulation refactorings
As we know, Encapsulation is an important object-oriented programming concept. It is also known as a data hiding mechanism. Encapsulation enables a group of properties, methods and other members to be considered a single unit or object. The idea of encapsulation is that an object’s internal data should not be directly accessible from an object instance. With correct encapsulation, a developer does not need to understand how the class actually operates in order to communicate with it via its publicly available methods and properties.
CodeRush has several refactorings that allow you to encapsulate fields and its members easily. They are:
- Encapsulate Field
- Encapsulate Field (read-only)
- Encapsulate Method
- Encapsulate Property
- Encapsulate Event
The Encapsulate Field refactoring encapsulates a field into a read-write property and replaces all occurrences of this field with the newly declared property. If a field is non-private, the refactoring will change it into a private field (encapsulation). The new property is given the same visibility as the original field (e.g., public, internal, etc.).
Apply the refactoring to an active field to encapsulate it:
You can choose the target location of the property with the help of a target picker:
The resulting property looks like this:
The second Encapsulate Field (read-only) refactoring is absolutely the same as Encapsulate Field, but creates a read-only property without writing access:
The other refactorings are also available on a field. They allow you to encapsulate a property, a method or an event of a field. These refactorings create new accessing members to members of an instance of a field.
Consider we have the following field declaration:
These refactorings allows you to choose which member you would like to encapsulate. For instance, the Encapsulate Method refactoring:
The refactoring will produce the corresponding code once applied:
Here is the result of Encapsulate Property for the AutoReset property:
And finally, the result of the Encapsulate Event for the XXX event:
All refactorings allow you to choose the target location and drop a marker to easily move back at the original location where the refactoring was applied.
Happy encapsulation using CodeRush!
—– Products: CodeRush Pro Versions: 12.1 and up VS IDEs: 2008 and up Updated: Jul/23/2012 ID: R057