Grails’ JSONObject.NULL More or Less Equal To Null

Since Groovy 1.8 we can check if a Map is equal to another Map if the keys and values are the same. Very convenient in tests for example.

def someMap = [age: 34, name: "Ted"]
assert someMap == [name: "Ted", age: 34] 

Today I kept staring at a failure, while testing some x and y graph data points returned by a Grails controller, where two Maps were somehow not equal according to Spock, while even the assertion’s output looked ‘equal’.

when:
controller.milkYield()

then:
response.json

and: "series are present"
def series = response.json
series.size() == 2

and: "realized series is correct"
...
and: "predicted series is correct"
def predictedSeries = series[1]
predictedSeries.values.size() == 2
predictedSeries.values[0] == [y:null, x:'Mar']
predictedSeries.values[1] == [y:121, x:'Apr']

resulted in:

Condition not satisfied:
predictedSeries.values[0] == [y:null, x:'Mar']
|               |     |   |
|               |     |   false
|               |     [y:null, x:Mar]
|               [[y:null, x:Mar], [y:121, x:Apr]]
[values:[[y:null, x:Mar], [y:121, x:Apr]]]

Why isn’t [y:null, x:Mar] equal to [y:null, x:Mar]?

After having checked explicitly with

predictedSeries.values[0].x == 'Mar'
predictedSeries.values[0].y == null // <- better be null!

I remembered again I was dealing with JSON data in Grails, which uses the Null Object pattern. Keeps biting me every now and then :-)

Condition not satisfied:
predictedSeries.values[0].y == null
|               |     |   | |
|               |     |   | false
|               |     |   null (org.codehaus.groovy.grails.web.json.JSONObject$Null)
|               |     [y:null, x:Mar]
|               [[y:null, x:Mar], [y:121, x:Apr]]
[values:[[y:null, x:Mar], [y:121, x:Apr]]]

Grails JSONObject null

It’s a JSONObject$Null instance. It exists because it’s equivalent to the value that JavaScript calls null, whilst Java’s null is equivalent to the value that JavaScript calls undefined.

There are some long time posts already describing this behaviour that JSONObject.NULL was not equal to null

JSONObject.NULL.equals(null) // true
JSONObject.NULL == null // false!!

and some meta-class changes you could do were suggested at the time. Seems reported GRAILS-7739 (Wrong == and asBoolean behavior for JSONObject.Null) says it’s been fixed a few years back in Grails 2.2.

Atleast something has been fixed. Although you still can not do JSONObject.NULL == null, you can change the assertion to using Groovy Truth since !JSONObject.NULL does work.

!predictedSeries.values[0].y
// or predictedSeries.values[0] == [y: JSONObject.NULL, x:'Mar'] if you like

And of course I should remember null in (console) output is always a String representation leading to “null” – such as JSONObject.NULL‘s toString() returns.

Grails 3 Released: Installing Gradle and Groovy 2.4 Support in Eclipse/GGTS

Grails 3 has been released with a ton of new features.

GGTS logoIf you’re used to adding a new Grails distribution in Eclipse or Groovy/Grails Tool Suite, you’ve might have experienced that your good old IDE might not support Grails 3 projects right out of the box.

You might be missing:

  • Grails 3 support at all :-)
  • Gradle support
  • Groovy 2.4 support

Here’s how I think you can fix some of these things.

Grails 3 support

As you regularly do with new Grails distributions is to add it in GGTS under Preferences > Groovy > Grails. But dang!…it doesn’t recognize the grails-3.0.x-directory you just unzipped a minute ago.

GGTS doesn't recognize Grails 3

No worries! We have Gradle now.

Gradle is the new Grails 3 build system, in favor of Gant. If you’ve created e.g. the helloworld-application as used in the Getting Started section of the manual, you see a few files like build.gradle and gradle.properties.

Because of this we don’t need a specialized IDE plugin perse, since existing Gradle tooling can do the trick! So we skip adding a Grails 3 distribution and we look for…

Gradle support

It is possible that GGTS doesn’t know to import a Grails 3 project into your workspace, because of missing Gradle support. You can:

Generate Eclipse/GGTS…

  1. … files with gradlew eclipse.
  2. This will generate .project and .classpath which will allow you to “import it as an existing project” into your workspace

or install Gradle support

  1. Open Eclipse Marketplace, search for “gradle”
  2. Choose e.g. the Gradle IDE pack or just the Gradle Integration plugin
  3. Now you can find and import your project too

In GGTS your Grails 3 project is just a “regular” Gradle project.

Hello world!

The above screenshot is possibly an idealized view – it might as well that you have some red markers! I did.

Grails 3 comes with Groovy 2.4, and if you don’t have the correct version set, you get:

