Thursday, September 14, 2023

Top 10 Eclipse Code Templates Java programmer should know

Every Java programmer wants to code fast and this is important because Java is more verbose than some of the cool scripting languages e.g. Python. Eclipse Code templates can help you to write faster code in Eclipse. If you used correctly Eclipse code template can generate all kinds of boilerplate code for you. Eclipse IDE comes with some frequently used Eclipse code templates e.g. sysout which is faster way to generate System.out.println() statements. Surprisingly, not every single Java programmer working in Eclipse is familiar with this cool feature which can save tons of times writing boilerplate code related to Exception handling, logging and frequently used test code e.g. writing main method. 

You can trigger Eclipse code templates by typing few matching word e.g. sy and then pressing alt+enter which is Eclipse shortcut for code completion or content assist, it will then show matching Eclipse code templates at top, e.g. sysout, synchronized. 

Just select needed Eclipse code templates and press Enter, Your code is ready. You can really increase your coding speed, if you get into habit of using Eclipse code templates.

 In  this Java Eclipse tutorial we will see some of the frequently used Eclipse code templates which Java programmer should be familiar and How to create new Eclipse code template, also known as user defined Eclipse code templates.



Built-in Eclipse code templates

Eclipse IDE provides good number of built-in Eclipse code templates for frequently needed Java code e.g. switch, try catch block, sysout etc. Though this number vary based upon which Eclipse IDE version you are using, you are most likely find these common Eclipse code templates in your Eclipse IDE.

  • main            Generates main method
  • sysout          Generates Sytsem.out.println code
  • ifelse          used to generate if else code block
  • for             Generates standard for loop code
  • while           To Generate while loops with variations to iterate over Enumeration, Iterable or with condition.
  • switch          Generates switch block
  • runnable        used to implement Runnable interface
  • try             used to create try catch block code
  • foreach -       used to create Java 5 foreach loop to iterate over array or Iterable e.g. Collections
  • lazy            used to lazy initialized a resource

Built-in Eclipse code templates not only contain Java statements but also Javadoc and SWT statements. In this blog we will only discuss Java code templates because that is one you will be mostly using while writing Java programs in Eclipse IDE. 

By the way you can see complete list of inbuilt Eclipse code templates by going into Windows-->Preferences-->Java-->Editor-->Templates . Here is how they look like when you open them in Eclipse IDE.

Top 10 Eclipse Code Templates Java programmer should know



How to create User defined Eclipse Code Templates

Now this is real power of Eclipse Code Templates, you can create your own code templates and use it just like built-in Eclipse code templates. Since every developer, depends upon kind of project, has some frequently used code to create. 

They can define that repetitive code as Eclipse code template for faster coding. Here we will see some of the most common user defined Code Templates which complements default inbuilt Eclipse code templates.

In order to create custom Eclipse code templates, open Template Screen by going to Windows-->Preferences-->Java-->Editor-->Templates and then click New.

Eclipse will ask for name, context, description and pattern. You can give name which is short and matches with functionality e.g. I usually give log to create Log4j logger, description is text which comes during content assist along with this Eclipse code templates, choose context as Java and provide required pattern to generate code. 

Eclipse allows you to choose variable from insert variable list which suits your purpose. Here is some examples of most common user defined Eclipse Code templates :

1. Log4j logger

Though Eclipse has a built in getLog code templates, it uses Apache commons logging library to create logger. Since most of Java developer uses either log4J or SL4J it make sense to create separate code templates in Eclipse for log4j or SLFJ loggers.  Here is the pattern code to create log4j logger as Eclipse code template :

${:import(org.apache.log4j.Logger)}
private static final Logger logger = Logger.getLogger(${enclosing_type}.class);

This code template creates log4j logger by importing org.apache.log4j.Logger and replacing ${enclosing_type} with name of the class on which it gets created.

Here is  an example  

private static final Logger logger = LogF.getLogger(Main.class);

2. Logging message with different log level

Another useful user define Eclipse code template, I have seen is to generate different level of logging e.g. INFO, WARN and ERROR. You can create Eclipse code templates for each of logging level and just call it as info, warn or error. There is a built in debug Eclipse code templates also, which can create debug logging code. Here is a sample code

logger.error(${cursor});

3. InvokeAndWait and InvokeLater

If your doing GUI development in Java and using invokeAndWait and invokeLater from Swing API, than you can use following Eclipse code templates to generate Runnable task. This is an extension of built in runnable Eclipse code templates but can be very handy to quickly call both of these methods

${:import(javax.swing.SwingUtilities)}
SwingUtilities.invokeLater(new Runnable() {    
      @Override
      public void run() {
        ${cursor}
      }
    });
You can write similar Eclipse code template for invokeAndWait method as well. Remember to use  ${cursor} variable so that your code is created at right place.

4. Not null check

While writing defensive code, we frequently need to check if certain variable or Collection is not null or null in case you checking argument. You can generate Eclipse Code templates to write minimal code for this kind of situation.

if (${varName} != null) {
    ${cursor}:
}

Though this code template generates only few lines of code, It speed up whole coding process because of frequent uses. On the similar line you can create Eclipse Code templates for null check, size check, empty check etc.

5. JUnit Eclipse code templates

If you love to write JUnit test case, which you should, than you can use Eclipse code template to generate some boilerplate code there e.g. methods like before, after, beforeClass and afterClass. here is a sample Eclipse code template for one of such methods :

${:import (org.junit.Before)}

@Before
public void setUp() {
    ${cursor}
}

It not only uses static import to bring JUnit annotation but also makes it easy to write frequently used methods. You can similarly create Eclipse code templates for other JUnit method as well.

That's all on How to use Eclipse code templates to improve coding speed in Java. Eclipse code templates are extensive and it depends upon your creativity and need to create new templates. Good thing about Eclipse code templates is that you can export it as xml file and later import it to Eclipse.

This way you can easily backup and share your Eclipse code templates. 

Even if you don't create custom Eclipse code templates, get in habit of using built-in templates to increase coding speed in Java.

And lastly, let me know if you have used code templates in Eclipse before and what is your favorite code template in comments?

1 comment:

  1. Can you write the same article for IntelliJ IDEA? Do they also code block or any automatic code generation feature?

    ReplyDelete