Happenings

Modern Java: Validation

In the previous post on Modern Java, I showed how Lombok is making Java beans more concise. In that post, I showed how we would end up with the following class:

@Data
public class Person {
    private String firstName;
    private String lastName;
    private int age;
}

Given an instance of that class by binding data from a web form, a database or some other data source, a fairly common requirement is to validate it against a series of rules and constraints.

For example, if we assume “age” is the number of years the person being described has been alive, we know that it must be zero or greater. Depending on our application we may also know that it’s above a minimum age (18, say) and is extremely likely to be below a maximum age (there are very few people over 100, and none over 120).

A few years ago, you would have to write a custom piece of code to validate simple rules in all of your domain classes. These would typically be specific to the class in question, running through a series of explicit checks, and produce a list of errors found. While this worked, it was often verbose and tightly-coupled to each domain class. It might look something like this:

public Collection<Error> validate(Person person) {
  Collection<Error> errors = new LinkedList<Error>();
  if(person.getAge() == null) {
    errors.add(new Error("Age cannot be null"));
  }
  if(person.getAge() < 0) {
    errors.add(new Error("Age must be greater than zero"));
  }
  if(person.getAge() > 120) {
    errors.add(new Error("Unlikely to be a real age"));
  }
  return errors;
}

Note that we’re only validating a few rules on one field, and it’s already quite verbose. If we validated every field on an object and the interdependencies between them, then we would have a lot of code.

Both the Spring Framework and Hibernate had come up with their own ways of making writing and integrating validation logic a little easier, but now validation has been standardised in JSR-303. The reference implementation is Hibernate Validator 4, and it’s a great starting point, but most uses of JSR-303 will be relatively agnostic of the implementation. Since this is a finalised specification, you can also make use of it today.

For our Person class above, let’s add the following constraints:

  • Age must be 18 or more
  • First and last name must be set i.e. they can’t be left null
  • First and last name must have at least one character in them

To implement these rules, we need only add a few new annotations, using standard constraints:

@Data
public class Person {
    @NotNull @Size(min=1)
    private String firstName;
     @NotNull @Size(min=1)
    private String lastName;
    @Min(18)
    private int age;
}

You then create a Validator instance (how you do this will depend on your chosen implementation), and pass the class in for validation:

Set<ConstraintViolation<Person>> errors = validator.validate(person);

All the validation is then handled for you, reducing the amount of code and making your bean classes very clearly state the constraints under which they operate. You know a first name is not just any old nullable string by just looking at the class, and you know ages have limitations in your particular domain of interest. The code is more expressive and concise, and that’s a very good thing.

There’s a lot more to the JSR-303 specification, and it has all the features you might want. While I fully intend to go into the other features at another time, I’d strongly recommend browsing the spec to see some of the power and flexibility available to you.

Modern Java: Lombok

In recent months, I’ve been looking at a lot of new Java libraries to see what I’d like to use and what I think still has a way to go. I’ll be posting about them all in due course but I wanted to mention Lombok first.

First, a class:

public class Person {
    private String firstName;
    private String lastName;
    private int age;

    public String getFirstName() {
      return firstName;
    }
    public void setFirstName(String firstName) {
      this.firstName = firstName;
    }
    public String getLastName() {
      return lastName;
    }
    public void setLastName(String lastName) {
      this.lastName = lastName;
    }
    public int getAge() {
      return age;
    }
    public void setAge(int age) {
      this.age = age;
    }
}

The problem here is that everything after public int age is predictable and verbose; you know that this is a Java bean class and that the fields are likely going to have getters and setters just like those provided. If we know exactly what to expect, shouldn’t the compiler take care of that for us rather than having us specify more code? Less code is often cleaner code.

For several years now, people have been asking for the idea of properties in Java. That is, being able to define fields and automatically having standard getters and setters defined, without having to clutter the class file with boilerplate. The most common (and reasonable) response for avoiding this is that it would be difficult to implement without affecting backwards compatibility.

While those proposals are pretty much dead at the moment, Lombok saves us from having to specify our standard getters and setters by marking our classes as beans and then jumping into the compilation process to make sure getters and setters are generated. The above code becomes:

@Data
public class Person {
    private String firstName;
    private String lastName;
    private int age;
}

That’s right: the 18 or so lines of getter/setter boilerplate are replaced by the tiny little @Data annotation, and the code is much cleaner. As a bonus, @Data also generates a toString(), an equals() and a hashCode(). You can use the other Lombok annotations to tweak the behaviour, but this is what most people are going to want.

