Skip to content

Instantly share code, notes, and snippets.

@ludofleury
Created March 29, 2022 11:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ludofleury/0964ac576d776a30025f2414dd0742c5 to your computer and use it in GitHub Desktop.
Save ludofleury/0964ac576d776a30025f2414dd0742c5 to your computer and use it in GitHub Desktop.
<?php
use DateTimeImmutable;
use LogicException;
Class Marker
{
public function __construct(private string $title, private DateTimeImmutable $activatedAt = null) {}
public function activate(): void
{
if ($this->activatedAt !== null) {
throw new LogicException;
}
$this->activatedAt = new DateTimeImmutable();
}
}
/*
The class here is reducted to the minimum possible, but imagine there would be much more... (method/property).
As a developer without any historical context on the code,
I will start to assume that a Marker can be optionnaly instantiated (created) and activated (in the same time)
But this is wrong, business doesnt allow that for some reason.
If the property is declared in the constructor as optionnal the meaning is: "Instanciation allow optionnal state"
which is vert different from "property constructor" reduced maintenance cost. it induced a possible usage of the code.
Let say that there is no usage of ActivedAt explicitely in the code, it would be even worse for me, as I would check for any inheritance case etc.
@localheinz
Copy link

Ha, now I understand what you mean, @ludofleury!

In this case I would only use constructor property promotion for fields that should be injected, like so:

<?php

use DateTimeImmutable;
use LogicException;

class Marker
{
    private ?\DateTimeImmutable $activatedAt = null;

    public function __construct(private string $title)
    {
    }

    public function activate(): void
    {
        if ($this->activatedAt !== null) {
            throw new LogicException;
        }

        $this->activatedAt = new DateTimeImmutable();
    }
}

What do you think?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment