Following my other question, is there a general rule of thumb, when we should pass a setting-like value, that controls class’ behavior (for example displayed texts) as as class’ constant or variable, one-by-one, and when it is better to “pack” them to one associative array? Or is it just a choice of the developer?
For example — is this approach better (PHP code):
class SomeClass
{
public $errorIncorrectProtocol = 'Please, don't use GET protocol in this context!';
public $errorMissingId = 'The ID can't be empty or equal zero...';
}
than this one:
class SomeClass
{
public $errorMessages = array
(
'IncorrectProtocol'=>'Please, don't use GET protocol in this context!',
'MissingId'=>'The ID can't be empty or equal zero...'
);
}
and if yes — then, why?
A good practice here (in PHP at least) is to use a combination of constants and arrays. To follow your error messages example:
class SomeClass {
const ERR_INCORRECT_PROTOCOL = "incorrectProtocol";
const ERR_MISSING_ID = "missingId";
public $errorMessages = array(
self::ERR_INCORRECT_PROTOCOL => "Please, don't use GET protocol in this context!",
self::ERR_MISSING_ID => "The ID can't be empty or equal zero..."
);
}
Error messages can then easily be retrieved:
$someObj = new SomeClass();
$someObj->errorMessages[SomeClass::ERR_INCORRECT_PROTOCOL];
Generally speaking, I don’t think having individual variables in this context provides any benefits over using a constants and arrays. Instead, it simply clutters the internals of your class, or worse (if they’re publicly exposed) clutters your API and possibly confuses developers (what’s this errorMissingId
? Is it some error object? A string? Is it safe to change? Do I need it?)
2