IntelliJ IDEA 13.1.5 Update is Available

Even if you’re already waiting for IntelliJ IDEA 14 with its all new awesome features, you still might be glad to know that we’ve just released a fresh update for IntellIJ IDEA 13.1 packed with lots of important fixes.

Screen Shot 2014-09-29 at 22.19.31

If you’re running IntelliJ IDEA 13.1, then click “Check for updates” and install a patch. Otherwise go to the official website and download the new version from there.

Develop with Pleasure!

Posted in Releases | Tagged , | 12 Comments

The Inspection Connection – Issue #2

Boolean algebra can be difficult to reason about, which is why IntelliJ IDEA provides several inspections and intentions to simplify boolean expressions, improve readability and help make your code less prone to bugs. Here are just a few you may encounter while writing Java.

1. De Morgan’s Laws

De Morgan’s laws are (1) ¬a ∧ ¬b ≡ ¬(a ∨ b) and (2) ¬a ∨ ¬b ≡ ¬(a ∧ b). We can use these laws to transform boolean expressions programmatically, saving you the hassle of drawing a truth table to confirm your own good intuition.

By placing your cursor on line 2, then pressing Alt+Enter,w to select Replace ‘&&’ with ‘||’, IntelliJ IDEA will apply De Morgan’s first law, by first replacing conjunctions with disjunctions and negating the whole clause, leaving us:

As you can see, this may not always be the shortest or most natural form, so we can easily swap back and forth by between them by pressing Ctrl/Cmd+Z and Ctrl/Cmd+Shift+Z, or by repeating the inspection to apply De Morgan’s first law in reverse.

2. Rearranging control flow

IntelliJ IDEA provides two intentions for merging nested Ifs with conjunction and equivalent Ifs with disjunction, and two for separating them, via Split if and Extract if condition, respectively. For example, consider the following scenario:

By applying the first intention Merge nested ‘if’s, this can be reduced to:

Likewise, sequential ‘if’ conditions with identical bodies can be joined with disjunction.

By applying the second intention Merge sequential ‘if’s, this can be reduced to:

Now, if you want to break up a complex ‘if’ statement, you can place the cursor over a boolean expression, and apply the intention Extract if (…), where ‘…’ indicates the expression to be extracted.

Whichever disjunct your cursor is covering when the inspection is applied, that condition will be extracted into a new If statement and either nested inside the existing one or placed directly afterwards.

Keep in mind, if that if the condition contains a function call, this refactoring may alter the sequential structure of your program.

3. Flip Comparison

By reversing the traditional order of conditionals, Yoda notation claims two benefits: reducing null pointer errors and preventing accidental assignment. Many programmers follow this style in order to call attention to the boundary value:

