More about faster Java coding in Eclipse Galileo

Using code templates

Eclipse includes the ability to define and use code templates that increase your productivity and make your code more predictable. This tip shows you how to edit the existing code templates and define new ones. It includes examples of the built-in variables so you can see what they resolve to in the editor.

Share:

Nathan A. Good, Senior Information Engineer, Freelance Developer

Nathan GoodNathan A. Good lives in the Twin Cities area of Minnesota. Professionally, he does software development, software architecture, and systems administration. When he's not writing software, he enjoys building PCs and servers, reading about and working with new technologies, and trying to get his friends to make the move to open source software. He's written and co-written many books and articles, including Professional Red Hat Enterprise Linux 3, Regular Expression Recipes: A Problem-Solution Approach, and Foundations of PEAR: Rapid PHP Development.



01 December 2009

Also available in Japanese Portuguese

The problems

Regardless of your project or team size, two problems occur when you edit the code base:

Code templates

Although code templates are a wonderful way to increase your productivity, make sure you don't use them to replace true reuse, which is writing methods or functions so that they can be used in many places. If you have large sections of code, always consider making methods with variables before using code templates.

  • Lack of consistency— When many people on a team edit files, small differences in coding can creep in and make the code more difficult to understand and maintain. It's more difficult to search for occurrences of code if they differ. Even if you work by yourself, differences can occur from day to day if you forget how you previously wrote a piece of code.
  • Lack of productivity— Saving keystrokes saves time because typing is at the heart of editing code. Larger sections of code may take some time to type or even to copy, paste, and change to fit the current context.

Before templates, a common but manual way of closing the gaps of consistency and productivity was to copy and paste. You search your existing code base — or the Internet — and copy the code that is closest to what you want to do. Then you change the parts that apply to your application.


The solution: Using templates

Templates in Eclipse are predefined listings of code that contain a section of code that doesn't change between uses. For instance, a for loop in Java™ code is constructed the same way no matter where it's used, except the inside condition or variables for the loop change. A template contains the parts that stay the same and uses variables for the parts that change.

Using templates in Eclipse is a great way to solve problems of consistency and productivity. With a template, you can write the code once and use it throughout your application with confidence. Or you might not even think about it, which is also the point.

This article explains how to:

  • Invoke templates
  • Edit templates
  • Create templates
  • Take advantage of variables in templates
  • Export templates
  • Import templates

Invoking a template

Invoking a template is easy. While typing in the editor, start typing the template name and use Ctrl+Space to invoke the code completion. The templates with names that match what you typed appear in the list (see Figure 1).

Figure 1. Choosing the template from the list
Figure 1 shows that the templates with names that match what you typed appear in the list

If you press Ctrl+Space again, Eclipse continues to cycle through the types of templates.

To insert a template, use the arrow keys to select the template from the list and press Enter. Alternatively, you can use the mouse to double-click on the name of the template in the list.

When the template is inserted, you have a chance to type in the values for the variables. Use the Tab key to move from variable to variable.


Editing a template

To edit a template, open the Eclipse Preferences by selecting Window > Preferences. Go to Java > Editor > Templates to see the existing templates. To edit an existing template, click on it in the list and click Edit. The Edit Template window appears (see Figure 2).

Figure 2. Editing the template
Figure 2 shows that the Edit Template window appears

Table 1 describes the fields in the Edit Template window.

Table 1. Field descriptions for the Edit Template window
FieldDescription
NameThe name of the template.
ContextThe context of the template. Eclipse limits the template choices to ones that are valid for the context. For instance, Java statements don't appear when you are editing XML files.
Automatically insertWhen selected, Eclipse automatically inserts the template if the full name of the template is typed and the template insertion is invoked (for instance, with Ctrl+Space).
DescriptionDescribes the template and is displayed in the drop-down list. The description helps identify the template because the name does not have to be unique.
PatternThe actual code that is inserted as the template, including any variables you want Eclipse to resolve.

You can edit the values for the template, and when you're done, click OK. To insert a built-in variable while you're editing the template, click Insert Variable. See "Taking advantage of variables in templates" to learn more about the variables available to you.


Creating a template

To create a template, click New. Edit the values as explained in "Editing a template," and when you're done, click OK. The new template now appears in the list. Click OK when you're done to edit your files.


Taking advantage of variables in templates

One of the largest challenges of using templates is knowing what the built-in variables resolve to when inserted into the code. These variables can automatically insert things like the name of the current type, location of the cursor, or selected values. The variables allow your templates to be much more dynamic and decrease the amount of manual changes you need to make to the template after it's inserted.

Consider the template code in Listing 1.

Listing 1. The template for a logging declaration
${imp:import(java.util.logging.Logger)}
private static Logger logger = Logger.getLogger(${enclosing_type}.class.getName());

