1

In TrainBoardingCard we have setTrainCode is it ok to use $this->trainCode = $trainCode inside constructor or we shoud always use setTrainCode like $this->setTrainCode($trainCode); as it could have some logic in future.

For both case what are the pros and cons? please let us know your preference with reasons.

class TrainBoardingCard extends BoardingCard
{
    /**
     * @var string
     */
    private $trainCode;

    /**
     * @param string $trainCode
     */
    public function __construct(string $trainCode)
    {
        $this->trainCode = $trainCode;
    }

    /**
     * @return string
     */
    public function getTrainCode(): string
    {
        return $this->trainCode;
    }

    /**
     * @param string $trainCode
     */
    public function setTrainCode(string $trainCode)
    {
        $this->trainCode = $trainCode;
    }
}
php.khan
  • 1,224
  • 1
  • 12
  • 21

1 Answers1

1

It depends.

You could say there are two different schools of thought and they both deal with both setters and constructors.

  1. The object must be created already valid state. This state can be changed with atomic operation from one valid state to another. This means, that you class doesn't actually have simple setters per se.

    $client = new Client(
        new FullName($name, $surname),
        new Country($country);
        new Address($city, street, $number));
    
    // do something
    
    $client->changeLocation(
        new Country('UK'),
        new Address('London', 'Downing St.', '10'));
    
  2. Constructor is used only do pass in dependencies and not to impart state. The object's state by default is blank and it gets changed only by using setters externally.

    $client new Client();
    $client->setId(14);
    
    $mapper = new DataMapper(new PDO('...'), $config);        
    $mapper->fetch($client);
    
    if ($client->getCity() === 'Berlin') {
        $client->setCity('London');
        $mapper->store($client);
    }
    

Or you can have a mix or both, but that would cause some confusion.

Not sure if this will make it better for you or worse :)

tereško
  • 58,060
  • 25
  • 98
  • 150
  • one thing still not clear to me, inside constructor can we do this $this->trainCode = $trainCode; or should always do $this->setTrainCode($trainCode); if we have setter(may be setter can have some logic in future may be not). – php.khan May 31 '17 at 10:07
  • If what you are passing in the constructor are dependencies (as in, other objects), then this is not necessary. If you are passing values (or value objects), then using setters would be a good idea. – tereško May 31 '17 at 10:09
  • Thanks for mentioning both cases, now it's making sense to me. – php.khan May 31 '17 at 10:19