« Return to Thread: "findOrCreateBy"

Re: "findOrCreateBy"

by Robert Fischer :: Rate this Message:

Reply to Author | View in Thread

I'm not looking for that flexibility.  I'm looking to eliminate this repeated code:

def nameArg = ...
Item.findByName(nameArg) ?: new Item(name:nameArg)

In that idiom, I repeat the class twice, the attribute twice, the argument twice, and it looks
scarier than it should.  And since I use this idiom all over the place, I'd like to fix that.

Don't take this personally, but I'm not looking for feedback on whether other people think it's a
good idea or not.  As far as APIs go, I figure that if you don't like it, you don't have to use it.
  There's no harm being done to the code on your side: a method existing where one didn't before
won't break your code.  And since this is going into GORM Labs and not core Grails, and since I find
it useful and there's no harm being done, I don't feel the need to vet it by the community.

I'm really just wondering if someone else has a better name, because I'd like to create something
that others might find useful and use now and again, too.  And a good name helps adoption quite a
bit.  :)

~~ Robert.

Scott Burch wrote:

> Do we need a new method for this or is this too much.  Seems like not
> that much to me.
>
> def item = Item.findByName('someName') ?: new Item()
>
> Certainly, this would be more flexible.
>
> def item = Item.findByName('someName') ?: new Item(name:'default', property:'something')
>
> On Fri, 2009-07-03 at 15:41 -0400, Robert Fischer wrote:
>> I'm adding "findOrCreateBy" in GORM Labs (does a find, and failing that, instantiates a new one).
>> Anyone have a nicer nomenclature for that?
>>
>> ~~ Robert Fischer, Smokejumper IT Consulting.
>> Enfranchised Mind Blog http://EnfranchisedMind.com/blog
>>
>> Check out my book, "Grails Persistence with GORM and GSQL"!
>> http://www.smokejumperit.com/redirect.html
>>
>> ---------------------------------------------------------------------
>> To unsubscribe from this list, please visit:
>>
>>     http://xircles.codehaus.org/manage_email
>>
>>
>
>
> ---------------------------------------------------------------------
> To unsubscribe from this list, please visit:
>
>     http://xircles.codehaus.org/manage_email
>
>
>

--
~~ Robert Fischer, Smokejumper IT Consulting.
Enfranchised Mind Blog http://EnfranchisedMind.com/blog

Check out my book, "Grails Persistence with GORM and GSQL"!
http://www.smokejumperit.com/redirect.html

---------------------------------------------------------------------
To unsubscribe from this list, please visit:

    http://xircles.codehaus.org/manage_email


 « Return to Thread: "findOrCreateBy"