Java – Coding style issue: Should we have functions which take a parameter, modify it, and then RETURN that parameter

ccoding-stylejavamethod-chaining

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?

Best Answer

This really is a matter of opinion, but for what it's worth, I find it misleading to return the modified item if the item is modified in place. Separately, if predictPrice is going to modify the item, it should have a name that indicates it's going to do that (like setPredictPrice or some such).

I would prefer (in order)

  1. That predictPrice was a method of Item (modulo a good reason for it not to be, which there could well be in your overall design) which either

    • Returned the predicted price, or

    • Had a name like setPredictedPrice instead

  2. That predictPrice didn't modify Item, but returned the predicted price

  3. That predictPrice was a void method called setPredictedPrice

  4. That predictPrice returned this (for method chaining to other methods on whatever instance it's a part of) (and was called setPredictedPrice)