nbro
nbro

Reputation: 15837

Is that possible to make member variables automatically private in Eclipse?

I would like that Eclipse automatically add the modifier private when finish typing the declaration of a member variable. If this option is not automatically present in the IDE, do you know a useful plug-in for such a purpose?

Since I tend to respect the OOP good programming practices, it would be very useful to have this option, like the existent option of making automatically the variables final.

Upvotes: 1

Views: 1328

Answers (2)

E-Riz
E-Riz

Reputation: 32915

In Preferences > Java > Editor > Templates, you could create a new template that inserts a private member variable. These templates can be invoked by typing part of the template name and then invoking Content Assist Ctrl+Space (or Command+Space on a Mac).

Here's the text of such a template that I use:

private ${type} ${variableName};

Selecting this template from Content Assist will insert the code and you can enter the class/type and variableName, tabbing through them.

In this screen shot, I typed inst and then Ctrl+Space, you can see my template listed as the top choice:

enter image description here

Here you can see Eclipse prompting me to enter the type and variableName after I selected the instance variable template:

enter image description here

Upvotes: 3

Waog
Waog

Reputation: 7245

Problem with on save trigger

This can't be accomplished properly on saving, because no visibility declaration means package scope in the java language. You couldn't declare package scope if you would automatically convert no visibility declaration to private scope.

Use Templates

In my eclipse installation there is a java template called static_final. Try to trigger it by using Ctrl + Space. You could use this template or add an own similar template, to enforce a visibility declaration. (See Window > Preferences > Java > Editor > Templates)

My best practice

Don't care about private variables at first. Only introduce them the moment they are needed. Use eclipse auto completion and refactoring features, to introduce your variable.

Option 1

enter image description here

Option 2 If you want the assignement together with the declaration, in

enter image description here

right-click the string > Refactor > Extract local variable

Upvotes: 2

Related Questions