Grails Goodness: Using Random Values For Configuration Properties

Since Grails 3 we can use a random value for a configuration property. This is because Grails now uses Spring Boot and this adds the RandomValuePropertySource class to our application. We can use it to produce random string, integer or lang values. In our configuration we only have to use ${random.<type>} as a value for a configuration property. If the type is int or long we get a Integer or Long value. We can also define a range of Integer or Long values that the generated random value must be part of. The syntax is ${[<start>]} or ${[<start>,<end>}. For a Long value we replace int with long. It is also very important when we define an end value that there cannot be any spaces in the definition. Also the end value is exclusive for the range.
If the type is something else then int or long a random string value is generated. So we could use any value after the dot (.) in ${random.<type>} to get a random string value.

Continue reading

Grails Goodness: Using External Configuration Files Per Environment

Grails 3 is build on top of Spring Boot and this adds a lot of the Spring Boot features to our Grails application. For example in Spring Boot we can store configuration properties in an external file. A default Grails application already adds application.yml in the grails-app/conf directory. If we want to specify different values for a configuration property for each environment (like development, test and production) we can use environment section in application.yml. We know this from previous Grails versions with a Groovy configuration file Config.groovy. But we can also create different configuration files per environment and set the value for the configuration property in each file. We can use the following naming pattern for the file: application-{env}.yml or application-{env}.properties. These files need be in:

  1. a config directory in the directory the application is running from
  2. the root of the directory the application is running from
  3. in a /config package on the classpath
  4. in the root of the classpath

Continue reading

Grails Goodness: Defining Spring Beans With doWithSpring Method

Grails 3 introduces GrailsAutoConfiguration as the base class for a Grails application. We can extend this class, add a main method and we are ready to go. By default this class is the Application class in the grails-app/init directory. We can override several Grails lifecycle methods from the GrailsAutoConfiguration base class. One of them is doWithSpring. This method must return a closure that can be used by the Grails BeanBuilder class to add Spring beans to the application context. The closure has the same syntax as what we already know for the grails-app/conf/spring/resources.groovy file, we know from previous Grails versions.

Continue reading

Grails Goodness: Passing System Properties With Gradle

In a previous post we learned how to pass Java system properties from the command-line to a Java process defined in a Gradle build file. Because Grails 3 uses Gradle as the build tool we can apply the same mechanism in our Grails application. We need to reconfigure the run task. This task is of type JavaExec and we can use the method systemProperties to assign the system properties we define on the command-line when we invoke the run task.

Continue reading

How to write bug free code – State

A lot of bugs are in some way related to state. So that is what we will be talking about today. We will start off with a quote from Einstein:
“Insanity: doing the same thing over and over again and expecting different results. ”

Code should be consistent, calling the same function with the same input should return the same result during the whole life cycle of the object. Insanity and bugs will follow if this rule is violated.

This sounds logical, but in practise it is quite easy to violate this principle. The main cause of this, is object state. This state is used in a lot of functions, and can thus affect the behaviour of our program at runtime. This principle can be even be seen in the most basic of examples (imagine the impact on a more complicated class…).

Given the following class:

Lets see how this state affects the behaviour of our object:

All it takes is a simple setter, and calling the same function over and over again with the same parameter (void in this case) does not have to result in getting the same output. This means the object is not safe, and the state should be checked every time we call getName(), since we have no way of knowing if the function might return null. (bonus points if you notice that you also get null if you do not call the setter at all!)

As developers we usually work on projects in teams, and even if you always do a null check on getName(), one of your colleagues might forget at some point, and that code might result in a null pointer at some point in time.

There are two ways of avoiding the consistency problem. The first is creating constant state (immutability), or passing the state as an argument, and thus make the method stateless.

Lets see what an immutable version of Person would look like:

There are a couple of things that have changed. First of all, we now use the final keyword for our variable name. This makes sure the variable can be assigned only once (in the constructor). In the constructor we also throw an exception if the parameter is null. Thus, the object cannot be instantiated in an illegal state, and since we lack a setter, the state cannot be altered during the lifecycle of the object. (for the sake of argument, we will ignore reflection for this discussion)
This means we now have a safe object. Every time we call getName(), the same result will be returned, and Einstein is again a happy man. Also, we can now remove all null checks on getName(), since it is now impossible for it to be null.

The downside of this, is that in order to change the name, you need to create a new object with a different name, but the consistency of immutability is well worth the trade-off.
A second downside is that since you do not have any setters, arguments can only be passed as constructor arguments, and this can lead to very ugly constructors. If this is the case, I suggest taking a look at the builder pattern, which deals with this problem quite well.

For the second solution Java can help us as well, with the static keyword. Let’s take the following example:

As you can see, sayHello1() uses the state of Person, and as we just learned, this would be safe if name was immutable, but we can avoid the issue entirely if we instead pass the variable as an argument. No matter the state of Person, sayHello2() will always return the same value when called with the same argument, and thus Einstein will again, be a happy man.

So, does this mean you should make all your classes immutable?
No, sometimes things are just optional, or you have no way of knowing the value for certain properties at object creation. However, it can still be a good practice to transform the mutable object to an immutable object once this is possible, MutablePerson -> Person and only use the immutable object in your buisnesslogic
My rule of thumb in this case is: you should make everything immutable, and only make them mutable with good argumentation.

In conclusion.
We learned that state can cause our methods and thus our application to behave differently. This is a mayor cause of bugs (especially null pointers). The solution is to be aware of state, avoid it if possible by using static methods, or if you cannot avoid it, make your object as immutable as possible.

Grails Goodness: Pass Configuration Values Via Environment Variables

Since Grails 3 is based on Spring Boot we can re-use many of the Spring Boot features in our Grails application. For example in a Spring Boot application we can use environment variables to give configuration properties a value. We simply need to follow some naming rules: the name of the configuration property must be in uppercase and dots are replaced with underscores. For example a configuration property feature.enabled is represented by the environment variable FEATURE_ENABLED.

Continue reading

Grails Goodness: See Information About Plugins

In Grails we can use the list-plugins command to get a list of all available plugins. The list returns only the plugins that are available for the Grails version we are using. So if we invoke this command in Grails 3 we get a different list than a Grails 2.x version. To get more detailed information, like website, source code URL and dependency definition we use the plugin-info command.

Continue reading

Spocklight: Mocks And Stubs Returning Sequence of Values

Creating and working with mocks and stubs in Spock is easy. If we want to interact with our mocks and stubs we have several options to return values. One of the options is the triple right shift operator >>>. With this operator we can define different return values for multiple invocations of the stubbed or mocked method. For example we can use the >>> operator followed by a list of return values ['abc', 'def', 'ghi']. On the first invocation abc is return, the second invocation returns def and the third (and following) invocation(s) return ghi.

Continue reading

Groovy Goodness: Turn Method Parameters Into Named Map Arguments With IntelliJ IDEA

A very useful feature in Groovy is the use of named arguments. Instead of a list of arguments for a method or constructor we can use a Map argument. If the argument is the first in the list of arguments then Groovy allows use to use named arguments when we invoke the method or constructor. This means all key/value arguments are gathered together and assigned to the Map argument. Inside our method or constructor we can then access the Map argument and get the values for the keys. This leads to better readable code and that is very useful. IntelliJ IDEA has a Groovy intention to turn method parameters into a Map parameter for named arguments with a few mouse clicks.

Continue reading