IntelliJ IDEA 2016.2.1 Update Available

Just a month after the release, it’s time for a fresh minor update. Please welcome IntelliJ IDEA 2016.2.1, with important fixes made based on your feedback.

To update, either download the new version from our website or, if you’re running IntelliJ IDEA 2016.2, install the patch by clicking Check for Updates and then Download and Update.

To learn more about IntelliJ IDEA 2016.2, read the corresponding blog post.

Develop with Pleasure!

Posted in Releases | Tagged , , | 16 Comments

Using JUnit 5 in IntelliJ IDEA

One of the new features in IntelliJ IDEA 2016.2 is support for the new JUnit 5 testing framework.  Almost all Java developers will have used JUnit at some point, so it’s pretty exciting to find the newest version has evolved with the times and provides a number of new features, some of which may be familiar to those who have used other frameworks.

IntelliJ IDEA supports the ability to actually run tests written for JUnit 5 – there’s no need to use the additional libraries (like the Gradle or Maven plugins for example), all you need is to include the JUnit 5 dependency. Here we’re using Gradle to include the dependency to the M2 version:

Setting up dependencies

Once you’ve done this, you can start writing tests that use the new annotations:

Simple JUnit 5 test

Running these tests will give you familiar-looking results in the IntelliJ IDEA run window:

JUnit 5 test results

You’ll notice JUnit Jupiter is the test engine for the new JUnit tests, and that you can run both new and old tests.

At first glance, the new JUnit 5 tests are no different to JUnit 4 ones, other than the annotations being imported from a different package, and showing two types of runner on the results.

But JUnit 5 comes with some new features, such as the ability to add a readable name or description for the test, so you no longer have to rely on a method name, using @DisplayName:

Using @DisplayName

You can group assertions so that all assertions are run, regardless of whether one (or more) fails, giving you better visibility over the true state of a failure:

Grouping assertions

And you can use the @Nested annotation, so you can write BDD-style tests or group the tests in a class by some dimension:

Running @Nested tests

JUnit 5 also has a new way of handling expected Exceptions, by letting you assert specific Exceptions are thrown

JUnit 5 can expect exceptions

And you can even get the thrown Exception to check for further details:

Inspect Exception

These are just some of the features available to use in JUnit 5, and IntelliJ’s support for the new framework is also evolving.

If you think JUnit 5 looks interesting, download IntelliJ IDEA 2016.2 and take a look at:

And, of course, you can check out more of the features available in IntelliJ IDEA 2016.2.

Posted in New Features | Tagged , , , | 6 Comments

What’s New in IntelliJ IDEA 2016.2 for Spring Developers

If you’re a heavy user of Spring and IntelliJ IDEA, you’ll find the IntelliJ IDEA 2016.2 update very interesting. Besides many important bugfixes, the update adds support for Spring 4.3 and Spring Security 4.0 features and cache abstraction, improves support for Spring MVC, and further tunes performance. Before reading about this in more detail, make sure you’ve registered for our webinar dedicated to the new release and Spring framework.

OK, now back to the update. First of all, the IDE now supports generics types as qualifiers and provides navigation for them:

Also, the IDE now supports custom @EventListener annotations defined with @AliasFor and enables coding assistance for editing SpEL:

The new inspection helps replace field injection with constructor injection:

The IDE now supports Spring Cache abstraction: CacheResolver, CacheManager, KeyGenerator, @Cachable, @PutCache, @EvictCache, etc. The support includes code completion, navigation, inspections and syntax highlighting.

The icon on the gutter (the narrow panel on the right-hand side of the editor) lets you navigate to other methods annotated with cache operations related to the same name:

A dedicated inspection checks if a cache name is provided for all cache-related operations:

If you use a @Cachable annotation on an interface or, e.g. put @Cachable and @CachePut on the same method, you’ll see a warning.

And of course, the IDE provides coding assistance for editing SpEl:

In FreeMarker and Velocity templates, you’ll get code completion and navigation for variables defined in Spring MVC controllers:

Also, the update has supported the changes introduced with Spring Security 4.0 and added code completion and navigation for SpEl in annotations and inside XML:

