0

As PHP 7.4 supports typed class properties: https://www.php.net/manual/en/migration74.new-features.php#migration74.new-features.core.typed-properties. Looks like a lot of code could be eliminated, in particular getters and setters that in entities and DTOs that was responsible for controlling properties types. For example such snippet:

class Foo implements BarInterface
{
    /**
     * @var int
     */
    protected $id;

    /**
     * @var int|null
     */
    protected $type;

    /**
     * @return int
     */
    public function getId(): int
    {
        return $this->id;
    }

    /**
     * @param int $id
     * @return $this
     */
    public function setId(int $id)
    {
        $this->id = $id;

        return $this;
    }

   /**
     * @return int|null
     */
    public function getType(): ?int
    {
        return $this->type;
    }

    /**
     * @param int|null $type
     * @return $this
     */
    public function setType(?int $type)
    {
        $this->type = $type;

        return $this;
    }
}

Can be refactored to:

class Foo implements BarInterface
{
    public int $id;

    public ?int $type;
}

Am I right that this is good idea? What should I take into consideration while making such refactoring?

Artem Khodos
  • 172
  • 1
  • 12
  • No it is no good idea to make properties of a class public – Jens Mar 03 '20 at 13:51
  • @Jens Some arguments why? While searched found the article where the author proposes to do in common the same things I suppose to do https://itnext.io/php-7-4-setters-and-getters-have-died-2cefa996d26 – Artem Khodos Mar 03 '20 at 14:33
  • 1
    https://softwareengineering.stackexchange.com/questions/143736/why-do-we-need-private-variables – Jens Mar 03 '20 at 14:36
  • The argument of incapsulation for objects is clear, however, for DTO's https://stackoverflow.com/questions/10831314/dtos-properties-or-fields – Artem Khodos Mar 03 '20 at 17:35
  • The consideration for anything public is the assumption something unintended will interact with it at some point and there is a high chance it will be difficult to identify the complexer a system gets. Simple systems may not require this design best practice. – Ryan Rentfro Sep 05 '20 at 23:10
  • I'd say it's not the time yet. I can recommend this article PHP Typed Properties: Think Twice (https://dev.to/mindplay/php-typed-properties-think-twice-3824) and comments below it. – piotr_cz Feb 09 '21 at 09:47

0 Answers0