Search code examples
phpoopsingle-responsibility-principle

Unexpected output on a ANDING boolean expression in a class and a single if statement


I wrote a function for getting data out of a array. A part in that function is verification of the data, it checks if the key is NOT empty and if the array key does NOT exists (my bad after the edit). The function looks like this:

public function getData($key = "")
{
    if (!empty($key) && !array_key_exists($key, $this->data)) {
        throw new ConfigurationException("$key does not exist");
    }
    return empty($key) ? $this->data : $this->data[$key];
}

After applying the SRP princple, by putting the 'verification' into another class, it looked like this:

class ConfigurationVerificationHandler
{

    public function isPresent($key, array $data)
    {
        return empty($key) && array_key_exists($key, $data);
    }
}

public function getData($key = "")
{
    $verificationHandler = new ConfigurationVerificationHandler();
    if (!$verificationHandler->isPresent($key, $this->data)) {
        throw new ConfigurationException("$key does not exist");
    }
    return empty($key) ? $this->data : $this->data[$key];
}

From both of these snippets, I expected the same result, because I put the ! operator before the isPresent function, making it check if the condition is false.

How does this come the boolean expressions are not the same and dont give the same result?


Solution

  • !A && !B is not the same as !(A && B). One only has to look at the case where one variable is true (let's pick A) and the other is false:

    !true && !false --> false && true --> false
    
    !(true && false) --> !(false) --> true
    

    However, !A && !B is equivalent to !(A || B):

    !(true || false) --> !(true) --> false