And last but not least, we’ve added highlighting and navigation for Spring-related messages in Console.

Found this interesting? Download the update and give it a try right away.

P.S. Oh, and we’re going to SpringOne Platform event in the beautiful Las Vegas. If you also plan to attend, come and listen to the Tips and Tricks for Spring in IntelliJ IDEA talk, by Yann Cébron and Stéphane Nicoll!

 

Develop with Pleasure!

Posted in New Features | Tagged , , | 1 Comment

Java 8 Top Tips

I’ve been working a lot with Java 8 code over the last couple of years, for both new applications and migrating existing ones, and it feels like the right time to write down some of the “best practices” I’ve found useful. I personally dislike the term “best practices” as it implies a “one size fits all” solution, and of course coding doesn’t work that way – it’s down to us as developers to figure out what will work in our situation. But I have discovered I have particular preferences for Java 8 code that I find makes my life a little easier, and I thought I’d start a discussion on this topic.

Optional

Optional is a highly underrated feature, and one that has the potential to remove a lot of those NullPointerExceptions that can plague us. It’s particularly useful at the boundaries of code (either APIs you’re using or APIs you’re exposing) as it allows you and your calling code to reason about what to expect.

However, applying it without some thought and design can lead to one small change impacting a large number of classes, and can lead to poorer readability. Here are some tips on how to use Optional effectively.

Optional should only be used for return types
…not parameters and not fields. Read this blog post to see a pragmatic approach to using Optional. Fortunately, IntelliJ IDEA lets you turn on an inspection to check you’re following these recommendations

Optional Parameter Warning

Optional values should be dealt with in the place they’re encountered.  IntelliJ IDEA’s suggestions will prevent Optional leaking all over your code, so remember you should deal with Optional where you found it and move swiftly on.

Deal with Optional immediately

You should not simply call get()
The strength of Optional is to express that this value might be empty, and allow you to cater for that case. Therefore, it’s important to check if there is a value before doing anything with it.  Simply calling get() without checking isPresent() first is likely to lead to a null pointer at some point. Fortunately, once again IntelliJ IDEA has an inspection to warn you to stick to this.

Get without isPresent

There is probably a more elegant way
The isPresent() combined with get() certainly does the trick…

Simplest use of Optional

…but there are more elegant solutions. You can use orElse to give an alternative value in the case that it’s null

Using Optional orElse

…or you can use orElseGet to tell it which method to call in the case that the value is null. This might seem the same as the above example, but the supplier method will be called only if needed, so if it’s an expensive method, using the lambda will give you better performance.

Using Optional orElseGet

Using Lambda Expressions

Lambda expressions were one of the main selling points of Java 8.  Even if you’re not using Java 8 yet, you’ve probably got basic understanding of them by now. But they are a new way of programming within Java, and it’s not yet obvious what is “best practice”. Here are some guidelines I like to follow.

Keep it Short
Functional programmers may be happy with longer lambda expressions, but those of us who’ve been using only Java for many years might find it easier to keep lambda expressions to a small number of lines. You might even prefer to limit them to just a single line, and you can easily refactor longer expressions into a method.

Extract longer lambda expressions into methods

These may even collapse down into method references. Method references may seem a bit alien at first, but it’s worth persevering with them as they can actually aid readability in some cases, which I’ll talk about later.

Collapse Lambda to Method Reference

Be Explicit
Type information is missing for lambda expressions, so you may find it useful to include the type information for the parameter.

Explicit parameter types for lambda expressionsAs you can see, this can get quite unwieldy.  So I prefer to give my parameters a useful name. Of course, whether you do this or not, IntelliJ IDEA lets you see type information of parameters.

See the parameter types of the lambda

and even the Functional Interface the lambda represents

See the lambda's functional interface

Designing for Lambda Expressions

I think of lambda expressions as being a little like Generics – with Generics, we use them regularly (for example, adding type information to List<> ), but it’s much more rare that we’ll design a method or a class that has a Generic type (like a Person<T>). Similarly, it feels like we’ll pass lambdas around when using things like the Streams API, but it’ll be much more rare for us to create a method that requires a lambda parameter.

