DEV Community

Discussion on: 10 practices for writing readable code

 
shayd16 profile image
Shayne Darren • Edited

I see. So basically, this is something that needs to be thought about from the design level up, and not a simple change that can be done to a method(in most cases at least). I am familiar with the practice of returning an empty list rather than null. Definitely reduces the number of null checks that have to be done in other parts of the code.

Thread Thread
 
acostalima profile image
André Costa Lima • Edited

Methods that return collections should never return null, ever. At the very least, an empty collection is returned. For plain objects, employ the Null Object Pattern. In case of Java, Optional class is what you should be looking for. 🙂

Thread Thread
 
shayd16 profile image
Shayne Darren

This is exactly what I was looking for, how to handle plain objects. Thank you, Andre.
Will definitely be implementing these where possible.

Thread Thread
 
ashleyjsheridan profile image
Ashley Sheridan

There is the null object pattern for this situation, which returns something that shouldn't break your existing code and only requires minimal changes to your methods which return objects.

en.m.wikipedia.org/wiki/Null_objec...

Thread Thread
 
acostalima profile image
André Costa Lima

👌💪