Set id in constructor, or generate it when asked for? I'm using PHP, I have a class that generates an id based on the calling class, so the id of the class won't change after it has been initialised, now I'm wondering which of my two methods is preferrable.

Set the id in the constructor
Generate the id when asked for

/* Set  the id in the constructor */

abstract class Badge
{
    protected $activities;
    protected $id;

    abstract public function check();

    public function __construct(array $activities)
    {
        $this-&gt;activities = $activities;
        $this-&gt;id = $this-&gt;getId();
    }

    public function getId(): string
    {
        $class = explode('\\', get_class($this));
        $classWithoutNamespace = array_pop($class);
        $snakeCased = strtolower(preg_replace('/(?&lt;!^)[A-Z]/', '_$0', $classWithoutNamespace));

        return &quot;{$snakeCased}_{$this-&gt;target}&quot;;
    }

    public function toArray(): array
    {
        return [
            'id' =&gt; $this-&gt;id,
        ];
    }
}

/* Generate the id when asked for */

abstract class Badge
{
    protected $activities;

    abstract public function check();

    public function __construct(array $activities)
    {
        $this-&gt;activities = $activities;
    }

    public function getId(): string
    {
        $class = explode('\\', get_class($this));
        $classWithoutNamespace = array_pop($class);
        $snakeCased = strtolower(preg_replace('/(?&lt;!^)[A-Z]/', '_$0', $classWithoutNamespace));

        return &quot;{$snakeCased}_{$this-&gt;target}&quot;;
    }

    public function toArray(): array
    {
        return [
            'id' =&gt; $this-&gt;getId(),
        ];
    }
}

```
I would go with lazy loading. Generate the id when requested
private $id;

public function getId()
{
    if ($this-&gt;id === null) {
        $this-&gt;id = //your logic to generate the id here
    }
    return $this-&gt;id;
}

and don't use anywhere else $this-&gt;id even inside the class. Use $this-&gt;getId() everywhere.
using $this-&gt;getId() everywhere will ensure that you always get the generated id (the same one everytime) and you are sure you don't get the null initial value.