However, if you do find yourself in this situation, here are some top tips.

IntelliJ IDEA can help you introduce a functional parameter
This lets you create a parameter where someone will pass in a lambda rather than an Object. The nice thing about this feature is that it suggests an existing functional interface that matches the specification.

Extract functional parameter

Which leads to…

Use existing functional interfaces
As developers become more familiar with Java 8 code, we’ll know what to expect when using interfaces like Supplier and Consumer, and creating a home-grown ErrorMessageCreator (for example) could be confusing, and wasteful. Take a look at the function package to see what’s already available.

Add @FunctionalInterface to your functional interface
If you really do need to create your own functional interface, then tag it as such with this annotation.  It might not seem to do much, but IntelliJ IDEA will show you if your interface doesn’t match the exceptions for a functional interface. It flags when you haven’t specified a method to override:

Functional interface without a method

it flags when you’ve specified too many:

Functional interface with too many methods

and it warns you if you’ve applied it to a class rather than an interface:

Functional interface that's actually a class

Lambda expressions can be used for any interface with a Single Abstract Method, but they can’t be used for abstract classes that meet the same criteria.  Seems illogical, but it is what it is.

Streams

The Stream API is another one of the big selling points of Java 8, and I think we still don’t really know how much this is going to change (or not) the way we code. Here’s a mixed bag of things I’ve found useful.

Line up the dots
I personally prefer to line up my stream operations. You don’t have to, of course, but I’ve found this helps me:

  • see which operations I have, in order, at a glance
  • debug more easily (although IntelliJ IDEA does offer the ability to set breakpoints on any of multiple lambda expressions on a line, splitting them onto separate lines does make it simpler)
  • comment out an operation while I’m testing things
  • easily insert a peek() for debugging / testing

Line up your dots

Also it’s neater, in my opinion. But we don’t gain a lot in terms of reducing lines of code if we follow this pattern.

You may need to adjust your formatting settings to get the dots lined up.

Formatting Stream method chaining

Use Method References
Yes, it does take a while to get used to this weird syntax. But when used correctly, it really adds to the readability. Consider

Stream using a simple logical filter

verses the use of the helper methods on the (fairly) new Objects class:

Stream with method reference

This latter code is much more explicit about which values it wants to keep.  IntelliJ IDEA will usually let you know when a lambda can be collapsed to a method reference.

Use method reference instead of lambda expression

When iterating over a Collection, use the Streams API where possible
…or the new collections methods like forEach.  IntelliJ IDEA can suggest this to you:

Replace iteration with forEach

Generally using the Streams API is more explicit than a combination of for loops and if statements.  For example:

Using traditional iteration

IntelliJ IDEA suggests this can be refactored to:

Using the Streams API

The performance tests I’ve done show that this sort of refactoring can be surprising – it’s not always predictable whether performance will stay the same, improve, or get worse. As always, if performance is critical in your application, measure it before committing to one style over another.

Use for loops when looping over arrays
However, using Java 8 doesn’t necessarily mean you have to use streams and new collections methods everywhere. IntelliJ IDEA will suggest things that can be converted to streams, but that doesn’t mean you have to say “yes” (remember inspections can be suppressed or turned off).

In particular, iterating over a small array of primitive types is almost definitely going to be better performance with a for loop, and probably (at least while Java developers are new to streams) more readable.

For loops are faster over arrays

As with any of the tips, this rule is not set in stone, but you should decide whether you are going to prefer using the Streams API where you can, or whether you’re still going to use loops for some operations.  Above all, be consistent.

Finally

I’ve written a similar but complimentary post on this topic for the Upsource blog, containing these tips and more things to look out for in Java 8 code when you’re performing a code review.

I’m discovering new things every day, and sometimes my preferences change – method references, for example, I used to hate, and avoided having them in my code. I’d love to hear your top tips!

Posted in Tips & Tricks | Tagged , | 26 Comments

IntelliJ IDEA 2016.2.1 EAP updates Kotlin support to 1.0.3

