Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Defaulting to passing reference types using the ref keyword [closed]

Tags:

c#

I work with a developer who defaults to passing reference types such as StringBuilder, string and MemoryStream using the ref keyword. They do this regardless of whether they need to actually change the reference itself.

public void ExampleMethod(ref MemoryStream ms)
{
    byte b=ms.ReadByte();
    ...
    // No changing of actual ms reference such as: ms=new MemoryStream();
}  

Almost always, the methods just use the object and return without changing the reference in any way. For the immutable types ie string, this is sometimes necessary, but why for the mutable types?

To me this has a bit of a "code smell" in that it could lead to less maintainable code in that it is more permissive than what it really needs to be.

However is this something that is serious enough for me to bring up with the developer? My intial feeling is yes, but maybe this is too pedantic?

like image 756
Ash Avatar asked Nov 28 '22 10:11

Ash


1 Answers

Perhaps you could ask that developer why he does that ... Maybe he (wrongly) thinks it is more performant ? Maybe that developer is a C++ developer, who thinks that using ref is similar as using a pointer in C++ ?

If he comes from a C++ background, I would ask the developer why he does that, and explain to him that this is totally not necessary. That it does not improve performance, and that it instead gives different semantics to the method, since it allows to change the reference, and that you should only use the ref keyword when it is indeed necessary that the method can change the reference.

I don't think it is pedantic. Even an experienced developer doesn't know all the in and outs of a new language he's using. When you explain it to him, he will learn something new, and maybe he'll be gratefull. :)

like image 68
Frederik Gheysels Avatar answered Nov 30 '22 22:11

Frederik Gheysels