the blog
Back to -Blog

ActionScript Refactoring - Getters and Setters

Automating ’properties’ with Amethyst
by Huw Collingbourne
Saturday 30 May 2009.

Declaring public variables in your classes may give you a quick and easy way of accessing data ‘inside’ objects. But public variables are not well encapsulated (they do not enforce ‘data hiding’) so it is generally better to make variables private and access them using getter and setter methods. The ‘encapsulate field’ refactoring in Amethyst (introduced in beta 5) can automate this process.

Here is a simple example.

In the first window (above) you can see I have defined a Room class (in the file ‘’). This has a public variable called _name (you could call it anything you want, incidentally). In the bottom window is a separate file which accesses this variable directly (here._name). In principle, this variable might be accessed innumerable times throughout many files in my project. I want to change the name of the variable, make it private rather than public, create getter and setter methods to access it and update all references throughout my project to use the getters and setters rather than the variable itself. In a big project, without refactoring, that could involve a lot of work. But with Amethyst’s refactoring, it can be done in moments. Let’s see how.

First I right-click the declaration of the variable _name and select ‘Encapsulate Field’ from the ‘Refactor’ menu...

A dialog pops up and suggests that the variable be encapsulated as a property (a pair of getters and setters) called ‘Name’. I can either accept this suggestion or I can edit the property name - here I have edited it to ‘RoomName’...

Optionally, I can preview the changes that will be made, navigating down a tree of references to the _name variable in files throughout my project. If I want any of these to be left unchanged when the refactoring occurs, I can uncheck some branches. Here I want to update all references so I leave all branches checked...

This is the result of refactoring...

The original variable has been changed from public to private and a pair of getter and setter methods have been auto-generated to assign and return the value of the variable. These methods have been given the name which I selected, RoomName. All references throughout my project to the original _name variable have been changed to use the new getters and setters - for example, the code in the bottom window now refers to this property: here.RoomName.

And all this was done in a matter of seconds!

Bookmark and Share   Keywords:  Amethyst  refactoring
© SapphireSteel Software 2014