Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best practice when having a terminate clause...see explanation :)

Tags:

c#

The case goes as following: You have a Boolean property called FullScreenEnabled. You enter some method, and the code within this method is executed iff FullScreenEnabled is true. Which of the 2 approaches below do you use in your everyday programming:

    private bool FullScreenEnabled { get; set; }
    // Check if FullScreenEnabled is false and return;
    private void Case1()
    {
        if (FullScreenEnabled == false)
        {
            return;
        }

        // code to be executed goes here!
    }

    // Surround the code by an if statement.
    private void Case2()
    {
        if (FullScreenEnabled)
        {
            // code to be executed goes here!
        }
    }
like image 712
Kiril Stanoev Avatar asked Dec 07 '22 09:12

Kiril Stanoev


2 Answers

private void MyMethod(bool arg){
   if(arg)
       return;
   //do stuff
};

(for voting)

like image 56
Oskar Avatar answered Dec 09 '22 22:12

Oskar


I generally prefer the first version (bailing at the start of the method). It leads to less nesting, which slightly increases readability. Should you decide you don't need to check for the condition in the future, it's also easier to remove the if condition in the first version, especially if you have several such checks. Plus, it could be easily be written in a single line: if (!FullScreenEnabled) return;

like image 41
Firas Assaad Avatar answered Dec 09 '22 23:12

Firas Assaad