Also of note is the @Cleanup annotation, which provides automatic resource management (ARM) for using input/output streams. While this will be less essential if ARM arrives in Java 7, it’s a handy little helper for the time being.

While Lombok can’t make bad code good, it can make verbose code a lot more succinct.

Film Fight 2010: March

The March 2010 film fight includes no fewer than 6 brand new movies. That should make up for the slightly quieter-than-usual February. Onwards…

The Crazies looked like it had decent potential: a Romero remake about an infected township, lots of explosions and action, and a little humour alongside. It blows it. The action overwhelms the story from the very beginning, moving things on to the next set-piece before really establishing any of the characters. Without anyone we actually care about, the film suffers immensely. The plot itself is as expected, but it fails to hit any of the big scares a film like this needs. It never gets better than mediocre. (See my The Crazies Twitter review).

A lot was expected of Tim Burton’s foray into Lewis Carroll’s classic novel, but Alice In Wonderland disappoints. It’s not a filming of either Alice story but a bizarre sequel/retelling. It fails by paying too much fan-service to the world of Wonderland, attempting to squeeze every character into this semi-new narrative, rather than tell a more coherent tale. The characters themselves are the high-point, with some great (if too short) appearances by the Mad Hatter and the Cheshire Cat. Does the spectacle of 3d make up for some of the story failings? No, not this time. Unlike Avatar, the effects on display are average at best. Some of the scenes work better than others, but some are clearly flat layers. There are also some frankly odd choices in the direction: tightly pulled-focus does not work in 3D. All in all, a disappointment.  (See my Alice In Wonderland Twitter review).

Crazy Heart earned Jeff Bridges an Oscar for his performance as drunken country singer, Bad Blake; and rightly so. The performances in this film are high quality, without ever getting towards scenery-chewing territory. Both Bridges and Maggie Gyllenhaal put in excellent and subtle performances, saying as much with quiet looks as with their words. The solid getting-your-life-together is marred only by a weak ending, when the central character gets his life together a little too fast to feel satisfying. A little more adversity and struggle here would’ve completed this very worthwhile film a lot better. (See my Crazy Heart Twitter review).

Martin Scorsese manages to show some great form with his latest work, Shutter Island, before ruining it with a cheap ending. The story follows a US Marshall tracking down an escaped mental patient on a small island off the US mainland. The film is spiked with a Lynch-ian vibe throughout, that something sinister is happening without being clear about what is wrong. It’s beautifully shot, if a little over-the-top in places. Leonardo Dicaprio pulls in a solid performance, but he can’t cover up the poor ending. The last thirty minutes devolve into cheap, seen-it-before cliche. A great beginning, that deserved a much better conclusion. (See my Shutter Island Twitter review).

The Girl With The Dragon Tattoo fails to live up to the not-inconsiderable hype. While some of the acting is solid, the story is full of cheap genre cliches. If you can imagine taking a high-street bestselling thriller and filming it straight-up, then you can imagine this movie: our heroes get involved in a murder investigation, working through it by uncovering previously indecipherable (but ultimately nonsense) clues. It’s slow to get started, and fails to engage. If you can switch off and not worry too much about how coherent the investigation is, then you can probably get something out of the performances. Otherwise, I’d pass on this film. (See my Girl With The Dragon Tattoo Twitter review).

Finally, I Love You, Phillip Morris is a real wasted opportunity, from what seems like it could be a genuinely brilliant story about a conman who will go to great lengths to get what he wants. Instead we have a movie that sits between flimsy comedy and feel-good movie, but never really reaching either. The central relationship between Jim Carrey and Ewan McGregor never feels convincing or genuine, needing more time to develop than the few moments we are given. The film desperately needed a longer run-time in order to show more development. Here’s a hint: if you have more than one montage (I think there were at least 3-4), you need a longer movie. A real shame, as it would be good to see Carrey do another serious film. (See my I Love You, Phillip Morris review).

The winner this month is Crazy Heart, mostly for the fantastic performances by the central cast and despite the short final act.

Film Fight 2010: February

It was a bit of a quiet month for me at the cinema, despite a lot of films that looked like they might be good being released. I only saw two films…

Youth in Revolt is a Michael Cera film, which should set up a number of expectations for it. You expect it to be a cute, indie-comedy about a geeky kid who has to find confidence to get the girl, or some other variation on the theme. The first act plays straight into this and is fairly weak for it. The middle, however, is substantially better as the lead character defers to his maniac alter-ego. Sadly, even this pretty funny section is ruined somewhat by the fact that 90% of it is in the trailer. While the ending isn’t as strong, it’s a fine finish to a watchable, but not great, movie. (Read my Youth in Revolt Twitter review).

