Many, many tools perform static analysis on code. There are all sorts of automated ways to look through your code and tell you if there are likely errors or not. FindBugs, PMD, and CheckStyle are some of the big names from the Java world. On the Groovy side we have two real options: IntelliJ IDEA and CodeNarc.

This post highlights my favorite static analysis rules for Groovy in IDEA that are not enabled by default. Groovy in IDEA 11 has well over 100 rules, but less than half of them are activated when you install the product. To turn these rules on you’ll need to go into Settings (Ctrl+Alt+S) and enable them under Inspections.

So here are my favorites that I think you should turn on:

Threading
Threading comes first because these inspections have saved my butt in the past. None of them are enabled by default, so do yourself a favor and enable a few. These ones are all must haves:

* Access to static field locked on instance data – Reading and writing a static field from multiple threads is not thread-safe. It needs to be done within a synchronized block. Do you know what happens when you synchronize on instance data, like this:

Java

1

2

3

4

5

6

7

8

9

10

classMyClass{

staticresource

finallock=newObject()

def initialize(){

synchronized(lock){

resource=newResource()

}

}

}

The object ‘lock’ is an instance field, not a static field. So this assignment within the synchronized block is not thread-safe. It is possible that the static field is accessed from multiple threads, which can lead to unspecified side effects.

* Synchronization on non-final field – If you are accessing a variable within a synchronized block then your synchronization token must be final. Consider this code:

Java

1

2

3

4

5

6

7

8

9

10

classMyClass{

def resource

def lock=newObject()

def initialize(){

synchronized(lock){

resource=newResource()

}

}

}

The field ‘lock’ is not final, so different instances of MyClass may have different values for lock. The result is that different threads may be locking on different objects even when operating on the same object. Make your locks final.

* Synchronization on variable initialized with literal – Do you understand the problem with synchronizing on a primitive literal? Consider this code:

Java

1

2

3

4

5

6

7

8

9

classMyClass{

def lock='my lock'

def initialize(){

synchronized(lock){

// do something

}

}

}

Strings are interned by the JVM, so the string ‘my lock’ may also be used by another class. Numbers are even worse because they can be assigned from a cache. Some other object in the system may be initialized with the same literal, and could create an accidental (or malicious) dead-lock situations.

* Unsynchronized method overrides synchronized method – In some limited circumstances you may actually want to override a synchronized method with an unsynchronized one. But probably not. More than likely you don’t even know and you are accidentally creating a subtle bug. If the parent is synchronized then the child should be also. Or better yet, make the parent final.

Probably bugs
* Named arguments of constructor call – This inspection warns you when something like the following happens when using named arguments, which is almost certainly a bug:

Java

1

2

3

4

5

classOrder{

intorderId

}

newOrder(orderid:5)

See the problem? The field is named ‘orderId’ with a big ‘I’ and the constructor call uses ‘orderid’ with a small ‘i’. RuntimeException if you run this code. This is a type of bug that CodeNarc cannot find because the type information of the classes is so limited. IDEA keeps track of types much better and can do nice things like this.

* Access to unresolved expression – There has been a lot of talk over the years about adding static compilation to Groovy. Some people want to be warned by the compiler or in the IDE if their Groovy code is referencing an object that does not exist. For example, they’d like this to produce a warning or error:

Java

1

2

3

defc={parm->

println it

}

See the problem? The closure parameter is named ‘parm’ but the closure references the parameter by the standard name ‘it’. The access to unresolved expression inspection turns this into a warning or error in the IDE. IDEA is quite smart about it too and knows all about delegate/super and the other Groovy dynamic variables. If you like this sort of thing then be sure to read up on Grumpy mode in Groovy 2, coming soon.

Control Flow
There are many features in Groovy that simplify standard and verbose Java code. Two of these are the Elvis operator and the Null-Safe Dereference. IDEA contains inspections to help you migrate to the new way of writing code with these features.

* Conditional expression can be elvis – This inspection migrates you from code like this:

Java

1

defx=value!=null?value:2

And suggests you rewrite it into the equivalent Groovy:

Java

1

defx=value?:2

Is it always safe to make this transformation? (Think about it for a few seconds). GroovyTruth means it is not. Technically speaking, the two code snippets are not equivalent: value != null may be true while value is false, such as when value is an empty String. Overall, I like the inspection but you need to be careful with it.

* Conditional expression can be conditional call – This inspection promotes the use of the Null-Safe dereference. This following code produces a violation:

Java

1

defx=value!=null?value.toString():null

