views:

41

answers:

3

In terms of "good code", is it acceptable to combine set and get methods into one? Like this:

public function dir($dir=null) {
    if (is_null($dir)) return $this->dir; 
    $this->dir = $dir; 
}
A: 

My initial thought is no the code is harder to read and therefore maintain. I have gotten to where I either use C#'s auto property or just a public field.

mpenrow
A: 

This pattern is at least very common in jQuery; I'd say it is fine.

Andrea
*Almost* this pattern, but it is not. jQuery check if the parameter is undefined, not null. You get a different behavior if you do `$('elem').attr('foo', null)` than `$('elem').attr('foo')`. That's because javascript distinguishes between `undefined` (no parameter) and `null` (parameter with no value). So, in this case is OK, but I won't say it is for the rest of the languages.
Chubas
Just for completeness of my comment: see http://code.jquery.com/jquery-latest.js, line 795, where the `access` function is defined.
Chubas
@Andrea, @Chubas, I wouldn't say that was "almost" this pattern at all. The difference between undefined and null in javascript is pretty huge, making this completely different, if superficially similar in the pattern of words on the screen.
Jon Hanna
Yes, I know jQuery uses undefined. Other languages will not have two distinct types (undefined and null), so the pattern will only work under the assumption that one does not want to explicitly set a value to null.
Andrea
+1  A: 

It's pretty dreadful. It makes it impossible to set the value to null, for one thing.

In a language that distinguished undefined from null, then it would be reasonable to do this with that undefined value, rather than null.

The mismatch between something being returned or not isn't even valid in many languages. In either case, why not return it anyway, to allow reasonable chaining of x.dir = y.dir = someValue? But that's a nick-pick, my first paragraph is my main answer.

Jon Hanna