I have a class that does something, and when it’s done it returns true, but if any of the various things go wrong it will return false. Now my question is, should status messages for such events be kept inside a class (Example1) or outside the class (Example2) where class maybe only provides error code to help distinguishing what happened.
class Example1 {
private $var;
private $status;
public function doSomething($var) {
$this->var = $var;
if (!is_numeric($this->var)) {
$this->status = 'Please provide a number';
return false;
}
if (empty($this->var)) {
$this->status = 'Please fill the field';
return false;
}
$this->status = 'Ok, you submitted a number, cool.';
return true;
}
function getStatus() {
return $this->status;
}
}
example 2:
class Example2 {
private $var;
public function doSomething($var) {
$this->var = $var;
if (!is_numeric($this->var)) {
return false;
}
if (empty($this->var)) {
return false;
}
return true;
}
}
Example 1 seems to me more convenient to use, code reads like a poem, but at the same time seems less reusable, depending on what you use class for, you might want success/error messages to have different syntax.
So basically my question would be what’s the usual practice?
First example: you hard code error messages which is… bad. And you can’t see the error message if you don’t check
$object->statuslater.Second example: if something goes wrong, you know it but you don’t know why.
I suggest avoiding both these ways and throwing exceptions for a more object oriented approach (I guess that’s what you want, since you’re using classes :).