Jump to content

Cleaner way to write long operator conditionals


Recommended Posts

I have a method where the operator condition started getting too long and was becoming difficult to understand and troubleshoot.

    private function validateCallbackRequest():self {
        if($this->params->xyz < 3 || isset($this->x->bla['hi']) || soOnAndSoOnAndSoOn) {
            throw new Exception('Invalid params');
        }
        return $this;
    }

I could break it into sections, but would rather not duplicate all the exception throwing.

    private function validateCallbackRequest():self {
        if($this->params->xyz < 3 || isset($this->x->bla['hi'])) {
            throw new Exception('Invalid params');
        }
        if(soOnAndSoOnAndSoOn) {
            throw new Exception('Invalid params');
        }
        return $this;
    }

I could assign variables, but don't really care for this all that much.

    private function validateCallbackRequest():self {
        $initialStuff=$this->params->xyz < 3 || isset($this->x->bla['hi']);
        $otherStuff=soOnAndSoOnAndSoOn;
        if($initialStuff || $otherStuff) {
            throw new Exception('Invalid params');
        }
        return $this;
    }


Thinking of maybe a while block and break, but not sure.

Any recommendations?

Link to comment
Share on other sites

Other than splitting them up on multiple lines to make it more readable, I don't think there is anything like what you are hoping for:

if (
   $something==$whoknows &&
   $somethingelse==$anything ||
   .
   .
   .
) {
   // do something
  };

 

Link to comment
Share on other sites

I tend to break it out into variables as it can help with readability quite a bit by giving a name to a particular condition.   For example:

$isRequired = $input->isRequired();
$isBlank = is_array($value) ? count($value) === 0 : trim($value) === '';
if ($isRequired && $isBlank){
	$Errors[] = $input->getLabel() . ' is required.';
}

Each condition now has an easy to understand name making it very clear what exactly is being checked for.  There's no need to try and parse the actual conditional code to figure it out.

It also allows for easy re-use of a particular condition.

$type = $input->getType();
$isRequired = $input->isRequired();
$isBlank = is_array($value) ? count($value) === 0 : trim($value) === '';
if ($isRequired && $isBlank){
	$Errors[] = $input->getLabel() . ' is required.';
} else if (!$isBlank && $type === CourseFormInput::SINGLE_CHOICE){
	//Check if $value is a valid option
} else if (!$isBlank && $type === CourseFormInput::MULTI_CHOICE){
	//Check if $value array contains all valid options.
}

$isBlank can be easily used repeatedly for each branch.

If a set of conditions gets particularly complicated or is checked frequently I may just make a separate method for that condition.

private function isEmptyInstitution($data){
  return !$data['name'] && !$data['address1'] && !$data['address2'] && !$data['city'] && !$data['country']
    && !$data['state'] && !$data['start_month'] && !$data['start_year']
    && !$data['end_month'] && !$data['end_year'] && !$data['credits'] && !$data['degree'];
}

 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.