When inserted into the Automobile class, the code looks like Listing 2.

Listing 2. The Automobile class after the logging declaration is inserted
private static Logger logger = Logger.getLogger(Automobile.class.getName());

You can see that the name of the class is resolved for you. This is better than the copy-and-paste technique where you can forget to update the name of the class. Because the incorrect class name in the declaration won't throw a compile error, you're likely to miss it until you're looking at the logs and wondering why the statements aren't where you expect them to be.

The import statement for the Logger is also automatically added for Logger at the top of the class.

Table 2 lists and describes the built-in variables that come with Eclipse for Java templates.

Table 2. Eclipse's built-in variables for Java templates
VariableDescriptionExample
cursorPlaces the editor's cursor in this location.N/A
dateInserts the current date.Oct 20, 2009
dollarInserts the literal dollar sign.$
elemTypeTries to guess the type of the element with the given ID.MyType
enclosing_methodInserts the name of the method that the template is being inserted into.method()
enclosing_method_argumentsInserts the arguments for the surrounding method.arg1, arg2
enclosing_packageInserts the name of the current class's package.com.example.ui
enclosing_projectInserts the name of the project that contains the class being edited.myProject
enclosing_typeInserts the name of the type (class) being edited.MyType
exception_variable_nameInserts an exception variable name, making a best guess.e, ioe
fileThe short name of the file.MyType.java
importInserts an import statement for the given type, if it's not already imported.import com.example.ui.MyOtherType
importStaticThe same as import, but with static imports.import static com.example.ui.MyOtherType.*
line_selectionInserts the selected lines in the location. Useful for wrapping lines with templates.do, while loop with selected lines as body
primary_type_nameShort name of the file without the extension.MyType
timeInserts the current time.9:09:35 a.m.
todoThe TODO tag in comments.TODO
userThe current user name.ngood
varResolves to local variables, providing a list if there is more than one.myvar
word_selectionInserts the currently selected word.N/A
yearInserts the current year into the code.2009

Another great feature of variables is that you can make up your own. They will not automatically resolve to any values. However, right after the template is inserted, you can type values into the template. When you type into a variable, the value you type is inserted wherever the variable is present in the code. Consider the template in Listing 3.

Listing 3. Creating your own variables
public void test${my_variable}() {
    String expected = "value";
    ${my_object}.set${my_variable}(expected);
    assertEquals("${message}", expected, ${my_object}.get${my_variable});
}

When you insert the template, it looks like Figure 3.

Figure 3. Automatically inserting the values
Screenshot showing automatically inserting the values

All you have to do is type in the first value, and the rest are automatically replaced. When you're done, press Tab to move to the next variable.


Exporting templates

To share your templates with other users, you can export them to a file. The file is an XML file that contains the template information and can be imported into other instances of Eclipse.

To export a template, select the template and click Export. Eclipse prompts you for a location where you can save the file. When you finish exporting the templates, click OK to close the Preferences window.


Importing templates

Team sharing

As a technical lead, I sometimes check my templates into a source-control repository where the other members of the team can access them.

You can import templates from a file that contains exported templates. To import a template, click Import. Eclipse prompts you for a file to import.

After you import the templates you want, click OK. You can now insert the new templates into your editor.


Summary

Code templates in Eclipse are a way to increase productivity and consistency in your applications. You can build code templates you can use to easily insert commonly used sections into your code while you're editing it. You can define variables in the code to automatically insert names of types, methods, or even selected code into your templates. When you have templates that you like, you can share them by exporting them and importing them into Eclipse.

Resources

Learn

Get products and technologies

Discuss

  • The Eclipse Platform newsgroups should be your first stop to discuss questions regarding Eclipse. (Selecting this will launch your default Usenet news reader application and open eclipse.platform.)
  • The Eclipse newsgroups has many resources for people interested in using and extending Eclipse.
  • Participate in developerWorks blogs and get involved in the developerWorks community.

Comments

developerWorks: Sign in

Required fields are indicated with an asterisk (*).


Need an IBM ID?
Forgot your IBM ID?


Forgot your password?
Change your password

By clicking Submit, you agree to the developerWorks terms of use.

 


The first time you sign into developerWorks, a profile is created for you. Information in your profile (your name, country/region, and company name) is displayed to the public and will accompany any content you post, unless you opt to hide your company name. You may update your IBM account at any time.

All information submitted is secure.

Choose your display name



The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerWorks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

Required fields are indicated with an asterisk (*).

(Must be between 3 – 31 characters.)

By clicking Submit, you agree to the developerWorks terms of use.

 


All information submitted is secure.

Dig deeper into Open source on developerWorks


static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=Open source
ArticleID=449569
ArticleTitle=More about faster Java coding in Eclipse Galileo
publish-date=12012009