However we can see that Yoda notation hides a null pointer that may potentially reappear later (in this case on line #4). The second motivation, that Yoda notation prevents ‘=’ where ‘==’ is intended, is demonstrated below.

In Java, there are very few cases where accidental assignment is also syntactically valid, and IntelliJ IDEA will detect those cases where assignments are used inside a condition. So we can safely swap Yoda conditions with the more traditional variation.

No matter which convention your code adopts, is important to use one consistently across your project. IntelliJ IDEA supports annotations for nullity inference, so the rationale behind Yoda notation in Java is less clear, but the choice is yours.

4. Avoiding negative conditionals

In Clean Code, Robert Martin writes, “Negatives are just a bit harder to understand than positives. So, when possible, conditionals should be expressed as positives.” (Martin, [G29]). IntelliJ IDEA has three inspections to help you stay positive.

When conditionals are negative, this is a good indication that control flow can be refactored. When refactoring your code, you should apply the intention Invert If Condition. Notice how De Morgan’s law is implicitly used to refactor this clause.

IntelliJ IDEA can detect when a boolean method is always inverted, giving you the opportunity to rename these functions. In order to trigger a global inspection like this one, you will need to explicitly run it. You can find this inspection under Analyze|Inspect Code.

This warning can be resolved by clicking “Invert method” on the right hand side of the Inspection Results Window, under “Problem resolution”. IntelliJ IDEA will prompt us to rename the method and then remove all negated invocations across the scope of the inspection.

isAlwaysInverted

Similarly, the inspection boolean variable is always inverted will help discover negated variables within a class, and IntelliJ IDEA 13+ offers an inspection for detecting negatively named boolean variables, like disabled, hidden, or isNotChanged. You can enable this inspection under Inspections|Data flow issues.

Posted in Tips & Tricks | 4 Comments

IntelliJ IDEA 14 Preview is Available!

Many of you, together with the IntelliJ IDEA team, have been waiting for this moment for some time: today we can finally reveal what we’ve been working on during the year to make your Java development even more of a pleasure. We’re extremely happy to announce that IntelliJ IDEA 14 is now available as a preview.

Everyone is welcome to download it and give the new features a try right away!

idea_logo

As always, IntellIJ IDEA 14 is better in every way: the UI, the editor, built-in developer tools, and coding assistance across all the supported frameworks. The major changes include: Continue reading

Posted in Beta Releases | Tagged | 3 Comments

Touring Plugins – Presentation Assist

When doing screencasts on IntelliJ IDEA or some of our other IDE’s, or giving live presentations, I usually use a very useful plugin which is called Presentation Assist.

What it does, once installed, is display on screen the keyboard combination that was just pressed.

highlight

The added benefit is that it provides keyboard combinations for one or two layouts. This can be really useful for those that are using different keyboard mappings. What’s even better is that the layouts and text displayed for alternative key presses can be configured, or even turned off

Configuration for Presentation Assist

Also, if doing presentations, note that there is actually a Presentation Mode in IntelliJ IDEA (View menu) which goes full screen and larger fonts.

Use while Pairing

You might wonder of course, what use is this for me if I’m not presenting or doing screencasts? Actually, this plugin is even more helpful when pairing with someone. Often times when I’m working with a colleague, I’m asked “Oh, what keyboard combination did you press just there?” or “What did you do to get that window?”. Having key presses show up on the screen answers most of these questions and helps us pick up shortcuts and more efficient ways of working with IntelliJ IDEA (or sister IDE’s).

One other tip in regard to pairing, don’t forget the Quick Switch Scheme (Ctrl+`) shortcut option, which allows us to quickly change keyboard mappings (and other things), something that is again very convenient when doing pair-programming or having to use someone else’s computer for a while.

keymap

Last but not least, and talking about presentations, if you’re at JavaOne 2014, don’t forget that we’ll be giving two talks, one on IntelliJ Tips and Tricks and another on building your own IDE. Hope to see you there!

Posted in Tips & Tricks | 1 Comment

IntelliJ IDEA 14 Ships Advanced Coding Assistance for Thymeleaf

If you’re using Thymeleaf (the coolest template engine for Java) in your project or just considering giving it a try, you’ll be excited to know that the latest EAP build of the upcoming IntelliJ IDEA 14 brings rich coding assistance for editing Thymeleaf templates.

The Thymeleaf support is enabled by default and includes Code Completion, Navigate to Declaration, Rename Refactoring, Find Usages, Highlight Usages, Code Analysis, and many other awesome features. Enjoy the demo:

IntelliJ IDEA 14 is still under heavy development, but the release date approaches very fast. That’s why we strongly encourage you to download the EAP build preview and share your feedback with us on our discussion forum or in the issue tracker.

Develop with pleasure, and spread the word!

Posted in New Features | Tagged , , | 9 Comments

Touring Plugins: Software Metrics

IntelliJ IDEA is a platform on to which most functionality is provided in the form of plugins. IntelliJ IDEA Ultimate has all the functionality our other IDEs have (with the exception of iOS/OSX-targeted functionality in AppCode). Each smaller IDE in turn is pretty much a cut-down tailored version of IntelliJ IDEA targeting a specific set of functionality. WebStorm for instance focuses on HTML, JavaScript, Node.js, etc. PhpStorm adds PHP to the mix.

In addition to all the built-in plugins by JetBrains, there are tons of other functionality and features available in the form of plugins. In fact, did you know that, as of writing this post, there are 1182 plugins available in our plugin repository? I’m sure there are even a few around the net that haven’t been published yet.

Plugins in the repository are categorized by functionality, although the easiest way to find something we’re looking for is to just search in free form text. For each entry we get information about the vendor, rating, number of downloads, etc.

IdeaVim

Starting with this issue, we’re going to look at some different plugins that are available. We’ll be focusing on plugins that aren’t bundled and active out of the box. We’ll look at the forgotten ones!

Also, remember that the easiest way to install plugins (and search for them) is via IntelliJ IDEA (or sister IDEs) directly, under Plugins. You can browse the JetBrains plugin repository or add custom ones.

Metrics Reloaded

Metrics Reloaded is a neat plugin that provides us with a wealth of metrics about our project. From cyclomatic complexity to class cohesion, it really offers good insight into our project structure. The plugin itself is OSS and the source code is available on GitHub.

metrics reloaded

Once installed, it provides us with a menu option under Analyze|Calculate Metrics. Metrics can be run for an entire project, a specific module, uncommitted files, current file, or a even a custom scope, making it extremely flexible in terms of what it is we want to analyze. It even provides us with the ability to filter out our tests.

In terms of the actual types of metrics, we can calculate:

  • Chidamber-Kemerer. Information on object coupling, inheritance depth, cohesion between methods (or thereof lack of), number of subclasses amongst other metrics introduced by Chidamber and Kemerer.
  • Class count. Provides information on the number of total classes, product classes, i.e. those that are not part of tests, and classes that are part of the testing code.
  • Dependency. Very detailed metrics on dependencies. It provides information about cyclic dependencies and transitive dependencies of classes, as well as dependents on each class.
  • Complexity. Details of cyclomatic complexity, essential complexity, and extended cyclomatic dependencies of methods.
  • JUnit Testing. Provide information on the number of JUnit test assertions and methods.
  • Javadoc Coverage. Simple count of the number of lines of Javadoc.
  • Lines of Code. Much like classes, it provides a total count of lines of code as well as production versus test code distribution.
  • MOOD. The six metrics under the MOOD umbrella, including Method Hiding factor, Attribute Inheritance, Method Hiding, Method Inheritance, and Polymorphism factor.
  • Martin Packaging. Refers to the series of metrics that Robert C. Martin a.k.a. Uncle Bob, mentions in his book Agile Software Development: Principles, Patterns and Practices. These metrics are mostly related to class and package coupling, providing information such as Afferent and Efferent couplings between classes, abstractness, instability and distance from main sequence. You can find more information about these metrics under Software package Metrics.

In addition to the built-in metrics, we can also define our own selection of metrics. By clicking the ellipsis next to the Metrics dropdown, we can access the Metric Profiles windows. This not only allows us to create custom metrics, but also to define the threshold values, which can then be used to only show values that pass a certain threshold. (By default, everything is shown although those passing threshold are marked in red.)

Metric Profiles

Here’s the output of running the Dependency metrics:

Output of metrics

If we right-click the columns, we’re also offered the option to see a Distribution Diagram or a Histogram of the values, a pie chart (where applicable), as well as learn more about the actual metrics collected.

Distribution

classes histogram

Histogram

distro chart

Pie Chart

pie chart

While the concept of metrics in software development is at times controversial, many of the statistics provided with this plugin are useful to the potential issues in the code, in an objective way.

To install it, just search for MetricsReloaded under the Browse Repositories option in the Plugins configuration.

Posted in Beta Releases | 2 Comments

The Inspection Connection – Issue #1

The release of JDK 8 has introduced a number of new language features into Java vernacular. In this issue of The Inspection Connection, we will examine eight useful inspections that IntelliJ IDEA provides to help you become more fluent in functional programming on Java 8, migrate your legacy code, detect bugs sooner, and develop with pleasure.

1. Anonymous type can be replaced with lambda

As a Java developer, you are probably familiar with anonymous classes, which declare and instantiate themselves all at once. These classes will either implement an interface or override functionality by extending another class. For years, IntelliJ IDEA has collapsed anonymous classes in order to make them easier to read. For example:

Now that Java 8 supports a feature called lambda notation, we can utilize this “folding” practice directly – once the compiler has seen the declaration, it knows the resulting type signature, so why bother with the ceremony of writing everything out? The solution here is very simple: our inputs come first, then a “goes to” or ->, followed by the statement block:

So this feature is available in different contexts: as a superficial folding rule, for language levels 7 and below, then as an inspection and intention for projects which have already migrated to Java 8. By default, IntelliJ IDEA will display anonymous classes as lambdas. On Java 8, you will be prompted to refactor them through the Quick Fix intention, as well as via the primary inspection.

2. Statement lambda can be replaced with expression lambda

Now lambda statements can be reduced even further in many cases. Brace yourselves, for braces are optional when the lambda body is a single expression. Java’s language designers have worked hard to help us do more with less – here expression lambdas are one result of their perseverance.

The above statement can be rewritten using an abbreviated expression lambda, in a similar manner to the way loops and control flow blocks may may opt to forgo enclosing a single-line body. Here is the above statement lambda, rewritten with this inspection:

This inspection can only be applied when the statement body invokes a single expression or void method. IntelliJ IDEA will detect and replace sites where statement lambdas can be reduced to expression lambdas, and suggest refactoring them with a Quick Fix.

3. Remove redundant types

When using lambda expressions in Java 8, you may choose to omit data types from the parameter list for the sake of brevity. In fact the formal parameter syntax is seldom used, since the declaration necessarily indicates the parameter type. Continuing our prior example:

Furthermore, parentheses are optional iff there is exactly one parameter. So this inspection will strip down any redundant type declarations, then peel off unnecessary parentheses from the parameter list, leaving us with the following concise expression.

So far, we have gone from a multi-line anonymous class to a single line lambda expression using the Function interface, which represents many of the new language patterns in Java 8. Now we will take the analogy one step further by introducing method references, the most succinct form of lambda expressions.

4. Lambda can be replaced with method reference

In a small but specific set of circumstances based on common usage patterns, lambdas may be replaced by method references, which are semantically equivalent to lambdas, but without any parameters. Instead, the parameter list is inferred based on an expected signature at the call site. As a result we can transform some expression lambdas to their equivalent method reference form, without any additional information.

The above line #2 can be rewritten using the Quick Fix inspection (which is enabled by default), by navigating to the highlighted region within your editor window, then pressing Alt+Enter when the lightbulb appears and selecting “Replace lambda with method reference”. This will result in a much cleaner version we see below.

However, even when the method reference is syntactically correct, this refactoring is not always appropriate, due to method overloading semantics in Java. IntelliJ IDEA does not suggest refactoring in these cases. Consider the following scenario:

While line #13 may pass our initial inspection, the method reference is semantically ambiguous, since it is unclear whether the author refers to the static method on line #6 or the arbitrary-object-particular-type instance method on line #2. So we can see how removing context from the call site can discard important lexical information, here, the overloading of Foo::bar.

5. Lambda parameter hides field (new in 13.1)

Like any field or method, lambda parameters can hide the visibility of homonymous fields in surrounding classes and superclasses. While field hiding may be deliberate, it is more likely an unintended side effect of refactoring that can turn into a serious bug. IntelliJ IDEA takes extra precautions to ensure they are not unintentional.

This inspection is not enabled under the default inspection profile, although it can be added under Settings -> Inspections -> Visibility Issues, by selecting “Lambda parameter hides field” under the default profile, or by using a custom profile, which can be configured to use any combination of these inspections for a custom application.

6. foreach loop can be collapsed with Stream API (new in 13.1)

In functional programming, recursion and composition are generally favored over loops and iteration, so in keeping with the functional design for Java 8, IntelliJ IDEA offers a dedicated inspection to unravel For-Each loops into a more functional style with the new Streams API found in JDK 1.8.

Now, we will apply this inspection to achieve the same result with the stream/filter pattern.

This inspection will transform the For-Each loop on our behalf, allowing us to rapidly refactor existing code. Notice how the filter condition is pared down to the compact expression lambda, and subsequent print statement is reduced to a method reference.

7. Interface may be annotated @FunctionalInterface (new in 13.1)

Java 8 introduces a new annotation that indicates when an interface type declaration is a functional interface, which are an important concept in Java 8 that have paved the way for lambda expressions. When is an interface a functional interface? You may have guessed the answer already.

A functional interface is an interface with exactly one abstract method, excluding those methods overridden from Object. If an interface has more than one abstract method or less than one abstract method, it is no longer a functional interface.

Should you forget when you may use the @FunctionalInterface annotation, IntelliJ IDEA will remind you. However, regardless of whether a functional interface is annotated by @FunctionalInterface, it will not be treated any differently by the compiler.

8. Abstract class may be interface (new in 14)

With the introduction of default methods in Java 8, longstanding sanctions on static methods from Interfaces have been relaxed, blurring some old lines between abstract classes and interfaces, and making it easier for us to share boilerplate and helper methods.

In many ways, it will now be simpler to convert abstract classes to interfaces, although this comes with several tradeoffs. There are a few important criteria that distinguish interfaces and abstract classes in Java 8, and these will influence your design choices in this area.

For language level 8 and above, IntelliJ IDEA will take now into consideration abstract classes with both static and non-static methods, allowing us to refactor them using the expanded interface definition. This inspection can be enabled under Settings -> Inspections -> Class Structure -> “Abstract class may be interface”. As a reminder, you can run any of these inspections individually by pressing Ctrl/Cmd+Alt+Shift+I.

With this, hopefully you have found some useful inspections and learned a few things about Java 8 along the way. If you are interested in learning more, one way to do this is by spending some time developing your own custom language inspections. Another way is by letting us know, so we can continue to deliver more educational content. Thank you for reading and develop with pleasure!

Posted in Tips & Tricks | Tagged , , , | 2 Comments

IntelliJ IDEA 14 EAP 138.2210 Brings Scratch Files and Better Mercurial Integration

Good news, everyone! Fresh IntelliJ IDEA 14 EAP build is released, bringing more goodies for you to check out.

First, the so called Scratch Files, a very handy feature that helps you experiment and prototype. With this feature you can sketch something really quick right in the editor, without modifying your project or creating any files.

You can open an infinite number of Scratch Files and easily switch between them. IntelliJ IDEA will provide all of its coding assistance features for these files according to the type you will select for them in a status bar widget.

scratch_demo

Continue reading

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

IntelliJ IDEA 13.1.5 RC is Out

We’re glad to announce that IntellIJ IDEA 13.1.5 RC is available. This EAP build brings you, among other fixes, the two important changes: creating new Grails projects and OS X 10.9.5 compatible application signature.

Hurry up to share your feedback on our discussion forum and report bugs to the issue tracker. If no critical problems are found, this build will become the IntellIJ IDEA 13.1.5 update.

Develop with Pleasure!

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

IntellIJ IDEA 14 Brings Better GWT’s Super Dev Mode Support

If you’re already using, or just considering the use of GWT in your projects, you’re going to be glad to know that IntellIJ IDEA 14 will feature significant improvements in this area, aimed to streamline development workflow.

First of all, running applications in Super Dev Mode doesn’t require you to start the application server and the code server separately: the IDE will do it for you. Also, applying changes to running applications happens without the use of bookmarklets, by simply clicking the compile button on the application page right in the web browser. These great features are made possible by the Sencha’s library that helps to operate in Super Dev Mode.

Debugger is also improved in a number of ways: the Source Maps support is fully leveraged; the GWT run configuration has an option to tell the IDE to start a JavaScript debugger session automatically.

Screen Shot 2014-09-09 at 13.48.56

We hope you’ll find these improvements useful. Your feedback as always is welcome, so don’t hesitate to share it in our discussion forum as well as report bugs directly to the issue tracker.

Develop with Pleasure!

Posted in New Features | Tagged , , | 3 Comments