Question

I am writing a class that has lots of getters and setters and was wondering on what people thought about the following:

The normal way is to code like the following:

public function setChangeSort($changeSort)
{
    self::$changeSort = $changeSort;
}

public function getChangeSort()
{
    return self::$changeSort;
}

What are your opinions on doing the following:

public function setChangeSort($changeSort) { self::$changeSort = $changeSort; }
public function getChangeSort() { return self::$changeSort; }

I have no problem doing it the orginal way, as that is how it shoul be done. It just seems to take up alot of space in my classon functions that are really obvious in what they do.

Thanks in advance.

Was it helpful?

Solution

One-line conditional blocks are fine if they're consistent, obvious and intuitive, although I'd encourage spacing them carefully so it's immediately obvious that they are functions rather than some single line of code!

OTHER TIPS

I would go with the "one-line" variation. But only if all it does is setting and getting a value. if you add a check for null or any other validation, or doing anything other than getting or setting I would go with the first and longer variation to keep the code more readable.

I usually threat one-line methods in the same way as the other methods. I don't mind my source code to be N-lines longer if it means it is more readable and maintainable.

I would also suggesto to checkout the following document http://framework.zend.com/manual/en/coding-standard.html IMHO it's the best PHP coding standard reference available so far.

I think magic getters/setters of PHP5 are really helpful when dealing with numerous getters/setters.

http://fr.php.net/manual/en/language.oop5.overloading.php#language.oop5.overloading.members

And an example.

<?php
class A {
  private $properties = array();

  public function __set($key, $value) {
    if (is_array($value)) {
      $this->$key = $value;
    } else {
      $this->properties[$key] = $value;
    }
  }

  public function __get($key) {
    if (array_key_exists($key, $this->properties)) {
      return $this->properties[$key];
    }

    return null;
  }
}
?> 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top