Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

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.

share|improve this question

1 Answer 1

up vote 4 down vote accepted

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.

share|improve this answer
    
+1 for "conceptually". –  rem Feb 24 at 12:23

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.