5

Which structure of writing code is better and why?

if (!file_exists('file.txt')) {
   throw new Exception();
} else {
   //operations
}

or

if (!file_exists('file.txt')) {
   throw new Exception();
} 
//operations

?

I did not find this in PSR documentation.

2 Answers2

14

What your describing in your second code example is a Guard Clause.

Guard clauses exist to help you avoid excessive nesting of conditions, which are hard to maintain and difficult to read:

if ()
{
    throw;
}
else
{
    if()
    {
        return;
    }
    else
    {  
         if()
         {
             log and return;
         }
         else

Writing guard clauses allows you to keep your conditions separated:

if()
{
    throw;
}

if()
{
    return;
}

if()
{
    log and return;
}

// Do actual work

Each guard clause can identify a specific condition or do specific cleanup work prior to exiting the function.

Further Reading
Replace Nested Conditional with Guard Clauses

Robert Harvey
  • 200,592
-1

I would apply separations of concern.

Your example shows two responsibilities: checking the preconditions and doing actual work. I would put them in separate methods:

throwIfFileFailsChecks(file);
workWithFileContent(file);

The latter may be split up in even more methods having dedicated "concerns".