Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ DAL - Return Reference or Populate Passed In Reference

[EDIT 1 - added third pointer syntax (Thanks Alex)]

Which method would you prefer for a DAL and why out of:

Car& DAL::loadCar(int id) {}
bool DAL::loadCar(int id, Car& car) {}
Car* DAL::loadCar(int id) {}

If unable to find the car first method returns null, second method returns false.

The second method would create a Car object on the heap and populate with data queried from the database. Presumably (my C++ is very rusty) that would mean code along the lines of:

Car& DAL::loadCar(int id)
{
    Car *carPtr = new Car();
    Car &car= *carPtr;
    car.setModel(/* value from database */);
    car.setEngineSize(/* value from database */);
    // etc
    return car;
}

Thanks

like image 421
ng5000 Avatar asked Oct 05 '09 13:10

ng5000


1 Answers

The second is definitely preferable. You are returning a reference to an object that has been new'd. For an end user using the software it is not obvious that the returned object would require deleting. PLUS if the user does something like this

Car myCar = dal.loadCar( id );

The pointer would get lost.

Your second method therefore puts the control of memory on the caller and stops any weird mistakes from occurring.

Edit: Return by reference is sensible but only when the parent, ie DAL, class has control over the lifetime of the reference. ie if the DAL class had a vector of Car objects in it then returning a reference would be a perfectly sensible thing to do.

Edit2: I'd still prefer the second set up. The 3rd is far better than the first but you end up making the caller assume that the object is initialised.

You could also provide

Car DAL::loadCar(int id);

And hope accept the stack copy.

Also don't forget that you can create a kind of null car object so that you return an object that is "valid"ish but returns you no useful information in all the fields (and thus is obviously initialised to rubbish data). This is the Null Object Pattern.

like image 161
Goz Avatar answered Nov 13 '22 06:11

Goz