Hi,

 

A recent discussion brought up the need for multiple constructors for the
same class.

https://externals.io/message/126428

 

The need was mostly answered by suggestions to use factory methods.

However on an earlier discussion it was discussed how it's fine and even
useful for constructor methods to violate the LSP.

https://externals.io/message/121789

 

I've felt a similar need on some projects. To have a named factory method
that would have an overridable signature.

 

Maybe a new keyword like `factory`that would make the method only callable
statically? I'm thinking of something like

 

    class Triangle extends Polygon

    {

        public factory method fromPoints(Point $p1, Point $p2, Point $p3):
static
        {

            // .

        }

 

        public factory method wrap(static|string $triangle): static
        {

            return $triangle instanceof static ? $triangle :
static::fromWkt($triangle);

        }

    }

 

Sure, I'm not saying this API is currently impossible. I can do the more
narrow checks within the methods and throw from there. But sometimes it's
useful to precisely describe the acceptable arguments in the method
signature.

 

What do you think? Would such a feature be useless and/or harmful?

 

BR,

Juris

Reply via email to