… and you will be prompted to transform it ito:

Java

1

defx=value?.toString()

These two code blocks really are the same and this can be safely accepted as the correct way to write the code.

* If statement (or conditional) with identical branches – I periodically refactor code and accidentally leave an if or conditional statement with identical branches. These are of course redundant and can be cleaned up by removing the if expression. If you have good unit tests and use automated refactorings then this sort of things happens from time to time. The cleanup reminder is nice.

What happens to the stack trace in this scenario? It gets eaten up, never to appear in a log. You shouldn’t have any unused catch parameters. If you really don’t care about the exception then name it ‘ignore’ or ‘ignored’ to suppress the warning.

Validity issues
* Duplicate switch case – Groovy has Switch on Steroids, meaning you can put almost any object in the case statement, including regular expressions:

Java

1

2

3

4

switch(input){

case~/[0-9]/:println'numeric!';break

case~/[0-9]/:println'a number';break

}

See the problem? The same regex appears twice. The second case will never be executed, even if it would match. As long as your case statements have literals in them then IDEA can verify that there are no duplicates.

Naming Conventions
Lastly, there are a whole bunch of naming convention inspections that you can activate and configure. If you’re not using CodeNarc (why not?) then you should at least activate some of these. Standards, on a whole, are good to adhere to.

IDEA Inspections of CodeNarc?
So which should you use, IDEA or CodeNarc? These two tools complement each other. There is good reason to use both CodeNarc and IDEA together. CodeNarc does have more inspections than IDEA, but the IDE integration in IDEA is better. Pressing Alt+Enter typically rewrites the offending code, and the speed of the actions are much better in IDEA. Also, the static analysis rules do not overlap between the products because the CodeNarc developers (that’s Chris Mair and myself) already use IDEA and made a conscious effort not to duplicate anything.

Google’s Android site has some fairly detailed instructions for testing Android applications… from Eclipse. They were nice enough to supply a “Testing from Other IDEs” page, but that is nothing more than instructions on using Ant and the command line. Well, if you are using IntelliJ IDEA then you already believe the IDE is going to be a better tool than Ant for this. It’s easy to set up a test project in IDEA and get your tests running. Here are some simple instructions.

Your Android tests are going to be placed in a separate module from your main Android application. Remember: an IDEA project is composed of several modules. We’re going to have the main application module and the test module. Each module has it’s own set of dependencies and classpath. (Eclipse users confused about the terminology should read this). Here are the steps to follow to set up a test project:

1. Have your main project open in IDEA
2. Create a new module using the menu File->New Module
3. Select “Create module from scratch” and click Next
4. Select “Android Module”, give the module a new name, and click Next. You should put the module in a directory called “tests” that is in your project root. That way your project will follow the same naming conventions that Ant expects, making the project easier to set up in a CI server later. Here is what your wizard screen might look like:

Adding an Android Testing Module

5. On the next wizard step just click Next to create a source directory for your files.
6. Finally, on the last wizard step select “Test” under Project properties. Make sure it is going to test your module. Then Finish.

Select Test as Project Type

At this point your two modules exist: the production module and your test module. If you look in the Project View (Alt+1) you will see both modules. Mine are named “android-testing-in-idea” and “tests”. You’ll even be given a template test for your main activity. It’s pretty slim so you will certainly want to write some of your own tests. IDEA isn’t smart enough to automatically create the test content for you… at least yet.

Running Tests

Running tests is simple. A run configuration to run all tests was created for you when you added the project. Click the ‘run triangle’ to run the tests or the ‘bug triangle’ to debug the tests. You’ll be prompted to select an emulator if you don’t have one set by default.

Click to Run All Tests

There are other ways to run tests at a more granular level, too. To run all the tests in a package, right click the package and select Run (Ctrl+Shift+F10). To run all the tests in a class, right click the class and select Run (Ctrl+Shift+F10). You can also run individual test methods one at a time. Just right click inside the test method within the IDE editor and select Run (once again, (Ctrl+Shift+F10)).

You may want to switch the emulator version from time to time in order to test across multiple devices. You can bring up the Run Configuration from the drop down menu highlighted in the screenshot above. It opens a screen like this where you configure the run target:

Configure the Test Run Target

You can switch the emulator here to a different version. Be sure to check out the other tabs as well. The Emulator tab allows you to configure the network speed and latency, and the Logcat tabs lets you configure one or two things about Logcat. Handy.

Viewing Results

