2005-06-15
| Table of Contents: |
| Rate This Article: | Add This Article To: |
( Page 3 of 5 )
Extract Interface">
Encapsulate Field
C# properties have benefits in several areas, such as type encapsulation and interaction with tools like Visual Studio. Rather than publicly exposing fields from a type, you can wrap them in properties and make your code more maintainable and robust. From an object-oriented perspective, encapsulation is a compelling concept that is well-served by properties.
As an advocate of properties, I like the Encapsulate Field refactoring because it makes it easy to wrap type state. It converts a public field into a private field that is wrapped by a public property.
Given the field in Listing 4, right-click the field name, select Refactor, Encapsulate Field, and you will see the Encapsulate Field Dialog in Figure 4.
Listing 4. You generally want to make the internal state of your type private to promote maintainable and robust code. This example shows a public field prior to an Encapsulate Field refactoring.
public string value = "some val";
Extract Interface Sometimes there are types you build on the first go-round on a project that are stand-alone and don't have a hierarchy or interface implementation. However, on subsequent modification, the design calls for additional types requiring similar functionality. It is quite possible that your design will indicate a need for the extra types to share an interface with the type you've already created. This would be a good case for an Extract Interface refactoring. An Extract Interface refactoring essentially allows you to pick the members of your type that should be specified by an interface. It then creates the interface with those members and modify your class to inherit the new interface. To make this work, right-click on your type name, select Refactor, and select Extract Interface, which will display the Extract Interface dialog as shown in Figure 5.
Discuss Refactoring in Visual C# 2005 >>> Be the FIRST to comment on this article!
![]() |
|


