I'm having a bit of a debate with my friend over whether these two practices are merely two sides of the same coin, or whether one is genuinely better.
We have a function which takes a parameter, fills out a member of it, and then returns it:
Item predictPrice(Item item)
I believe that as it works on the same object that is passed in, there is no point going on to return the item. In fact, if anything, from the perspective of the caller, it confuses matters as you could expect it to return a new item which it doesn't.
He claims that it makes no difference, and it wouldn't even matter if it did create a new Item and return that. I strongly disagree, for the following reasons:
If you have multiple references to the item passes in (or pointers or whatever), it allocating a new object and returning it is of material importance as those references will be incorrect.
In non-memory managed languages, the function allocating a new instance claims ownership of the memory, and thus we would have to implement a cleanup method which is called at some point.
Allocating on the heap is potentially expensive, and therefore it is important to whether the called function does that.
Hence, I believe it to be very important to be able to see via a methods signature whether it modifies an object, or allocates a new one. As a result, I believe that as the function merely modifies the object passed in, the signature should be:
void predictPrice(Item item)
In every codebase (admittedly C and C++ codebases, not Java which is the language we are working in) I have worked with, the above style has essentially been adhered to, and kept to by considerably more experienced programmers. He claims that as my sample size of codebases and colleagues is small out of all the possible codebases and colleagues, and thus my experience is no true indicator over whether one is superior.
So, any thoughts?
Item
isclass Item ...
and nottypedef ...& Item
, the localitem
is already a copy