So you want to view the test results? Well results window probably popped up on screen after you ran the test. Anyway, if you’re still confused you can click the Run (Alt+4) or Debug (Alt+5) drawer and see the JUnit results. There is also a Logcat drawer to click (sorry no shortcut) to view the logs.

Viewing Test Results

Other Tools

The last thing you need to know is a little about the other tools. You can manage your emulator ROMs using the AVD Manager. The menu option for that is Tools -> Android -> AVD Manager. Also, you can change the project compatibility to be a different version of Android OS. It’s under File->Project Structure (Ctrl+Alt+Shift+S) then click Module SDK. Finally, if you want to set the project up for continuous integration then head on back to the Ant command line guide from Google. It’s best not to have the IDEA project file drive your builds.

You made it to the end. Thanks for reading! And remember, Canoo is here to help with your Android and Mobile needs. Email me directly (hamlet.darcy@canoo.com) or give us a phone call. Thanks.

Earlier this month I switched from writing my Android projects in Eclipse to writing them in IntelliJ IDEA. Overall the experience has been great, and I much prefer using IDEA to Eclipse for Android development. And now that IntelliJ IDEA 11 EAP (Early Access) has a visual layout window, there is almost no reason for me to write my Android apps in anything else. I wrote this post to help other users along their way when converting between the IDEs.

Why IntelliJ IDEA for Android?

There’s no need to ask why if IDEA is already your favorite IDE or if your company is forcing you to use it. But just in case you’re not already a raving fanboy, here are some of the features specific to Android that made me want to switch.

Find usages (Alt+F7) is aware of Android XML resources (and the semantic meaning of their content), so searching across project assets is easier. Plus, I just find IDEA’s search capabilities a little saner than Eclipse’s. Below you can see what happens when I search from within my layout XML file for a certain widget ID:

Find Usages in IDEA

Because IDEA knows about the Android XML resources, refactorings like Rename (Shift+F6) work across Java code and XML. You can rename a widget’s ID from the XML file and have the Java code updated, or rename from the Java code and have the XML updated. Here I am renaming a widget ID in XML. Nice. In general, I do not search within comments and Strings because it is a little too aggressive.

02. Rename Refactor

There are several Android specific intentions that make life easier in IDEA. Intentions are the quick-fixes that are activated in Eclipse with Ctrl+1. In IDEA you use Alt+Enter. For example, if there is a static String referenced from your code then you should make that String a resource by moving it to strings.xml. Put your cursor into the String, press Alt+Enter, accept the name suggestion, and you’re ready to go. Ctrl+Z for undo on refactorings work great, too. One of the big differences between IDEA and Eclipse is refactoring support. In IDEA, the source files do not need to compile in order for refactorings to work. It is quite common to have a broken file and fix it through a couple automated renames or refactors.

03. Move Refactor

Finally, before IDEA 11, the killer feature for Eclipse Android was the visual editor for XML based layout files. Personally, I don’t often use drag and drop layout editors but I do value seeing my code changes immediately without recompiling and redeploying. Eclipse had the better feature set. But IDEA 11 now has a layout “Preview” mode. Make a change in the XML and see it immediately updated in the preview. You can also quickly change the theme, preview in landscape and portrait, switch to night mode, and select different screen sizes. If you absolutely need a visual editor, then Eclipse is the way to go. Otherwise, the Preview in IDEA 11 is good enough. More info available on the IDEA blog.

04. Visual Preview

Let’s get started with a tour of IDEA.

Getting Oriented in IDEA

The basic layout of IDEA is not all that different from Eclipse. You have a main code window (right, in image below), you have a Project View (upper left), and you have a Structure View (lower left). If there is a window for it in Eclipse, then there is probably a window for it in IDEA. A good way to get started and get familiar with IDEA is to read the DZone IDEA RefCard I wrote a few years ago. It is still relevant today. I highlighted the image to show the relevant details.

05. Project View

At any time you can jump to the code window by pressing Escape, and you can close any open tool window with Shift+Escape. On thing that IDEA does not have is perspectives. Maybe you love Eclipse perspectives. Maybe you love when your code view shrinks up into a postage sized porthole whenever you launch a debugger. Who knows, perhaps this is useful to you somehow. I am trying very hard to be positive here, and the nicest thing I have to say about perspectives is that I hate them. Another thing IDEA does not have is a “Team Plugin”. There is no single “Team” abstraction that somehow fits on top of every version control system. Instead, when you enable Subversion then you use Subversion features. Git uses Git Features. Version control systems are enabled using the Tools->Enable Version Control menu item. Then the Alt+9 shortcut brings up the Version Control View.

