0

Just a few high-level, hopefully very quick questions:

1) If I have a class A with a single field x, is constructing it

def A = new A(x:someVal, y:someVal) 

totally fine?

2) Related, is the following a good way to copy relevant parts of a command object into a domain object?

 def domainObject = new DomainObject(commandObject.properties).  

Where command object has extra properties. Or should it be done instead:

def domainObject = new DomainObject()
domainObject.properties['prop1', 'prop2', ...] = commandObject.properties

or ?

Thanks

Jay Prall
  • 5,295
  • 5
  • 49
  • 79
Ray
  • 5,885
  • 16
  • 61
  • 97

1 Answers1

1

For the first question, it's important to distinguish between a vanilla groovy object, and a grails domain object. Groovy objects with throw a MissingPropertyException. Grails domain objects will silently ignore extra properties.

Regarding the second question, initializing grails domain objects with a command object is a common pattern, and generally ok. Params can be a little bit more dangerous. A malicious user can put anything into params so it's best to explicitly spell out what properties you want to assign. Otherwise, things like timestamps and users, or even non-mapped columns like injected spring beans could be affected.

ataylor
  • 64,891
  • 24
  • 161
  • 189
  • Wonderful, thanks for this explanation. Could you please expand just a bit on the last part, i.e. the injected spring beans. I'm still a bit new to Grails. Thanks again – Ray Oct 04 '11 at 22:24
  • There are special objects that grails/spring manages ("spring beans") that you can use by simply defining a field with the right name in another spring managed object (e.g. controller, domain object, or service). Your field gets gets set to the object when your object gets created. While it's much more common to put them in controllers, if you have one of these in a domain object, it could get clobbered by a params property. There's a better explanation in the manual: http://grails.org/doc/latest/guide/14.%20Grails%20and%20Spring.html. – ataylor Oct 04 '11 at 22:33