Tag Archives: templates

Know your Tools: An Introduction to Eclipse Templates

How often do you find yourself writing the same small piece of code over and over and over?

Never, because I follow the D.R.Y. methodology, or “Don’t Repeat Yourself”, so I-

Let me stop you right there.  I mean really small pieces of code.  Things like this:

System.out.println( message );

That’s a good couple dozen keystrokes, and I’m positive you write other recurring code snippets over and over.  For me a common one is a null and empty check on Collections:

if( CollectionUtils.isNotEmpty( bar ) ) {
	//Do some stuff
}

Let’s go back to the print line example and see how we can speed that up, using a built-in template. In Eclipse, simply type “syso” and then hit the content assist shortcut (ctrl + space). Eclipse will replace the “syso” with the only named template that has a match in its name, which is the above print line code.

To more easily see what’s happening, hit the content assist shortcut first, and then type “syso”.  First, you’ll see the familiar dialog pop up:

content assist

Then, while typing “syso”, you’ll notice the options fall away as Eclipse filters out options that don’t match, and you’ll be left with one option, a template:

content assist filtered

That template is then used to generate code for you.

Built-in Templates

There are numerous templates already available for you.  Such as quickly generating a for-loop.

content assist for loop

Hint: Hitting ctrl+space a second time will show you just templates.  

Writing Your Own

For when the built-in templates have failed you and there isn’t one that does what you want, you can write your own.  For example, the second code snippet at the beginning of this post makes use of the class “CollectionUtils”, which is an Apache Commons utility class.  There wasn’t a built in template for that.  So to make it, go to:

Window -> Preferences -> Java -> Editor -> Templates

preferences templates

Click on “New”, and create whatever template you like!  Here’s mine to check Collections for null or being empty:
custom template creation

Hint: “Insert Variable” can help you figure out those “${…}” values.

Which is now in the content-assist window and will allow me to rapidly check future collections before I begin to use them:
custom template in action

In Conclusion

Using templates, both built-in and custom, can save you a lot of time and keystrokes.  Try ’em out.