Given that out and ref parameters have slight different connotations would writi
ID: 643741 • Letter: G
Question
Given that out and ref parameters have slight different connotations would writing code like below be considered a bug (even though it doesn't cause an issue at present), or just a lack of understanding on ref and out parameters?
public void MyMethod()
{
int myInt = 0;
MyMethodWithRef(ref myInt);
}
public void MyMethodWithRef(ref myInt)
{
// not used before being assigned a value. Does an out parameter make more sense then
myInt = 5;
}
I understand that this is the incorrect usage of ref but if you saw that in code constantly or even once would you consider it a bug and hence fix it as well as inform the original coder or just do it as part of general refactoring practices?
Explanation / Answer
It's not a bug in that the compiler won't flag it and given the existing code base, it will not cause a difference in behavior.
It is an issue that would be brought up in a code review or interview -- it is imprecise, it makes the next programmer ask "why", which if not a mortal sin is at least a venial sin. Is it left over from a copy/paste code reuse, a half implemented feature, part of an incomplete bug fix -- which way, changing from out to ref or vice-a-versa, is it necessary and I'm just not seeing it, is it a terrible mistake by someone that didn't know better and am I not seeing that....
Although I generally approve of extra restrictions, I'm not convinced that in practice this is a useful syntax -- that said, the language does make the distinction, and there's a cost to not following conventions. Not in terms of performance or scale, but in readability and maintainability.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.