Refactoring with Visual Studio 2005 – Encapsulate Field


One of the basic principles of object oriented programming is ‘Encapsulation’, and to me one of the fundamental ways to acheive encapsulation when creating classes is to only allow access to it’s private members through public accessor methods.

For example using C# I create the following class:

public class LeeClass

    {

        public String _name;

    }

 

 

The problem with this code is it directly exposes the classes data to the outside world and this breaks the encapsulation rules of OOP.

What we need to do to allow the outside world access to this variable is define a public accessor method which effectively ‘encapsulates’ the variable.

We can code this by hand but Visual Studio provides you with a handy refactoring function that handles all the work for you.

Do the following

Right click on the _name variable and select Refactor -> Encapsulate Field as show below.

Refactoring - Encapsulate Field

You will now be presented with a dialog box which allows you to give your new method a name.  You can also from here select the ‘External’ option in the ‘Update References’ option group which will update all references to your variable to point to your new accessor method.

You show now have a class that looks like this

public class LeeClass

    {

        private String _name;

 

        public String Name

        {

            get { return _name; }

            set { _name = value; }

        }

    }

 

 

Notice how Visual Studio changes your publicly exposed variable to private and inserts get/set methods to access it.

 

You now have a class that conforms to the encapsulation principle of object oriented programming.

One thought on “Refactoring with Visual Studio 2005 – Encapsulate Field

  1. currently i’m working with vs2005, but netbeans or eclipse do the refactoring in a really good way.

    An example, If you have a class with 20 attributes, how i can do the refactor faster ? do i have to click in each one attribute to make it ?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s