A Single Man is a fairly straight-forward and somewhat predictable story of living with grief, through the eyes of someone who cannot allow themselves to express their feelings. The direction here is solid, bringing memories of Kubrick’s shorter shots; dressing tables, desks, and lived-in spaces giving the feel of the characters in a few short seconds. Colin Firth puts in a fantastic performance as the lead, wavering between having a breakdown at any moment and keeping a stiff upper-lip. A very good film overall. (Read my A Single Man Twitter review).

While there wasn’t much in the way of competition, A Single Man is a well-deservied winner.

Film Fight 2010: January

Another year, and another fresh film fight. As always, January was a tough month, with lots of pretty strong competition (usually the Oscar wannabes are released around this time of year). To get us started, there are 6 films this month.

First up is Robert Downey Jr. in a role that he really wasn’t born to play: Sherlock Holmes. Guy Ritchie gives us an interesting take on the classic detective. His typically non-linear storytelling is used to great effect to explain how the master detective has reached his conclusions, and is particularly good when he’s sizing up opponents in fights, slowly and methodically showing how he’s going to break down their defences. Why this particular story mechanic is dropped relatively early in the film is beyond me, because it’s one of the strongest. Less good is the script: a fairly poor mishmash of ideas, ranging from secret societies, magic, steampunk and master villians. It doesn’t particularly fit into the Sherlock Holmes mythos, and doesn’t readily establish itself as a new take. It’s a pretty mediocre action film, that’s also trying to be a comedy. It fails to do anything particularly well. Not recommended.  (Read my Sherlock Holmes Twitter review).

Daybreakers is a surprisingly watchable, but not great, film. It deftly manages to build up its world, quickly, quietly and effectively, and moves on with the story it has to tell. This is a world where an infection has caused the vampires to take over and hunt down the humans. The vampires, however, have over-extended and food is becoming scarce. Queue a story about diminishing food supplies, the folly of rapid and mindless expansion, and a lot of gore. That’s what saves this film: the tongue-in-cheek bloodbath we’re treated with visually, paired with some slightly cheesy lines. The film would’ve been better had it been more over-the-top. As it stands, Daybreakers is a decent action movie, but not a great one. (Read my Daybreaks Twitter review).

The Road is the almost resolutely bleak, yet absolutely compelling. The primary narrative follows a father and son travelling through a post-apocalyptic world (what happened is never explained), as they encounter endless difficulties and enemies. What starts as trying to protect his son soon becomes a desperate paranoia, as the father becomes wary of everyone they met, and slowly loses his way. Several scenes are horrifyingly blunt about the lengths the father will go to to ensure they don’t become food for the more cannibalistic elements, and Viggo Mortensen does a fantastic job of showing the slow decay that takes a grip of him. While the ending ties things up a little too neatly, the rest of the film is very well done. A must see. (Read my The Road Twitter review).

Not many people would make a comedy about firing people, but Jason Reitman has done just that with Up in the Air. The core conceit gives way to an inspection of the main character’s choices in life at just the right time, showing him up to be a willing outcast and seeing if those choices are right. While it does veer dangerously close to schmaltzy in places, it always manages to pull away by being brutally honest elsewhere. It’s not the funniest comedy, nor the best character piece, but both halves combine to make a good, solid movie. (Read my Up in the Air Twitter review).

A Prophet is a very interesting French film, a fairly gritty take on a prison drama. Malik begins as a young, somewhat naive hoodlum who goes to jail and, over the course of the film, becomes warped by his environment and the things he needs to do to survive. It doesn’t pull many punches as he schemes his way further up the criminal ladder. It’s well-structured and well-paced, being lent real weight by the very natural performances. While the scene in the middle where they both use the title and throw around a dead deer are puzzlingly unnecessary (and in poor taste), the rest of the film is very well done. (Read my A Prophet Twitter review).

Finally, Precious is a fairly harrowing story of bullying, abusive upbringings and never thinking you can make something of yourself. While, at times, it turns things around a little too neatly, the main plot-line is equally engaging and chilling. Mo’Nique puts in an Oscar worthy performance as the abusive mother, handling a fairly dicey subject with a great believability. It’s not easy to watch, but it is worthwhile. A powerful film. (Read my Precious Twitter review).

And the winner? It was a close-run thing between Precious, The Road and A Prophet, but I think The Road takes it in the end. Another great January for film.