Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it necessarily bad style to ignore the return value of a method

Tags:

c#

.net

Let's say I have a C# method

public void CheckXYZ(int xyz) {
  // do some operation with side effects
}
Elsewhere in the same class is another method
public int GetCheckedXYZ(int xyz) {
  int abc;
  // functionally equivalent operation to CheckXYZ, 
  // with additional side effect of assigning a value to abc
  return abc; // this value is calculated during the check above
}
Is it necessarily bad style to refactor this by removing the CheckXYZ method, and replacing all existing CheckXYZ() calls with GetCheckedXYZ(), ignoring the return value? The returned type isn't IDisposable in this case. Does it come down to discretion?

EDIT: After all the responses, I've expanded the example a little. (Yes, I realise it's now got out in it, it's especially for @Steven)

public void EnsureXYZ(int xyz) {
  if (!cache.ContainsKey(xyz))
    cache.Add(xyz, random.Next());
}
public int AlwaysGetXYZ(int xyz) {
  int abc;
  if (!cache.TryGetValue(xyz, out abc))
  {
    abc = random.Next();
    cache.Add(xyz, abc);
  }
  return abc;
}
like image 653
Jono Avatar asked Jan 19 '26 15:01

Jono


1 Answers

It entirely depends upon what that return value is telling you and if that is important to know or not. If the data returned by the method is not relevant to the code that is calling it then ignoring it is entirely valid. But if it indicates some failure/counter/influential value then ignore it at your peril.

like image 99
Ira Rainey Avatar answered Jan 22 '26 06:01

Ira Rainey