-4

What is the best way to return result after first false validation. I would like to achieve same functionality without checking for result after each validation.

bool ValidateMany()
{
  bool result=true;

  if(ValidateFirstProperty){
  result = ValidateFirst();
  if(result == false)
    return result;
  }

  if(ValidateSecondProperty){
  result=ValidateSecond();
  if(result == false)
    return result;
  }

  //always validate third one
  result=ValidateThird();
  if(result == false)
    return result;

return result;
}
bugrasitemkar
  • 431
  • 1
  • 7
  • 26
  • https://stackoverflow.com/questions/4820610/is-relying-on-short-circuiting-safe-in-net may be worth a read if you haven't seen `&&` before. – mjwills Jul 18 '19 at 14:37
  • 4
    That is inappropriate @bugrasitemkar. You just changed the question **markedly**, wasting the time of all people who wrote answers for the **original question**. This isn't a game of 'guess how the question will change'. – mjwills Jul 18 '19 at 14:40
  • Sorry I just realized this is the way I should write at the beginning and changed my pseudocode. Yes it is the final question. – bugrasitemkar Jul 18 '19 at 14:43
  • 1
    `if (ValidateFirstProperty && !ValidateFirst) return false;` will get you started. You can get your code down to three lines with that approach. It can be shorter using `||` but honestly I think readability will suffer. – mjwills Jul 18 '19 at 14:44

4 Answers4

5

You can put them all in the same if block, it will only move on to the next && if the previous does not match the criteria.

bool ValidateMany()
{
  if(ValidateFirst() && ValidateSecond() && ValidateThird())
  {
      return true;
  }

  return false;
}

Or combine them into one line.

bool ValidateMany()
{
   return ValidateFirst() && ValidateSecond() && ValidateThird();
}
mjwills
  • 23,389
  • 6
  • 40
  • 63
andyb952
  • 1,931
  • 11
  • 25
  • Thanks :) - For reference: https://learn.microsoft.com/en-gb/dotnet/csharp/language-reference/operators/boolean-logical-operators#conditional-logical-and-operator- – andyb952 Jul 18 '19 at 14:40
4

I could try this :

        bool ValidateMany()
        {
            return  ValidateFirst() && ValidateSecond() && ValidateThird();
        }
JeePakaJP
  • 830
  • 7
  • 21
3

After you have changed the question this is the short version:

return (!ValidateFirstProperty  || ValidateFirst())
    && (!ValidateSecondProperty || ValidateSecond())
    && ValidateThird();

But you will lose the information which validation failed, in case you want to output or log it.

Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
1

This is cleaner version:

return ValidateFirst() && ValidateSecond() && ValidateThird();

Cheaker
  • 89
  • 8