Great news! IntelliJ IDEA 2016.2.1 is on the horizon. You’re welcome to give its first EAP build a try. In addition to the usual dose of bugfixes, this EAP build updates the bundled Kotlin plugin version to 1.0.3. Here’s a little more insight into what it brings you.

If you’ve ever pasted Java code into a Kotlin file, you’ve probably noticed that IntelliJ IDEA offers to automatically convert it to Kotlin. However, this used to work only if the code was copied from inside the IDE. Now it works no matter where you got the code, even if it is a StackOverflow page.

Code completion for Kotlin also got better. IntelliJ IDEA suggests non-imported members and adds an import statement automatically on selection. Smart Completion is available after by and in statements.

The Move Element Left/Right actions, which were added earlier for Java, now work for Kotlin.

And finally, the Kotlin Bytecode tool window now has a Decompile button.

For more details read the announcement in the Kotlin blog.

As always, we appreciate your feedback here in the comments as well as in our issue tracker.

Develop with Pleasure!

Posted in EAP Releases, New Features | Tagged , , , | 1 Comment

Live Webinar: What’s New in IntelliJ IDEA 2016.2

We hope you’ve already tried IntelliJ IDEA 2016.2 which we released earlier this week. Even if you haven’t, we’re offering a deeper insight into its new features Wednesday, July 27th, 12:00 PM – 1:00 PM EDT (New York) / 18:00 – 19:00 CEST (Berlin) (check other time zones) during a live webinar What’s New in IntelliJ IDEA 2016.2, featuring Trisha Gee.

intellij_idea_webinar_2016_2

In this webinar Trisha will give you an overview of the most important changes of 2016.2 and, of course, will answer your questions.

Register now!

Speaking to you

Trisha GeeTrisha has developed Java applications for a range of industries, including finance, manufacturing and non-profit, for companies of all sizes. She has expertise in Java high performance systems, is passionate about enabling developer productivity, and dabbles with Open Source development. You can follow her on Twitter – @trisha_gee


The Drive to Develop

Posted in Webinars | Tagged , | Leave a comment

Java Annotated Monthly – July: Java Tools and Technologies

Whether you like to branch out into other JVM languages, or prefer to get deep knowledge in “classic” Java, there’s always more to learn in our Java-flavoured world.  This issue aims to give you some summer holiday reading. But the most exciting news this month is a double-whammy: IntelliJ IDEA is the top IDE, according to the latest Developer Productivity Report, and we have a new version of IntelliJ IDEA!

JavaAnnotatedMonthly@2x

Continue reading

Posted in News & Events | Tagged | 5 Comments

IntelliJ IDEA 2016.2 is Here!

The last four months passed quickly, yet they were very productive. Today we give you IntelliJ IDEA 2016.2, our second update in the series of this year’s releases. As usual, it brings both useful new features and important fixes. Read on to learn what kept us busy and download the update to try all of its new features without any further ado.

IntelliJIDEAult_splash20162@2x

Continue reading

Posted in New Features, Releases | Tagged , | 87 Comments

IntelliJ IDEA 2016.2 RC is Out

Time flies! The IDE update planned for this summer is now a matter of days. Today’s good news is that we’ve published its first RC build. You’re very welcome to download it and give a thorough try to all of its new features.

We appreciate your feedback on bugs and other flaws you may find in the build. Report them without hesitation to our issue tracker.

Develop with Pleasure!

Posted in EAP Releases, Release Candidates | Tagged , | 2 Comments

IntelliJ IDEA 2016.2 EAP Adds Breadcrumb for Java

Fresh IntelliJ IEA 2016.2 EAP build is out and ready. Among the usual bugfixes it also brings something special: Breadcrumbs for Java code.

Until now breadcrumbs were only available in HTML and XML code, where they have proven to be super handy for tracking of the editing position as well as traversing the tag tree. Now breadcrumbs work for Java, too, where instead of tags they let you navigate through classes, lambda expressions and methods:

To enable this feature, go to SettingsEditor → General → Appearance and select Show breadcrumbs.

Your thoughts and impressions about this and any other changes are very welcome here in the comments, and, of course, in our issue tracker.

Develop with Pleasure!

Posted in EAP Releases, New Features | Tagged , | 18 Comments