Wednesday Dec 07, 2005

Encapsulating Fields, aka generating Getters / Setters


Thought I would start a little blog series talking about some of the code generation features of the NetBeans IDE which should make NetBeans users more productive. It's likely that many of our NetBeans IDE users already know about some of these features. However, there's likely some new developers coming into the NetBeans community who are not aware of some of these capabilities.

To start things off, I thought I would look at a commonly overlooked code generation capability of encapsulating fields, or often times called getters and setters.

Both of these terms refer to the common workflow of taking a class variable, usually scoped with private access, and adding a method, usually scoped with public access, to 'set' or 'get' the value of a class variable.

Yeah, I know this probably is not ground shaking news to many developers. But, it may clear up any confusion as to the terms "encapsulate fields" versus "getters/setters".

In NetBeans IDE 5.0, there are a couple ways to encapsulate fields, or generate getters/setters.

One way is to use Refactor | Encapsulate Fields which can be selected from the context sensitive menu when you right click inside the NetBeans IDE editor or you can select Refactor | Encapsulate Fields from the main menu. Once you have selected Refactor | Encapsulate Fields, you can:
- specify which fields you would like to have getters and setters generated for
- specify field visibility
- specify accessor visibility
- whether to use the generated getter/setter when the field is accessible

Here's the UI presented when you select Refactor | Encapsulate Fields:




A second way to encapsulate fields or generate getters / setters is in the developer workflow where you declare class variable and would like to encapsulate that variable with a getter and/or setter.

Here's the typical workflow. Declare a class variable, after you press ';' to terminate the line and hit <Enter> to go to the next line, press <Control-Spacebar>. The NetBeans IDE will give you a set of options which will include a choice to generate a getter and setter for the class variable you just entered.

Here's a screenshot where I had just entered 'Menu itsMenu; <Enter> <Control-Spacebar>' in the NetBeans IDE editor:


As you can see, NetBeans IDE has given me a choice to create a getter or setter for the class variable I just created.

Enjoy!

Comments:

Post a Comment:
Comments are closed for this entry.