tags:

views:

112

answers:

5

Imagine an interface with a method to create objects of type Address. The entities involved here are irrelevant.

/**
 * @throws IllegalArgumentException if addy is null or invalid
 * @throws PersistenceException if db layer encounters a problem
 */
Object addAddress( Address addy );

addAddress inserts the domain object into the database.

I've left the return value to be Object. My question is: what should the return type be ? Normally I've chosen a boolean return value (assuming no exceptions were thrown). Sometimes I've chosen to return the autogenerated PK key of the record for the Address. And more often than not, I just leave it as void. What do you normally do & why ?

+1  A: 

I return the auto-generated primary key. You could update the address object itself (and you may still want to) but returning it makes the point of the method obvious.

This would make the signature:

long addAddress(Address address);
Matthew Murdoch
+4  A: 

bool is definitely no good since there will be no architecturally sound way of finding out what actually went wrong while inserting a row in a database (by "architecturally sound" I mean absence of singletons and other shared state in service layer). What there's left is a PK and void, of which I prefer the PK since it communicates the intent better.

Anton Gogolev
Agreed. boolean doesn't fit
Harry Lime
OK you've convinced me of the futility of returning boolean.
Jacques René Mesrine
Corollary: What would you do in a method that performs the D in CRUD ? It doesn't make sense to return the PK anymore. Would you return a void instead ?
Jacques René Mesrine
Number of rows deleted. Simple enough.
Adeel Ansari
@Vinegar That makes total sense!
Jacques René Mesrine
+4  A: 

I have traditionally used the approach to return the generated id or have no return value at all. But I am starting to like the idea of returning the added object itself, populated with generated PK. If the object has methods you can use the return value and invoke methods on it directly, or you can directly pass it along to some other method:

// invoke a method on the returned object
addAddress(theAddress).DoSomething();

// pass the object to some other method
SomeOtherMethod(addAddress(theAddress));

What I would not do is to use a boolean; a failure in the add method is an exceptional state and should be treated as such, throwing an exception.

Fredrik Mörk
A: 

If you like method chaining, you can return this:

dao
.addAddress (a1)
.addAddress (a2)
.addAddress (a3)
.addAddress (a4)
;
Aaron Digulla
+1  A: 

most of the time i return void. we use a persistence framework (Hibernate) which updates the primary key of the object, so there is no need to return it. When the insert does not succeed, an exception is thrown.

Method chaining is not needed when persisting object, but the suggestion of Aaron Digulla is also a good one if you need it.

Salandur