How to implement isValid correctly?
        Posted  
        
            by 
                Songo
            
        on Programmers
        
        See other posts from Programmers
        
            or by Songo
        
        
        
        Published on 2012-10-11T19:59:06Z
        Indexed on 
            2012/10/11
            21:47 UTC
        
        
        Read the original article
        Hit count: 279
        
I'm trying to provide a mechanism for validating my object like this:
class SomeObject {
    private $_inputString;
    private $_errors=array();
    public function __construct($inputString) {
        $this->_inputString = $inputString;      
    }
    public function getErrors() {
        return $this->_errors;
    }
    public function isValid() {
        $isValid = preg_match("/Some regular expression here/", $this->_inputString);
        if($isValid==0){
            $this->_errors[]=  'Error was found in the input';
        }
        return $isValid==1;
    }
}
Then when I'm testing my code I'm doing it like this:
    $obj = new SomeObject('an INVALID input string');
    $isValid = $obj->isValid();
    $errors=$obj->getErrors();
    $this->assertFalse($isValid);
    $this->assertNotEmpty($errors);
Now the test passes correctly, but I noticed a design problem here. What if the user called $obj->getErrors() before calling $obj->isValid()?
The test will fail because the user has to validate the object first before checking the error resulting from validation. I think this way the user depends on a sequence of action to work properly which I think is a bad thing because it exposes the internal behaviour of the class.
How do I solve this problem?
Should I tell the user explicitly to validate first? Where do I mention that?
Should I change the way I validate?  Is there a better solution for this?
UPDATE:
I'm still developing the class so changes are easy and renaming functions and refactoring them is possible. 
© Programmers or respective owner