Post-Redirect-Get pattern with Grails

In this post I would like to share with you a very common pattern used in web application development and how I implemented the pattern in my Grails application. Let’s start with a simple explanation of the pattern and what is it useful for.

Post-Redirect-Get

Post-Redirect-Get refers to the flow or process that web applications follow. When user submits the form in the browser the information is typically send with HTTP POST method to a web server. Application processes the information and sends back the response. Response is sent in a form of redirect to another view. Browser loads new state from web server using GET method.

Post-Redirect-Get pattern

Some of the benefits of using this patterns are:

  • Pressing refresh button in the browser will not cause duplicate form submission. The most annoying dialog box asking you if you want to resubmit your form will be gone.
  • Bookmarking result page would be possible.
  • Pages with forms submissions will be gone from your browser history.
  • Nice and clean separation of the HTTP methods that change state of an object (POST, UPDATE, DELETE) from non-destructive, read-only methods (GET).
  • Easier to test response, as all you need to check is the redirection. Typically when form is submitted successfully it will redirect to different page then failed submission. To test the behavior it is enough to test the redirection.

With the pattern in mind and the benefits let us try to look at the concrete FooBar example.

Grails example

I assume you know what Grails is. I’ve created a project and created domain object called Foo. The only property it has is a String, Bar that cannot be blank.

package post.redirect.pattern
class Foo {
  String bar
  static constraints = {
    bar blank: false
  }
}

Foo controller with two methods responsible for creation of new object.

class FooController {
…
def create() {
  def instance = new Foo(params)
  if (flash.model){
    instance = flash.model
  }
  [fooInstance: instance]
}
def save() {
  def fooInstance = new Foo(params)
  if (!fooInstance.save(flush: true)) {
    flash.model = fooInstance
    redirect(action: "create")
    return
  }
  flash.message = "Hooray, you did it!"
  redirect(action: "show", id: fooInstance.id)
}
…
}

When user submits the form and the object is invalid, the browser is redirected back to the form instead of rendering the form with error messages.

There is an extra check to see if user arrived on this page after unsuccessful form submission.

I used flash to store invalid object between pages, so the user could get feedback on what is wrong with provided values.

If you want to try on another example, the easiest way is to create a domain class and generate the scaffolding for it. You can try the browser behavior on generated code.Try refreshing the page after form submission (valid and invalid), try to navigate between pages using Back and Forwards buttons of your browser, try to bookmark the submitted page.

Later, go and modify the code, replace renders with redirects and see browser behavior after that.

Summary

This is all there is to it. It’s rather simple and easy to follow pattern with number of benefits. Grails makes it a doodle to implements,. Have fun redirecting.

Greg

How to use simulators during web development

Ski SimulatorThis is probably two topics that I would like to combine into one, as they are related in the context I will be writing about.

In one of the previous articles I wrote about the story wall that we evolved on our project. Christian in his article, described the way we worked not in pairs but in threesomes. Two developers and a QA. This was the way that involved iterative, small-steps, story delivery with constant showcasing to QA. QA was able to instantly check the correctness of a functionality, business logic, even a site layout and provide feedback to devs about it.

As any application (at least majority of them) our application has multiple points of integration to other systems. Database, web services, file system etc. One of the integration points was delivered some time ago and never tested, we were ready for a problems and bugs.

It would be very unwise to stop development because the part of the system needs fixing or some rework carried. We decided that we will shield our selfs with the layer of wrappers around third party systems , that we called Anti Corruption Layer.

The Layer gives as a constant API controlled by ourselves but it doesn’t mean that we can continue our way of working and constantly showcase all the acceptance criteria to our QAs and BAs.

We decided to bring on simulators on a board and hooking them into our anti corruption layer. This is how we achieved it:

Control

It would be very painful to switch simulator on or off using configuration in one of the file. Knowledge about the environment was not sufficient enough as we don’t want simulators to be on or off all the time. What we decided was to create a class called SimulatorDecider that will use two variables to determine if the Simulator should be on or off: current environment and a browser cookie.

The environment variable allowed us to switch simulators off regardless of the cookie, in any environment other than DEV or TEST.

