Question

Here is my domain class definition:

class Profile {
           PhotoAlbum photoAlbum

           static constraints = {
               photoAlbum(nullable:true)
           }
}

class PhotoAlbum {

        static hasMany = [photos:Photo]
        static belongsTo = [profile:Profile]

}

class Photo {
       static belongsTo = PhotoAlbum
}

In a controller I'll have an instantiated profile domain. The domain starts out with a null photoAlbum. If I want to add the first photo, I'll get a null pointer exception on the photoAlbum:

Photo photo = new Photo()

profile.photoAlbum.addToPhotos(photo)

What is the grailsy way to do this and avoid the null pointer exception:

Photo photo = new Photo()

if (!profile.photoAlbum) { profile.photoAlbum = new PhotoAlbum) }

profile.photoAlbum.addToPhotos(photo)

I would have thought that if photoAlbum was null, grails would just create a new one when I tried to add the first photo object to it. While the 3 lines of code above work, I'm wondering if there is a better way to accomplish the same thing in 2 lines of code.

Was it helpful?

Solution

You can override the getter for PhotoAlbum in Profile to create an album on demand:

class Profile {
    ...
    PhotoAlbum getPhotoAlbum() {
        if (photoAlbum == null) {
            photoAlbum = new PhotoAlbum()
        }
        photoAlbum
    }
}

Then when you call profile.photoAlbum, it will be created automatically as you expected. This will create empty albums whenever the getter is called, though, which might not be what you want. I'd make it more explicit, like this:

class Profile {
    ...
    PhotoAlbum createOrGetPhotoAlbum() {
        if (photoAlbum == null) {
            photoAlbum = new PhotoAlbum()
        }
        photoAlbum
    }
}

And call it like this: profile.createOrGetPhotoAlbum().addToPhotos(photo)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top