-
Notifications
You must be signed in to change notification settings - Fork 409
Return empty collections in place of nulls #211
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Conversation
When calling some getXyz() method, where xyz is a collection, if xyz is null then an empty collection will be returned.
Hi @TBuc! Thanks for the PR! Could you please provide some explanation why we need to return empty collections rather than nulls? With Best Regards, Elmer |
Hi @thinkingserious, I kept it short at first, but I can do it for sure! In general, nowadays avoiding returning nulls is generally a best practice, especially for collections. When fetching a collection, I expect to get a collection. If it has no objects in it, it will just be an empty collection. A potential There are many alternatives to achieve this goal, i.e.:
In my PR I've opted for the solution n.2 since it has the lowest impact on the existing code. Best regards, |
@TBuc You're right about returning empty collections instead of nulls (Effective Java 2nd edition Item 43). Also, quoting directly from Item 43, "To eliminate the overhead from creating an empty collection or array, return the immutable empty collections in java.util.Collections". Would you mind using the java.util.Collections immutable empty collections instead?
instead of:
|
@vaskoz that's great! I've read Bloch quite a few years ago, and I did really not remember such immutable collections do exist. I will modify my code accordingly to your great suggestion. Thank you for pointing out! I would only add the type parameterization to the code you propose, in order to return the exact type for the collection objects in order to maintain the current return types. So that, i.e., what you proposed: |
When returning an empty collections is needed, now makes use of the ready, immutable empty collections of java.util.Collections in place of instantiating a new collection every time.
Since one day has passed, I suppose it's OK and I've updated the PR. |
@TBuc Thanks so much! I have no comments. |
When calling a getXyz() method on a Mail object, where xyz is some object implementing Collection, if xyz is null then an empty collection will be returned (currently returns null).