jeromegamez/duration-php

Why is Duration no longer final ?

Closed this issue · 3 comments

@jeromegamez nice package why is the Duration class no longer final ? Seems to me that it is a Value Object and therefore should be final 🤔

That's a good question that I've asked myself as well.

In 1.x the class was final, but extensible through the spatie/macroable package, in case somebody would want to extend the class, e.g. with inDays(), inMinutes() or similar helper functions that I perhaps would not be willing to implement in the basse class. After releasing it, it felt wrong to me - having a final class that's still open for extension through "cheating" :).

So I decided to see the Duration class within the package more as an open utility class than a strict value object. In a project that uses the class, a developer can for example to something like this

<?php

namespace App;

use Gamez\Duration;

final class Duration extends \Gamez\Duration
{
    public function inMinutes(): int
    {
        $now = new DateTimeImmutable();
        $then = $now->add($this->toDateInterval());

        $durationInSeconds = $now->diff($then, true);

        return intdiv($durationInSeconds, 60);
    }
}

I am planning to add more features to the class (perhaps even those helper methods), and as soon as I think that the class is feature complete, I will make it final again and create a new major release.

I hope this makes sense and answers your question.

Making your class final will help you down the road when adding new functionalities that requires messing up your internal code. Currently any changes to your internal code is potentially a BC break because the class is not final. This was discuss in length in a specific issue of League\Period before v4 release

Also another proof is because I made Period final I was able to add full boundary type support without any BC break 😄 because the internal was heavily rewrote. Otherwise I would have add multiple method marked as deprecated left because I would have potentially broke the code of someone using them via extension.

TL;DR: You should favor composition over inheritance and make your class final.

My 2 cents

You're right. Well then, that will be a fast iteration to a 3.x release :D. Thank you for your input!