Hiding your data and accessing it through an outward interface based on accessor methods is a good idea. Later you can change the data internals, preserving full compatibility with the code relied on the class and its available methods. The Encapsulate Fields refactoring allows you to hide your data and create the necessary accessors.
To perform the Encapsulate Fields refactoring, follow these steps
- Select a class or a specific field within the class. The way you perform selection depends on the
view where you do it.
- In the editor: position the caret at the desired field or at any place inside the class to be refactored.
- In the Project view: select the desired class.
- In the Structure view: select one or more fields.
- On the main menu or on the context menu of the selection, choose Encapsulate Fields dialog box is opened, displaying all fields, detected in the selected scope. . The
- In the Fields to encapsulate area check the fields you want to create accessors for.
- In the Encapsulate area, specify whether you want to create getter or setter methods, or both.
- To replace all field occurrences with the calls to the appropriate accessor method, in the Options area check the option Use accessor even when field is accessible.
- In the Encapsulated fields' visibility area specify the new visibility scope for the selected fields.
- In the Accessors' visibility area select the visibility scope for the created accessor methods.
- Preview and apply changes.