My team recently decided to explore switching to IntelliJ. Things are going pretty well, but someone discovered Live Templates and all of the complicated stuff they can do. Someone jokingly challenged me to write a live template which would spit out Preconditions checks for methods... A couple of days later I had figured this much out:
Abbreviation:
precon
Template Text:
$GROOVY$
Variables:
GROOVY - groovyScript("_1.collect { 'Preconditions.checkNotNull(' + it + ', \"'+ it +' cannot be null\");' }.join('\\n')",methodParameters())
This is pretty cool, and the output looks something like this:
Preconditions.checkNotNull(id, "id cannot be null");
Preconditions.checkNotNull(sourceKey, "sourceKey cannot be null");
Preconditions.checkNotNull(partitionId, "partitionId cannot be null");
Preconditions.checkNotNull(loadId, "loadId cannot be null");
Now, that's a good start, but definitely isn't perfect. This is fine if all of these variables are POJOs or other types which should only not be null, and are fine otherwise. However, we normally use other tools to help give us better control over input parameters and more informative output when things go wrong. Here's a better example of what the generated code above should look like:
Preconditions.checkArgument(StringUtils.isEmpty(id), "id cannot be empty null");
Preconditions.checkNotNull(sourceKey, "sourceKey cannot be null");
Preconditions.checkArgument(StringUtils.isEmpty(partitionId), "partitionId cannot be empty or null");
Preconditions.checkNotNull(loadId, "loadId cannot be null");
So, my main/core question is, how can I get both the method parameters and their type injected into my Groovy script, so that I can do conditional checks and generate preconditions checks accordingly?
But, more generally... Is there a better way to code these groovy script and smart template combos? There were a lot of hiccups while I was putting the above script together and instead of any really usable output/feedback/information, IntelliJ would just dump the errors/exceptions out into my source code after I had triggered the abbreviation.