Monday, April 15, 2013

Snippets in Eclipse

As programmers, we spend a significant portion of our day typing code that we've typed many times before. Sometimes large chunks of code - class definitions, try/catch blocks, trigger handlers, etc. Significant productivity can be gained by defining 'snippets' of commonly used code and pasting them with the click of a button. Eclipse has just such a mechanism - allowing you to define a parameterized snippet library.

The Snippet View

Navigate to Windows | Show View | Other... and select Snippets. I like to pin my snippet window to the right side of my screen, for easy access.

Right click in the view and choose Settings... to adjust things like font, layout, and auto-close options.

Your First Snippet

There are 2 methods for creating a snippet. First, you can paste a snippet from the clipboard. Just copy the code, right click in the Snippet View, and choose Paste As Snippet... Your second option is to simply select Customize... from the same menu. Either method will bring you to a window like the one below.
A pinned Snippet view


The pane on the left allows you to manage and organize your code snippets. You can also import and export them, which is handy for archiving or sharing coding standards across a team of developers.

Creating a Snippet

To create a new Snippet, click New, then New Item in the upper left corner of the window.

Give your item a name and description.

Paste or type your code into the 'Template:' box. If you don't add any variables, your snippet can be pasted directly into your code with a single double-click. That may be most efficient in some situations. But if you have recurring text (i.e. a class name) in your snippet, you may consider adding a variable, which can then be referenced and auto-populated within your snippet.

Inserting a Snippet

To insert your snippet, simply
  1. Place your cursor where you'd like the snippet inserted
  2. Double click on the snippet in Snippet View
  3. Add parameter values
  4. Click Insert
Don't forget to export your completed library and add it to source control.

Happy Coding!

2 comments:

  1. Is there any way to save all the category by one click? Not it's export one by one.

    ReplyDelete
    Replies
    1. To export all snippets in a category, right click in the snippet window, select 'Customize...', select the category in the pane on the left, then click the 'Export' button.

      Delete