On Sun, Oct 23, 2016 at 3:39 AM, Michał Brzuchalski <mic...@brzuchalski.com>
wrote:

> Hi all,
>
> I would like to initiate discussion for Object typehint RFC
> https://wiki.php.net/rfc/object-typehint
>
> This feature is developed to provide missing functionality which is needed
> and quite easy to introduce.
> There are many people which I've talked about the benefits of this
> functionality.
>
> For those who doesn't like the idea and think they won't need neither use
> it rather than just saying 'no' they
> please say why other people who want to use that parameter type are wrong,
> for wanting to do that.
>
>
Type hinting, along with the assert statement, provide a means to establish
expectations for a methods. It's part of a coding paradigm known as 'design
by contract' and it's critical for large teams and projects that are used
among multiple teams.

Checking to see if a variable is an object in no way provides a real test
of what can be done with it.  Can it be iterated on? Probably, but not
always. Does a method exist on the object? No way to know without further
testing.

Defining what an object can do is the reason interfaces exist. This is also
why objects are allowed to implement multiple interfaces, so that they can
be labeled according to all the roles they can fulfill.

My principle worry with this RFC is it encourages an anti-pattern - not
using interfaces and thereby not clearly labeling what objects can and
cannot do.

The one situation this might be useful requires additional testing anyway -
that would be a method that will receive objects of one or more classes
that don't have a common interface and rewriting the class to add the
desired interface isn't viable (for example, the objects come from
different packages). In that event though type hinting for an object is
only going to be the first step in determining if the code state is sane,
you'll also need to check if the object belongs to one of the several
classes the code can work with.  This gets even hairier when dealing with a
collection of objects.  I wrote this generic assertion for Drupal 8.

https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Component%21Assertion%21Inspector.php/function/Inspector%3A%3AassertAllObjects/8.2.x

In your own code you'll likely need to do something similar with your
argument.  Incidentally, these sorts of tests, which can only fail if the
code is wrong, are what assert statements are to be used for, not
exceptions. This way the check for correct objects can be turned off in
production to avoid the cpu overhead of the test (assuming your function
doesn't need to switch to different branches depending on the exact object
used).

In summary, -1 to this as it encourages bad code writing.

Reply via email to