php - method can return an error or an array - bad implementation? -
i'm reading code complete , there statement in warns against using variable double purpose, example:
1) if variable number, contains error code. 2) if varibale array, contains data.
and that's i'm doing in program variable $text
in code snippet below:
$text = $editor->gettextforlinking($data_array['idtext']); if (arr::is_array($text)) { ... } else { log::instance()->add(log::error, $text); $this->response->body("text can't retrieved"); }
i have access method gettextforlinking() can changed. how can changed exclude undesirable situation double purpose?
i don't want use exceptions this:
$text = array(); try { $text = $editor->gettextforlinking($data_array['idtext']); } catch(someexception $e) { log::instance()->add(log::error, $text); $this->response->body("text can't retrieved"); }
i think clear if returned gettextforlinking()
, not array, should considered error (logged) - i'm not entirely convinced example warrants such change.
with said might improvement keep return signature of function same data type
(array) regardless of data send it. way consistent (you loose need $text = array();
) , wont have make special cases depending on if error or not.
$results = $editor->gettextforlinking($data_array['idtext']); if (empty($results)) { log::instance()->add(log::error, $data_array['idtext']); } else { // handle results array }
update
if setting error message within function, violates single responsibility principle - function/method should have 1 job. far $editor->gettextforlinking()
concerned return array of text, not deal return of error.
the error message should depend on context (where method used). if @ point empty array invalid handle/set error (message) outside of function have shown above.
doing way allows $editor
oblivious of validity of returned result , allow reuse function elsewhere empty array not considered error.
Comments
Post a Comment