This is the fifth post in my Missing in PHP7 series. The previous one is about Collections. This is a short post, as there really is not much to explain or motivate.
Nullable return types
As of PHP7, we have return types at our disposal. Unfortunately, these have some annoying limits. One of them I described in my PHP Collections blog post. Another is the lack of nullable return types. This blog post is about the latter.
Take the following code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
class DoctrineKittenRepository implements KittenRepository { /** * @param int $kittenId * @return Kitten|null */ public function getKittenById( int $kittenId ) { try { $kittenOrmEntity = $this->doctrineThing->gimmehStuff(); } catch ( ORMException $ex ) { return null; } if ( $kittenOrmEntity === null ) { return null; } return $this->getKittenFromOrmObject( $kittenOrmEntity ); } private function getKittenFromOrmObject( OrmKitten ): Kitten { return new Kitten( /* ... */ ); } } |
This is a repository, that obtains a kitten from the persistence in some manner (such as using Doctine ORM). It then returns the kitten as an Entity part of the domain, in this case represented by the Kitten
class. As you can see, we’re using a return type hint for the getKittenFromOrmObject
private method. However for the public method, we’re prevented from using a return type hint, as it can also return null. This is really unfortunate, as we need to fall back to using documentation instead of code. The IDE I’m currently using, PhpStrom, manages to add salt to the wound by then requiring all parameters to also be present in the docblock if you don’t want to get any warnings about them not being there.
It’d be very nice to be able to do
1 |
public function getKittenById( int $kittenId ): Kitten|null {} |
Or alternatively
1 |
public function getKittenById( int $kittenId ): ?Kitten {} |
After asking about this on Stack Overflow several months ago, I found out that there is an RFC for nullable return type declarations. Unfortunately this appears to not be going anywhere for now. A somewhat related RFC, one for introducing a void return type, has on the other hand already been implemented and will land in PHP 7.1.
Nullability in Java
I have not often worked with Java in the recent past, though when I did, I always ended up being surprised by it’s default nullability of types.
1 2 3 4 5 |
void someStuff(Kitten kitten) { if (someobject != null) { kitten.doStuff(); } } |
The caller of someStuff
can pass in null, which forces null checks in many places, be it like above, or in the form of a guard clause that throw a type error. This is annoying, and indeed, the Clean Code book even has a chapter on avoiding returning null.
So not all is bad in PHP-land when it comes to nullability 🙂
Pretty sure php doesn’t even take itself seriously