Answer the question
In order to leave comments, you need to log in
One "multifunctional" method or several?
There are two options for writing methods:
Functionality in multiple methods
public function setGlobal($name, $value)
{
$this->globals[$name] = $value;
}
public function hasGlobal($name)
{
return array_key_exists($this->globals, $name);
}
public function getGlobal($name)
{
if ($this->hasGlobal($name)) {
return $this->globals[$name];
}
return false;
}
public function setGlobals(array $array)
{
$this->globals = array_merge($this->globals, $array);
}
public function getGlobals()
{
return $this->globals;
}
public function globals($name = null, $value = null)
{
// Слияние массивов с заменой
if (is_array($name)) {
return $this->globals = array_merge($this->globals, $name);
}
// Передача всего содержимого
if ($name === null && $value === null) {
return $this->globals;
}
// Проверка на наличие и передача переменной из массива
if ($name !== null && $value === null) {
if (array_key_exists($name, $this->globals)) {
return $this->globals[$name];
}
return false;
}
// Запись переменной
if ($name !== null && $value !== null) {
return $this->globals[$name] = $value;
}
}
Answer the question
In order to leave comments, you need to log in
The first is because it is clearly written which method does what, and not the passed parameter determines what the method should do.
When parsing this code, you will have to study the method (or its documentation) very carefully, and only then work.
And the getter and setter are methods that are obvious to all programmers with familiar behavior.
In addition, instead of working directly, the interpreter will be forced to decide based on the parameters, but what should it do now?
And it will be inconvenient to use this thing - we wanted to read something into a non-empty variable, so we must first reset this variable, and only then call your miracle method. What if we forgot to do it? So the method will do the opposite, and corrupt the data - you get a subtle error.
The second solution is badcode. Never do this.
Code with the assumption that all programmers who will maintain your program are violent psychopaths who know where you live.
Martin Golding
In your case, the first one, because it is much more correct in terms of code purity and application building principles. This option is easier to maintain, a system with such a structure is easier to extend, and it will be easier for a third-party developer to find the right place in the code and understand what it refers to. However, indeed, sometimes it is necessary to create a multifunctional method, i.e. depends on the situation.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question