hdoghmen
hdoghmen

Reputation: 3422

Putting condition inside or outside method

I have to choose between two designs which do exactly the same thing.
Which one would be better from maintenance effort perspective ? SRP violation ?

Design #1

if(ConditionVerified())
{
    Process();
}

public void Process()
{     
    // Do a lot of work ...
}

Design #2

Process();

public void Process()
{
   if(ConditionVerified())
   {
        DoProcess();
   }    

}

public void DoProcess()
{
    //Do a lot of work ...
}

Upvotes: 6

Views: 1594

Answers (2)

Quintin B
Quintin B

Reputation: 5881

Since your method has no return type for an error / success condition, I would recommend you use Design #1.

However if you are doing a lot of work you should consider how a failure or a pre-execution condition may affect the operation. In which case you should go with Design #2.

Personally I default to #2 because I like to keep all pertinent logic contained, however there are good reasons NOT to go with #2:

  • You don't need the variables for anything other than performing the validation
  • You use the method somewhere else and the conditional logic is not required

Upvotes: 0

steenbergh
steenbergh

Reputation: 1761

If process can be started from multiple places in your code, and condition always follows the same requirements, then option #2 might be a viable design. In all other cases, the extra hop is un-useful and I would stick with #1.

Upvotes: 1

Related Questions