Coding Snippets (Live Templates) in IntelliJ IDEA (OMG Java!)

Good evening folks!

This is somewhat of an experimental post. I’ve written this purely ‘in the heat of battle’, whilst I was trying to illustrate how to do this. A little bit of a departure from my usual posts; whereby I research a subject and then give you a condensed and refined product. Why did I do this? Just an interesting experiment in all honesty. On the subject of the word honest, this style of post is a chance to be authentic and more in the moment, even if I do trip up here and there and expose myself as the occasional fool; it’s a chance to see my internal monologue as I go about trying to learn something on the fly. I hope you enjoy…

I have an amazing, now completely out of control and rather feral, list of topics in my ‘to blog about’ list. Finding myself in the mood to be a ‘completionist’ however, I really should make something of this coding snippets mini-series and pack a few more of these in before I call it quits.

Today I’m looking at IntelliJ IDEA, a JetBrains IDE for coding in Java (and more than just that, if the tag line is anything to go by). This IDE has been selected out of the magic hat just because I wanted to go for something that I haven’t heard too much about before, rather than a name more frequently bandied about, such as the NetBeans IDE. This received a solid mention in Robert C. Martins ‘The Clean Coder’, which I’ve just finished digesting, so it seems most worthy of an intellectual punt!

Getting your hands on IntelliJ IDEA

To get mitts on this IDE is simple enough. I started by going here:

Choose your Edition

There you’ll find links to a Community and Ultimate edition (with Ultimate having a free, thirty-day trial). As I’m not doing a review per se on this software I won’t dig into the particulars of each edition too heavily. For anyone wondering what the different offerings entail you can navigate to the Compare Edition page and have a gander. What I will say is that language support beyond Java is most certainly a thing (.Net languages are out, as you may expect) and if you’re using Git you appear to be golden in relation to the Community edition; only Ultimate supports TFS.

Let’s get this install done and figure out a) how to write some Java and b) encapsulate something into a snippet.

Installing IntelliJ IDEA

Installing the product is, as you would expect, a next…next…next affair. I opted for the desktop shortcut (I have a messy desktop) and rigged it so that anything with a .java file extension would be associated with this IDE. On running the application you get prompted to import previous, custom settings. I’ve got none so an easy choice for me. After reading those pesky ‘policies’ (that we all read in minute detail of course!) you get, which is a nice touch, an opportunity to pick a theme (for those who know me, its dark themes all the way) and customise/install plugins. Again, I’m not really doing a review but I really liked the ease of the setup process here; being accustomed to Visual Studio for the main part I can often see times when (despite all of the functionality it does offer, I’m not bashing on it) it’s heavyweight nature does show through, not always for the best.

So, we’re ready to rock and roll; being presented with the following screen:

IntelliJ Start Screen.

IntelliJ Start Screen.

Making that Magic Coding Snippet!

Ok, so far, so good. I’m hoping that (although I’ve gazed at a fair bit of Java through my time) not having written a single line of Java is not going to be a ‘blocker’ to success ;-). The remit of this blog post is just to show how to create a code snippet, no matter how simple that is. Besides, I have read and digested the following books, so I’m feeling ready:

Googling the Error Message.

Googling the Error Message.

Copying and Pasting from Stack Overflow.

Copying and Pasting from Stack Overflow.

Create New Project seems like the way to go! I proceeded using the following tutorials by the way, should you wish to follow along:

IntelliJ IDEA Documentation

My first issue appeared to be the fact that I didn’t have the Software Development Kit installed (JDK in this instance), so I navigated here to grab one, for 64 bit Windows in my case:

JDK Downloads

Time for a cup of tea at this point; find a suitable beverage for yourself as you continue to read through, you’ve earned it by hanging on this long :-). On a side note, whoever bought me this mug needs to take a trip to the opticians. I do wonder if I could rock a twirled moustache too:

Someone needs an Optician.

Someone needs an Optician.

I downloaded and installed this package without any bother. Going back to create a new project again, I was able to (yes, I Stack Overflowed my way to glory here – I rather idiotically selected the ‘jre’ folder) hit New and navigate to the root JDK folder under my default Java install directory, as follows:

