I’m trying to improve FxCop compliance in my code (for the first time ever), but I’m a little stuck on an ethical issue. I have a method GetText() that returns a string from a remote server, but can throw an exception under certain circumstances. Which is why I also have a method TryGetText(ByRef text As String) that returns a boolean which indicates whether the call was successful. The return value is assigned to the text variable if true.
I thought this construction was perfectly acceptable, considering that even Microsoft does it (e.g. Integer.TryParse).
FxCop is tut-tutting me though, dictating “Thou shalt not pass by reference!”
To circumvent this warning (and there are quite a few of them), I replaced the parameter with a StringBuilder. But despite now being compliant, I don’t think it really improved my code in any way.
Before:
Public Function TryGetText(ByRef text As String) As Boolean
Dim command As New GetTextCommand(Me)
Dim result As CommandResult = ProcessCommand(command, True)
If result.CommandStatus <> Constants.Status.Failed Then
text = result.Text
Return True
Else
Return False
End If
End Function
After:
Public Function TryGetText(builder As Text.StringBuilder) As Boolean
Dim command As New GetTextCommand(Me)
Dim result As CommandResult = ProcessCommand(command, True)
If result.CommandStatus <> Constants.Status.Failed Then
builder.Clear()
builder.Length = result.Text.Length
builder.Append(result.Text)
Return True
Else
Return False
End If
End Function
Is this acceptable use of ByRef, or should I use the stringbuilder alternative? I’m not feeling very comfortable about suppressing this warning for every method where I use this construct. I don’t feel like the stringbuilder variant improved code usability either.
Well, I think everybody hates too many byrefs. Two are already too many. Although in your case having many methods and they all follow the same pattern does not sound like a real issue.
You have the option to not stick to Microsoft’s pattern of Try* methods.
Instead of a Boolean, why not returning the string if successful or Nothing/Empty if it fails?
Then you can test your TryGetText output with String.IsNullOrEmpty(resultText).
It’s more code, indeed, but it does solve the warning (if that’s really what you’re after).