Groovy: compiler mismatch Project level is: 2.4 Workspace level is 2.3
Groovy compiler level expected by the project does not match workspace compiler level.

It’s similar as when you had to install Groovy 2.3 into GGTS :-) You can fix the project level to 2.3 but then you get

Groovy:Unexpected problem with AST transform: The Spock compiler plugin cannot execute because Spock 1.0.0-groovy-2.4 is not compatible with Groovy 2.3.10. For more information, see http://versioninfo.spockframework.org

You’ll have to get…

Groovy support

Assuming you don’t already have it, we have to install the Groovy Compiler 2.4 Feature into GGTS.

1. Go to Help > Install New Software and use the update site http://dist.springsource.org/snapshot/GRECLIPSE/e4.4/

2. Select the Groovy 2.4 compiler and Next.

GRECLIPSE update site

3. If there’s a conflict, just press on – it’ll install Groovy 2.4 next to the other versions.

GRECLIPSE update site - just continue!

4. Continue all the way. Finish, restart.

5. Switch the compiler for the workspace. Go to Preferences > Groovy > Compiler and switch to 2.4.3.

Switch to Groovy 2.4.3 compiler

Done.

Happy programming!

Basic Groovy and Grails Code Review Guidelines

I’ve been – and still am – teaching Grails to non-Java programmers for a while now. This also meant to coach them into some ways of working I hold very dear, such as pair programming and doing code reviews.

Code Review

Of course, in the beginning with a new team I am doing the lot of the reviews, but as time passes I need everybody to do understand why they matter and what to look for in the code as a reviewer themselves. Every team should have a set code review guidelines they agree on – so we wrote down some conventions and rules and agreed to follow them.

Here I describe some guidelines and good practices to perform a peer code review of (the work of) a colleague. It’s not an exhaustive list and some are pretty straight-forward for seasoned developers, but it served me well to cover some basics for non-Java junior teams beginning with Java, Groovy and Grails.

General

  • Does the code fulfil the specifications or acceptance criteria written in the user story, or is there a gray area?
  • Do you understand what’s been programmed? Would you be able to make modifications to it later on?
  • Have the proper Grails and Groovy constructions been used to realize the proper things?
  • Is the code readable and does it adhere to our guidelines of code style and naming of things? See following sections.

Naming

Use the proper structures and names. Use the correct names of Grails artifacts, such as Domain Classes, Controllers, Services, TagLibs and methods and variables.

  • Packages should start with nl.<company> followed by application name, such as nl.first8.myapp
  • Classes start with CAPITALS, such as Animal, methods and variables are written in camelCase, such as displaySummary() or animalInstanceList
  • Try to avoid abbreviations. Prefer domainCode over dmnCd
  • Does the name actually cover the subject?

Readability

General readability- and formatting guidelines to read code easy and have it written in a consistent manner. A part can be done automatically with the built-in Formatter in the IDE, e.g. Ctrl-Shift-F in Eclipse or GGTS, but not everything.

Not all one-liners

In example below, split up e.g. the initialization of variables, in order for its usage to become more clear.

out << body() << ( (attrs.int('offset')) + "-" + ( Math.min(attrs.int('count'), attrs.int('offset') + attrs.int('max') ) ) + " " + title + " " + attrs.int('count') )

could become

int start = attrs.int('offset')
int total = attrs.int('count') )
int end = Math.min(total, start + attrs.int('max') )
 
out << body() << start + "-" + end + " " + title + " " + total

Spock tests and labels

There’s plenty to say about “proper” writing Spock tests, but that’s beyond the scope of this post.

Use the proper labels in Spock tests for readability. Use and:to separate multiple labels – with additional “textual description” after them – to make them stand out. Write

when: "searching for existing animal"
...
then: "we have results"
model.animalSearchResults.animalsCount == 1
flash.successMessage == "animal.all.found.message"
session.selected.size() == 1

as

when: "searching for existing animal"
...
 
then: "one found animal is returned"
model.animalSearchResults.animalsCount == 1
 
and: "all found message is displayed"
flash.successMessage == "animal.all.found.message"
 
and: "animal has been auto-selected"
session.selected.size() == 1

White-space

Use white-spaces to separate combined statements. Write

Integer.valueOf(params.offset?:attrs.offset)

as

Integer.valueOf(params.offset ?: attrs.offset)

White-space and brackets

Before and after brackets in general you do NOT have to use white spaces. Write

if ( params )
if ( total > 0 )
if ( end < begin )

as

if (params)
if (total > 0)
if (end < begin)

Curly brackets

Use curly brackets for one-liners. Write

if ( end < begin )
      end = begin

as

if (end < begin) {
  end = begin
}

Although you can write an if-statement on one line or just the line below without the curlies, especially when there are multiple statements after each other, it will improve readability and shows intent more clearly.

