I have an object and it is passed to a method to be altered. This sort of behaviour seems quite rare so I want to make sure that other developers don't trip up on it and it's easy to see. Is there anything I can do to make it obvious what's happening?
The method adjusts some properties on the object, but it doesn't return the object. Perhaps it should return it?
myObject = Processor(myObject);
would be redundant, but it would make it clearer...?
The only thing I can think of is adding ref
before it in the interface but not sure if that's a good idea or not. Any ideas?
No, returning the same reference doesn't make it clearer - in some cases such a method would be expected to clone the object and return a different version, e.g.
string Escape(string input)
Indeed, because a void
method can't return anything, its very existence pretty much guarantees there will be side-effects. It doesn't state whether the side-effects will be on the target of the call or on a reference, but at least it implicitly highlights that you should think what the side-effects will be. A method returning a value could very easily be side-effect free.
Likewise using ref
is just wrong - that suggests you want to be able to change the caller's variable to refer to a different object, which is in no way the same thing as modifying the data within an existing object. It gives the wrong impression.
Ultimately, there are two approaches to this:
See more on this question at Stackoverflow