Regardless of your project or team size, two problems occur when you edit the code base:
- 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.
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 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
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.
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
Table 1 describes the fields in the Edit Template window.
Table 1. Field descriptions for the Edit Template window
| Field | Description |
|---|---|
| Name | The name of the template. |
| Context | The 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 insert | When 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). |
| Description | Describes 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. |
| Pattern | The 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.
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 insertedprivate 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
| Variable | Description | Example |
|---|---|---|
cursor | Places the editor's cursor in this location. | N/A |
date | Inserts the current date. | Oct 20, 2009 |
dollar | Inserts the literal dollar sign. | $ |
elemType | Tries to guess the type of the element with the given ID. | MyType |
enclosing_method | Inserts the name of the method that the template is being inserted into. | method() |
enclosing_method_arguments | Inserts the arguments for the surrounding method. | arg1, arg2 |
enclosing_package | Inserts the name of the current class's package. | com.example.ui |
enclosing_project | Inserts the name of the project that contains the class being edited. | myProject |
enclosing_type | Inserts the name of the type (class) being edited. | MyType |
exception_variable_name | Inserts an exception variable name, making a best guess. | e, ioe |
file | The short name of the file. | MyType.java |
import | Inserts an import statement for the given type, if it's not already imported. | import com.example.ui.MyOtherType |
importStatic | The same as import, but with static imports. | import static com.example.ui.MyOtherType.* |
line_selection | Inserts the selected lines in the location. Useful for wrapping lines with templates. | do, while loop with selected lines as body |
primary_type_name | Short name of the file without the extension. | MyType |
time | Inserts the current time. | 9:09:35 a.m. |
todo | The TODO tag in comments. | TODO |
user | The current user name. | ngood |
var | Resolves to local variables, providing a list if there is more than one. | myvar |
word_selection | Inserts the currently selected word. | N/A |
year | Inserts 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
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.
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.
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.
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.
Learn
-
Read "Faster
Java coding in Eclipse Galileo" to learn about the
toString()generator feature in Eclipse Galileo. -
Check out the "Recommended Eclipse reading list."
-
Browse all the Eclipse content on developerWorks.
-
Follow developerWorks on Twitter.
-
New to Eclipse? Read the developerWorks article "Get started with the Eclipse Platform" to learn its origin and architecture, and how to extend Eclipse with plug-ins.
-
Expand your Eclipse skills by checking out IBM developerWorks' Eclipse project resources.
-
To listen to interesting interviews and discussions for software developers, check out check out developerWorks podcasts.
-
The My developerWorks community is an example of a successful general community that covers a wide variety of topics.
-
Stay current with developerWorks' Technical events and webcasts.
-
Watch and learn about IBM and open source technologies and product functions with the no-cost developerWorks On demand demos.
-
Check out upcoming conferences, trade shows, webcasts, and other Events around the world that are of interest to IBM open source developers.
-
Visit the developerWorks Open source zone for extensive how-to information, tools, and project updates to help you develop with open source technologies and use them with IBM's products, as well as our most popular articles and tutorials.
Get products and technologies
-
Check out the latest Eclipse technology downloads at IBM alphaWorks.
-
Download Eclipse Platform and other projects from the Eclipse Foundation.
- Download
IBM product evaluation versions
or explore
the online trials in the IBM SOA Sandbox and get your hands on application development tools and middleware products from
DB2®, Lotus®, Rational®, Tivoli®, and WebSphere®.
-
Innovate your next open source development project with IBM trial software, available for download or on DVD.
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.

Nathan 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.




