collections icon indicating copy to clipboard operation
collections copied to clipboard

[2.0] Use null instead of false on failure

Open enumag opened this issue 5 years ago • 6 comments

I noticed that some methods of Collection return false on failure. Specifically first(), last(), current(), next() and indexOf(). It would be better in my opinion to return null instead.

Since this is a BC break I'd like to propose this for doctrine/collections 2.0.

https://github.com/doctrine/collections/commit/c3564a69cf8e073f4031ce86a77fde44563f7f03 (Of course all Collection implementations and tests would need to be changed accordingly.)

enumag avatar Apr 10 '19 11:04 enumag

Returning null would allow using PHP 8.0's nullsafe operator: $foo->getBars()->first()?->getName();

ThomasLandauer avatar Jul 27 '22 16:07 ThomasLandauer

What is the status of this issue? I'm willing to implement it if needed. Personally I'll be more than happy to have it, we may want to have methods like: ->firstOrNull() to keep BC? Let me know

jeromegxj avatar Feb 13 '23 14:02 jeromegxj

I'm not aware that anyone is working on this issue, so feel free to do so.

derrabus avatar Feb 13 '23 14:02 derrabus

A try has been given leading to a discussion The conclusion is that this is too much of a breaking change to be done even if it would go to the next major version.

jeromegxj avatar Feb 22 '23 10:02 jeromegxj

Maybe a year later we could revisit this issue, or does the team still have the same opinion?

This is one of my only gripes with Doctrine, always having to use $obj->getRelation()->isEmpty() ? null : $obj->getRelation()->first()->getField(); instead of the much better readable $obj->getRelation()->first()?->getField()

mbolli avatar Apr 26 '24 14:04 mbolli

Maybe a year later we could revisit this issue, or does the team still have the same opinion?

My opinion hasn't changed: https://github.com/doctrine/collections/pull/362#discussion_r1113998654

derrabus avatar Apr 26 '24 16:04 derrabus