Compare

if (end < begin)
end = begin
end = end + 1

with

if (end < begin) {
  end = begin
}
end = end + 1

Comments

Use comments to state the purpose of classes and methods, clarify difficult pieces of code and document the decisions (“why?”) made. For Java en Groovy code we can use Javadoc to generate API documentation in HTML format in the source code.

Javadoc on classes

Use Javadoc comments at the top of a class to describe the general purpose, such as

/**
 * General convenience tags for layout - header, body and footer - purposes.
 */
class LayoutTagLib {

Javadoc on methods

Use Javadoc on public methods to describe the purpose and its parameters. You can use @param for parameters, @return for what it returns, when or if exceptions are thrown with @thrown etc.

/**
 * Gets the user for specified code and role.
 *
 * @param code The code, either username or email address
 * @param role The role identification e.g. A, B or C. Default is A.
 * @return the user or null if not found
 */
User findUser(String code, String role = "A")

Clean up

Remove obsolete comments, e.g. which got left behind, or which are plain wrong, or correct them!

Simplicitly

Is the code simple and does it do its work in the most simple way….but not simpler

Intuitive API

Use an intuitive API. Use similar structures or naming. Is only the actual required input needed and are for others sensible defaults being used? If you’re creating a betterPaginate tag, don’t burden the user too much with all kinds of input. Have him instead of

<g:betterPaginate offset="${params.offset?:0}“ count="${results.animalsCount?:0}" max="${params.max?:0}"/>

allow to use your tag as

<g:betterPaginate count="${results.animalsCount}" />

where you take care of the defaults, and the reading from paramsetc.

Simple writing

The more complicated lines used, the more difficult it is to understand what happens and where changes should go. It turns out that the following 10 lines created by a co-worker

int offset = 0
int total  = 0
int max    = 0
  
if (params) {
    offset = Integer.valueOf(params.offset ?: attrs.offset ?: 0)
    max    = Integer.valueOf(params.max ?: attrs.max ?: 0)
} else if (attrs) {
    offset = Integer.valueOf(attrs.offset ?: 0)
    max    = Integer.valueOf(attrs.max ?: 0)
}
total = Integer.valueOf(attrs.total ?: 0)

can be rewritten in just 3 lines with the same behavior:

int offset = Integer.valueOf(params.offset ?: attrs.offset ?: 0)
int max = Integer.valueOf(params.max ?: attrs.max ?: 0)
int total  = Integer.valueOf(attrs.total ?: 0)

If you have a good test, you can refactor somewhat more freely these kinds of constructions and still be fairly confident you didn’t change anything unexpectedly.

Oh and:

Rule 1: Try to find at least something positive
Image credits:

[1] What is Code Review? – http://smartbear.com/all-resources/articles/what-is-code-review/

[2] – How to Facilitate Friendlier Code Reviews – http://www.syncano.com/friendly-code-review/

GGTS: Clean up Grails 2.0 output

GGTS logoHave you ever had in Groovy/Grails Tool Suite (GGTS) that console output, by a running Grails application, which is exactly the same as the previous output, just isn’t displayed?

This can often be seen with println statements for debug-purposes e.g. in a Controller, which you think should output some line to the console every time, but simply doesn’t.

class TestController {
	def index() { 
		println "index called"
	}
}

When http://localhost:8080/test/test/index is invoked repeatedly in the browser, you just keep seeing only the first occurence.

....index called

When the same message repeatedly is sent to the console a certain convenience feature of GGTS swallows some output – if it looks the same. It has to do with the – since Grails 2.0 introduced – ANSI codes to make some output to the console coloured or re-appear on the same line.

Kris de Volder gives a nice example in JIRA issue STS-3499 about how multiple lines such as

Resolving Dependencies.
Resolving Dependencies..
Resolving Dependencies...
Resolving Dependencies....

are supposed to ‘rewrite over themselves’ on ANSI-supported consoles, so you’d only see

Resolving Dependencies...<increasing periods>

on the same line.

Output in the GGTS non-ANSI-enabled console is stripped from these codes – which would result in additional output which some people find unpleasant. So GGTS uses a workaround – which is enabled by default – and strips the beginning of the output which matches previous output and only print the remainder.

So if you were wondering why

class BootStrap {
	def init = { servletContext ->
		['A', 'B', 'B'].each { println it }
	}
}

would only print

|Running Grails application
A
B
|Server running. Browse to http://localhost:8080/test

instead of

|Running Grails application
A
B
B
|Server running. Browse to http://localhost:8080/test

you know now this is not a bug :-)

You have to disable the option ‘Clean Grails 2.0 output‘ in the GGTS preferences under Groovy > Grails > Grails Launch to prevent this swallowing-behaviour.

Now your output appears in GGTS when you want it to appear :-)