JDK Directory Selection in the IntelliJ IDEA.

JDK Directory Selection in the IntelliJ IDEA.

This brings me to a promising point on hitting next…I can make a command line application which, right now for me, is grade-a territory; that will do nicely thank you very much (I know where I stand with a Main() method after all):

Create a Command Line Application in IntelliJ.

Create a Command Line Application in IntelliJ.

After being nosey on Java rules of Package Naming, and naming my actual project, I was presented with this amazing sight:

IntelliJ Simple Command Line Application.

IntelliJ Simple Command Line Application.

As you can probably see the project name is ‘FizzBuzz’ related, so I’m going to write code to solve this classic problem and get a code snippet in along the way.

Ten minutes later I have this, which apart from questionable string handling, does the job I’m after (just needed to figure out how to print content to the output window and convert integers to string; refrained from googling here and just went on an IntelliSense rampage, which equals an ‘apologies if this is incorrect’). The output, without any unit tests to back it up, gives me expected ‘Fizz’ for multiples of three, ‘Buzz’ for multiples of five, ‘FizzBuzz’ for multiples of three and five, or just the number for everything else.

package lg.snippet.testing;

public class Main {

    public static void main(String[] args) {
        fizzBuzzerTest();
    }

    private static void fizzBuzzerTest() {
        for (int j = 1; j <= 100; j++) {
            System.out.println(evaluateInput(j));
        }
    }

    private static String evaluateInput(int fizzBuzzInput) {
        String fizzBuzzString = "";

        if (fizzBuzzInput % 3 == 0) {
            fizzBuzzString = "Fizz";
        }

        if (fizzBuzzInput % 5 == 0) {
            fizzBuzzString += "Buzz";
        }

        if (fizzBuzzString == "") {
            fizzBuzzString = Integer.toString(fizzBuzzInput);
        }

        return fizzBuzzString;
    }
}
FizzBuzz Command Line Output.

FizzBuzz Command Line Output.

That’s the best piece of Java I will fashion today, happy for it to be ripped to shreds by all the experts out there.

So, although this has been somewhat of a ramble, we are now ready to fashion a code snippet. I’m going to make the snippet encapsulate the fizzBuzzerTest method and supporting evaluateInput method, as a complete package that can be dropped anywhere. The way this is achieved, after a little research, is via Live Templates.

To get started, navigate to File > Settings and select the Live Templates section under Editor. In this next screenshot, I’m creating a new custom Template Group to act as a repository for my own weird and wonderful snippets:

Live Template Options.

Live Template Options.

After creating the custom template group you can repeat the process (with the new group highlighted) to add a new Live Template. The template itself has a few configuration options that need to have valid settings before you can proceed. Firstly, define what ‘contexts’ this Live Template can operate within; for the purposes of this little example only Java is applicable:

Defining the Live Template Context.

Defining the Live Template Context.

I gave my Live Template an abbreviation (allowing easy accessing from the editor), a Description (the one you’ll see in this screen shot I amend before saving, as it was blooming terrible!) as well as the actual code that defines the template. I’ve placed the variable COUNT into my template, which allows the template user to switch out the value when the template is brought into scope (with a default value as shown here; the dialog for managing this being accessible via the Edit Variables button). Variables must be wrapped in ‘$’ symbols and default literals must be wrapped in double quotes in order for this to work (another google-fest here!):

Completing the Live Template Definition.

Completing the Live Template Definition.

Remit basically complete…we’ve done snippets (well, Live Templates) in Java via IntelliJ IDEA! The next two screen shots show the template in use, achieved by hitting tab to generate the snippet after typing the abbreviation. We are also illustrating the place holder for the COUNT variable being editable. The variables can be tabbed through, as you would expect, for fast template completion:

Before Live Template Usage.

Before Live Template Usage.

After Live Template Usage.

After Live Template Usage.

There’s our random walkabout of IntelliJ IDEA and Live Templates done and dusted, mission complete. Cheers all, until the next time happy coding!