Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Independent getter/setter methods, or combined?

While working on a project, I've been making some changes and browsing around existing framework API docs for insight.

While perusing the Kohana docs, I noticed that the getters/setters of any given class are typically combined:

public function someProperty($value = null){
    if(is_null($value){
        return $this->_someProperty;
    }
    $this->_someProperty = $value;
    return $this;
}

Rather than:

public function setSomeProperty($value){
    $this->_someProperty = $value;
    return $this;
}

public function getSomeProperty(){
    return $this->_someProperty;
}

Is there any value in doing this (the former), beyond lessening the method count of a given class? I was always under the understanding that methods (functions in general) should be more descriptive of an action. Do other experienced developers cringe, even a tiny bit, when they see this?

I was just surprised to see a popular framework use such conventions (I haven't used Kohana of course)

like image 633
Dan Lugg Avatar asked Jul 13 '11 06:07

Dan Lugg


Video Answer


2 Answers

I consider this bad practise because it violates CommandQuerySeparation. Setting a value is changing state (Command). Getting a value is asking for state (Query). A method should not do both, but one thing only.

Also, it's not really obvious what a method does when it's just called username, e.g. does not have a verb, like get or set. This gets even worse in your example, because the return value is either the object itself or the property value, so its not consistent.

Moreover, getters (and setters) should be used sparingly as they will quickly convolute your API. The more getters and setters you have, the more knowledge about an object is required by collaborators of that object. If you find your objects asking other objects about their internals, chances are you misplaced the responsibilities.

like image 124
Gordon Avatar answered Sep 29 '22 02:09

Gordon


jQuery goes the same way as Kohana. However I think it's better to create separate methods for setting and getting. It's more obvious what the method does and I think it's more practically in code-completition in your ide. For example you type set and you get a list of all Properties you can set.

Another disadvantage is: what if you want to set a value really to null? This wouldn't work since the null is the identifier for returnin the value, you are restricted in setting specific values...

So it's nice, since you'll have to write less, but hey what are three letters (set/get) in front of your methods?

like image 22
Fidi Avatar answered Sep 29 '22 02:09

Fidi