Cookie in web browser is very simple to set and to remove. We created a little page called Cookie Monster that has a simple on/off buttons for setting and removing the Simulator cookie.
The approach gives a possibility to control and switch on/off different parts of the system by using different cookies for each parts.

Simulator

We have a bunch of wrappers around the integration points. The one that we are interested in, the one that we would like to simulate, we decorate with Configurable object and inject SimulatorDecider into it. This is how it works:


interface IFoo
{
  ReturnType DoStuff(ParameterType type);
}

public class Foo : IFoo
{
  public ReturnType DoStuff(ParameterType type)
  {
    // Doing some real stuff that is very important
  }
}

public class SimulatedFoo : IFoo
{
  public ReturnType DoStuff(ParameterType type)
  {
    // Doing some other stuff that is only SIMULATED
  }
}

public class ConfigurableFoo : IFoo
{
  private SimulatorDecider _simulatorDecider;

  public SimulatedFoo(SimulatorDecider simulatorDecider, IFoo realFoo, IFoo simulatedFoo)
  {
    _simulatorDecider = simulatorDecider;
  }
  public ReturnType DoStuff(ParameterType type)
  {
    if (_simulatorDecider.ShouldSimulate())
    {
      return _simulatedFoo.DoStuff(type);
    }
    return _realFoo.DoStuff(type);
  }
}

Because we are using dependency injection container (Yadic) we don’t need to worry about dependencies.
It is also possible to not code SimulatedFoo as separate type and just inline simulated behavior within the configurable type. We made this decision on a base of how complex the simulated behavior should be.

Hope you find this useful when you stuck on integration pice that you don’t know how to carry on 🙂
Comments are welcome as always 🙂

Greg

How to deal with nulls

This week I’ve been refactoring and improving some code in a .Net world. In last few weeks I also had some close encounters with Java as well. When looking at the code in both environments I realized that there is a lot of checking for null values on in a code. Where it is not a bad practice to check for null it actually presents another problem.

For someone like me when I was new to a code I couldn’t guess, what is the goal of that check. When you dealing with null the very important thing is to know where they came from and why it happened that null values occurred. When dealing with integration points it is even more important.

As you can guess code:

if (serverResponse == null)
{
    DoSomeStuff();
}

is not very descriptive. What actually happend when I got null, does it mean that there was a communication problem, error occurred or perhaps a null means that the operation was successful.

I think the best approach will be to avoid nulls if it is possible at all. Ways we could try to avoid it:
use Maybe pattern
• create Empty object values
• use Null Object pattern

Maybe pattern

I’m not sure if that is it’s appropriate name but I’ve used it on few projects and it seems like people are referring to it this way.

Have a Maybe interface and return it instead of the object itself.

interface Maybe<T>
{
    bool Hasvalue;
    T Value;
}

Also have two implementation of the interface:

public class Something<T>
{
    private readonly T _value;
    public Something(T value)
    {
        _value = value;
    }

    bool HasValue { get { return true; }  }
    T Value { get { return value; } }
}

public class Nothing<T>
{
    bool HasValue { get { return false; } }
    T Value { get { throw new InvalidOperationException(); } }
}

When returning value from an object return Maybe. Collaborator that consumes value can check if it is Something or Nothing or just ask if it has value.

Empty Object value

Just like string.Empty you can implement Empty or something similar as predefined value on your type. For example:

class Hen
{
    Egg LayEgg()
    {
        // doing stuff
        return Egg.Empty;
    }
}

class Egg
{
    public static Egg Empty = new Egg(“nothing in it”);
}

You can always check before the execution if the egg is empty.

Null object pattern

Object with no default behavior. For example:

interface TV
{
void ShowMovie();
}

class LCD : TV
{
    void ShowMovie()
    {
        // showing movie
    }
}

class Plasma : TV
{
    void ShowMovie()
    {
        // showing movie
    }
}

class NullTV : TV
{
    void ShowMovie()
    {
        // do nothing
    }
}

If something is not working well and we don’t have any of the TVs available we could return NullTV and nothing will happen.
Using the patter we can validate by type if the returned TV is a valid object and act accordingly.

I’m interested what other approaches people are heaving. Also what are the approaches in dynamic languages like Python or Ruby.

Please add your comment 😉

Greg