Useful eclipse templates

When working as a coder, you have to now your tools. And the tool you’re using most is the IDE of your choice. Most Java-programmers choose Eclipse as their development-platform, because it is free and powerful (I remember the days when JBuilder 2.0 was state-of-the-art – I don’t miss them). Facing your daily business, you’ll often find yourself write the same (boilerplate) code-snippets:

  • getters and setters
  • equals and hashcode
  • make a class a Singleton
  • create a local logger-instance
  • etc.

As a coder you should hesitate when writing them repetetive and ask yourself: is there a way to automatize it? I mean automatization is one of the main reason why computers were invented and the programs you’re writing are doing the same things repetetive (and fast). Some of those tasks can be automatized with build-in Eclipse-features (Source – menu), but others not. At least by default.

Eclipse has a cool feature, calling “Code Templates” which ist accessible via Window -> Preferences. “Code Templates” allow you to store code-snippets and substitute the code with a meaningful name. Let’s start with a simple example, e.g. having a shortcut to Java’s currenttime:

  1. Press the New… – Button.
  2. Enter a meaningful name like _currenttime (I prefer adding underscore to the name, to group all my templates).
  3. Add a description if you like.
  4. Write System.currentTimeMillis(); into Pattern-Textbox.
  5. Press OK.

When you’re writing code the templates are part of the auto-completion-feature which is accessible pressing CTRL+SPACE. In future, when you’d like to know the system’s current time, just write _cur and press CTRL + SPACE and then ENTER. Eclipse will replace that with the pattern you’ve written into the template. Here are some useful Code Templates:

Description: Creates the singleton boilerplate-code.

Pattern:


private static ${enclosing_type} instance = new ${enclosing_type}();

private ${enclosing_type}(){}

public static ${enclosing_type} getInstance(){
return instance;
}

Description: Creates a static SLF4J-Logger-instance in current class.

Pattern:

${:import(org.slf4j.Logger,org.slf4j.LoggerFactory)}
private static final Logger logger = LoggerFactory.getLogger(${enclosing_type}.class);

Description: Creates a try-finally block for locking-purposes.

Pattern:

try{
lock.lock();${cursor}
}finally{
lock.unlock();
}

Stackoverflow has many suggestions on this topic. What are your favorite templates?

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s