Running, Debugging, and the Android Tools

Running and Debugging an application is slightly different in IDEA than in Eclipse. You manage your “Run Configurations” using your Run/Debug dropdown menu at the top of the screen:

06. Run/Debug Configurations

You can create temporary and permanent run configurations. Right clicking a test and choosing Run creates a temporary run config. If you want to run the target repeatedly then just save it so it is permanent. And you Maven users: you can right click a goal in the Maven view and create a run target, such as a run:jetty goal. The Maven support is amazing in IDEA, so you are actually lucky to be a Maven user in this case.

The features of the debuggers are fairly close between the two products. Set a break point by clicking in the gutter (Ctrl+F8), select and right click a reference to add to the watch window. I’ve noticed that Eclipse users love to enable and disable breakpoints rather than just set and remove them. Well, you can press Ctrl+Shift+F8 to manage all your breakpoints if that’s the sort of thing you like to do. Also, notice the Logcat tab on the debugger, which shows you the Android log. If you are Running (and not debugging), then the Logcat output is in the “Android Logcat” view that you see on the bottom toolbar:

07. Debug Window

The main Android Tools from the SDK are available under the Tools->Android menu. You can export a signed package this way and also launch the AVD to manage your emulators and environments. If you need the other SDK tools like “hierarchyviewer” or “monkeyrunner” then you’ll have to launch them from the command line. There is built-in Android testing support in IDEA, and when you run a unit test then the IDE will ask you whether to run it as a JUnit test or an Android test. It remembers your answer, so if you make a mistake then just delete the run configuration and start over. It will ask you again.

Managing Your IDEA Project

The two hardest parts of switching IDEs is Project configuration and Web Server configuration. Luckily we avoid the latter in an Android tutorial. But you still need to set up the project. First, some terminology. An “Eclipse Workspace” is an “IDEA Project”. An “Eclipse Project” is an “IDEA Module”. An Eclipse Workspace is composed of several projects. An IDEA Project is composed of several modules. If you have Eclipse project files then IDEA should be able to import them with no problems, and this is the fastest way to get started.

The Project is configured using the File->Project Structure menu item. You can also open the window using the Ctrl+Alt+Shift+S shortcut, which I call the Paw Mash because holding your left hand like a bear paw and mashing the keyboard usually suffices to open the window. This is where you specify your source folders, your SDK version, and your dependencies. If there is no Project SDK selected in the dropdown list, or if the list shows an error, then click on the SDKs item in the left side pane to create a new one.

08. Project Configuration

Configure the modules by clicking the module entry on the left side. Here you can mark certain folders as source or as tests. By default, a fresh IDEA Android project has no “tests” folder, so you should add the folder and then come in here as mark it as Test Sources. You can also change some of the Android compiler settings by clicking the Android facet shown in the middle.

09. Module Configuration

One last thing to configure before leaving the window. If you are writing JUnit tests then you’ll need to add JUnit to your project dependencies. If you just annotate a method as @Test then IDEA prompts you to add the junit.jar to your classpath. The problem is that they add it as the last dependency, which causes the test to fail with the error “java.lang.RuntimeException: Stub!”. Come into this window and move JUnit up in the dependency list. Or configure Ivy/Maven/Whatever to do this automatically for you.

10. Module Dependencies

That’s the quick tour of Project Structure… lets move on to Settings. Settings are the options not directly related to compiling the project. Things like code style, version control, plugins, and much more. Open Settings using File->Settings or use your Claw Attack to hit Ctrl+Alt+S. I call this shortcut the claw attack because if you pinch your left hand into an eagle claw and swoop it down on your keyboard then the Settings window usually opens right up. It helps to let out a mighty, “Ka-KAW” when you do it.

There are thousands of settings in here. I heard the advice recently that new users of either IDE should spent a few hours just clicking around the settings page, and I honestly think that is pretty good advice. If you know what you’re looking for but can’t find it, then enter your search term in the upper left side search box and the settings list dynamically displays only those pages with matching entries. For instance, if you know you want to show line numbers, then type in Line or Line Numbers and click through the resulting pages. In this case, the highlighting you see in the image was created by IDEA and is used to point you to the correct setting.

11. Settings Configuration

You most definitely want to change some of the default settings. Showing Line Numbers is under Editor->Appearance. Changing your tabs and space settings are done on a per-file type basis, and is accessed from Editor -> Code Style. By default IDEA allows you to place the cursor past the end of the line in a text file, and you turn this off under the Editor page. And Version Control is something you really must configure as well, which is under Version Control. GitHub integration in IDEA is tip-top and goes beyond just Git support, but lately I’ve been using and recommending BitBucket for free, private git hosting. In general I find myself using the IDE to make local commits and manage changelists, and the command line to perform pushes.

