dre
dre

Reputation: 1037

Grails - Interface rather than abstract class

I want to include "created" and "modified" fields in all of my domain classes and would like to embrace the DRY principle if possible. I don't want to extend each class as I cannot do that for a second time so instead, I'm trying to implement an interface.

Consider:

interface AutoTimeStamp{

  Date created
  Date modified
}

class Dog implements AutoTimeStamp{
  String breed
}

class Cat implements AutoTimeStamp{
  String noOfLives
}

But when I try to create a new Dog or Cat I get:

Cannot set the property 'created' because the backing field is final.

Any idea as to why this appears to be illegal? This works like a charm as an extended class.

Upvotes: 0

Views: 315

Answers (3)

Graeme Rocher
Graeme Rocher

Reputation: 7985

The above answer is correct, to define an interface that has properties you need to do:

interface AutoTimeStamp{

   Date getCreated()
   void setCreated(Date created)
   Date getModified()
   void setModified(Date modified)
}

Then in the implementing classes you can define the properties

Date created
Date modified

Upvotes: 1

dmahapatro
dmahapatro

Reputation: 50245

dateCreated and lastUpdated is available in domain class by default.

If you want to disable autoTimestamp then use:

static mapping = {
    autoTimestamp false
}

Upvotes: 1

Loic Cara
Loic Cara

Reputation: 301

You should not forget that Groovy interfaces follow the same philosophy as Java interfaces. As such for every property in a Groovy interface:

PropertyType propertyName

means:

public static final PropertyType propertyName

You can also have a look here, please have a look on Guillaume Laforge's posts ;)

http://groovy.329449.n5.nabble.com/RFE-interface-properties-td386038.html

Upvotes: 0

Related Questions