1

This might sound crazy but hear me out...

I have a method that violates https://rules.sonarsource.com/csharp/RSPEC-4457

Parameter validation in "async"/"await" methods should be wrapped

...split the method into two: an outer method handling the parameter checks (without being async/await) and an inner method to handle the iterator block with the async/await pattern...

An async Task that checks the arguments and performs async logic

So I've split the method into two as it suggests, one checking for null arguments and one performing the logic

private Task ThisMethod(string value) {
    if(value == null)
      throw new ArgumentException(nameof(value));

    return ThisMethodAsync(value);
}

private async Task ThisMethod(string value) {
    //async logic
}

The problem I now have is that really I don't want that second method to ever be called in isolation as the checks won't be performed, I want it to be one logical method but have split as suggested

Is there a way to limit this second method from being called at all unless being called from the first method? A nifty attribute I'm unaware of perhaps? A stricter than private access modifier?

Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
Steji
  • 580
  • 1
  • 6
  • 17
  • 1
    Create a class and add them there, make the first public and the other private – Tim Schmelter Jul 08 '21 at 15:59
  • 3
    Make it local (nested) function... (that would be an answer to non-Sonar question... but I have no idea how bad Sonar would throw up on such code) – Alexei Levenkov Jul 08 '21 at 16:03
  • 3
    Personally I would ignore or even disable this particular rule. The proposed solution is in my opinion worse than the actual issue and raises an issue you perfectly described. [Peter has a nice post on that](https://stackoverflow.com/a/56909963/941240). – Wiktor Zychla Jul 08 '21 at 16:47
  • 1
    You could analyze the call stack and throw an exception if the caller isn't the intended method (This was a joke). – lidqy Jul 08 '21 at 17:30

0 Answers0