Links

That’s it! There are tons of ways to learn more, and here are my favorite links:

The formal release of IntelliJ IDEA 10.5 came out this month, and the new Groovy features are all part of the free and open source Community Edition, and the Grails features are part of the Ultimate Edition. IDEA X (or 10 to you non-Romans) was a larger release of the product, and I already blogged about IDEA X for Groovy and IDEA X for Grails. There’s still plenty of nice features in 10.5 though. The prices for IDEA recently dropped between $100 and $50, and anyone purchasing IDEA since last November gets 10.5 as a free upgrade.

Here’s what 10.5 is all about (or skip straight to the release notes).

Groovy 1.8 Support
A big push in IDEA 10.5 was Groovy 1.8 support. Groovy 1.8 contains many compile time AST transformations that do things like write out new methods and fields into the Groovy .class files. Normal IDEs will show in-IDE compile errors when using these annotations yet still allow you to compile and execute the script. This has been fixed in IDEA, so the IDE should give you proper code completion and support when you use @Field, @TupleConstructor, and @Log. This is especially helpful when invoking these synthetic members from Java code.

Introduce Parameter and Introduce Field Refactorings
Introduce Parameter is one of my favorite refactorings. Select a local variable within a method, press Ctrl+Alt+P, and the local variable is extracted into a method parameter. It doesn’t yet work for closures, but you can vote for that feature. Introduce Field is also handy: select a local variable in either a method or a closure, press Ctrl+Alt+F, and the local variable is extracted into a field on the enclosing class. IDEA is not capable of extracting a field in a script yet, which would logically create an @Field script field, but feel free to upvote the issue.

Go To Test (and vice versa) Support
Tests and production source follows a naming convention, for example MyClass and MyClassTest. You can now press Ctrl+Shift+T to jump to the test (if you’re in production code) or jump to the production code (if you’re in the test). And if there is no test, then it will prompt you to create a new one. This works great in most cases. Of course, with Groovy it is not so rare to have several top-level classes in a single source file. In these cases the feature can sometimes get confused. Upvote the fix here if you want it to be just that much smarter in the future.

More Code Completion and Intentions
The “add static import” intention is nice for those who use a lot of static imports. Just set your cursor in a constant referenced from your code, press Alt+Enter, and viola… the constant is statically imported. Also, code completion is now available when creating an object using named parameters, which makes them a little easier to use. A whole bunch of other code completion issues were fixed as well, but these were technically marked as bugs not features. You can always peruse the release notes to see the whole story.

Performance
JetBrains claims that file indexing (typically at IDE startup) is now faster and that working with large Groovy files is more performant. It is hard for me to see a difference since I use the EAP versions and don’t currently work on any massive projects currently.

Grails Code Generation & Completion (Ultimate Edition)
Some small but nice things here. If you reference a controller action from a GSP, and that action does not exist, then pressing Alt+Enter creates an empty action for you. Also, the type inference for values on the GrailsPlugins has been improved, such as the closure parameters for doWithApplicationContext, doWithDynamicMethods, etc, and code completion for controllers and action in custom plugins are now discovered automatically. Finally, the code inside <r:script> tags from the Grails Resource plugin is now parsed as JavaScript, so full IDE JavaScript is available within them. This is supposed to become a standard for Grails 1.4, so it should continue to work with that release.

Improved Grails Resource Bundle and i18n Support
With 10.5, if you reference a property using the <g:message> tag in a GSP, and that property does not exist, then the property will be underlined in red and you’ll be given an Alt+Enter Intention to create it for you. Nifty. Also, the existing i18n intentions should now work better when you have GString syntax in your text. For instance, the string “Hello, ${user}” should now be properly handled when extracting to a resource bundle.

Various Usability Improvements
Last on the list are a few odds and ends around usability. Closures can now have the separator line between them in the IDE, the way methods show a line between them. GSP stacktraces have correct (and clickable) hyperlinks. The scripts folder is visible in the Grails view. And code navigation and formatting has been improved for several Grails Artefacts.

That’s it. Enjoy the upgrade, may your solid state disk never fail, and may your caches always be valid. Caio!

If you like this sort of thing, then there is also a whole bunch of other IDEA related content on my own blog and on the Canoo blog. Enjoy.