Is there a general rule of thumb, when we should pass a value as as class variable and when as a method argument? Or is it just a choice of the developer?
For example — are there any reasons, why following (PHP code):
class SomeClass
{
public function __construct()
{
$this->id = $_GET['id'];
$this->showMessage();
}
public function showMessage()
{
echo 'The ID is '.$this->id;
}
}
is better (or worse?) than this:
class SomeClass
{
public function __construct()
{
$this->showMessage($_GET['id']);
}
public function showMessage($id)
{
echo 'The ID is '.$id;
}
}
Note, that I’m only asking about differences between passing value as class variable vs. passing as method argument. Please, don’t point out, that I should never operate directly on superglobals in PHP. I know, that this is wrong. I used it here, to simplify the example.
If conceptually the value is part of the object’s state, it should be passed as a member field. If it’s only part of specific action of the method invocation, it should be passed as a method argument.
For example, let’s say objects of SomeClass
can be saved to a file. You’ll have a save
action and you need to pass the file’s path.
-
If you pass the path as a member field, it is now a part of the object state. That means that conceptually, the object is bound to that file. It would make sense then, for example, to load the object from the same file, to block other objects from saving to that file, to overwrite the file without confirmation etc.
-
If you pass the path as a method argument, it is not part of the object state. The object, after being saved, couldn’t care less about the file. In this case, it would make sense to save the object to different files(possible with incremental names), or to ask for confirmation if you save it again to the same file.
The choice, ofcourse, should depend on how the object relates to the value in each individual case.
0