Consider an object passed (by reference) into a method, which then modifies the object. Should the method return the object on completion?
Well, it’s redundant. Here’s why.
There are two approaches to doing this – the classic way (caller chooses what to manipulate/change), and callee changes (which is what happens when you pass in an object by reference:
- If the caller chooses what to manipulate, then your method will operate on a copy of the dataset, and return that copy, leaving the original untouched. Then the caller may overwrite the original, if desired. Many array operations in Perl work like this.
- The alternative lets the called method do the in-place operation, in which case the return value is more typically a boolean (“Yes, I’ve succeeded!”) or an int containing the number of values affected. This is how database updates work.
Of course, if the object is not passed by reference (i.e. a copy is passed into the method) or if the method explicitly returns a modified copy, then returning an object is the right way to do it.