Moment For Technology

Try not to use null when the method returns!

Posted on Aug. 8, 2022, 7:02 p.m. by Amani Chander
Category: The back-end Tag: The back-end

This is the fourth day of my participation in Gwen Challenge

In daily development, we always encounter some development problems. For example, when we make some logical judgments, novice developers may think that since none of your data matches, I have no return, so I will return null.

The ten-year-old developer in your company cursed his mother.

Today when looking at the effect of Java and look up this paragraph, think it's necessary to record the first under the said why not suggest returns null, because if you this method is a tool or a class method interface, each time to empty first and then judge others in content, and many people sometimes can't remember whether this development, After all, everyday business requirements return collections, but with some exceptions, you should not leave the problem to the caller if you can solve it here;

It's just like the question in the article, there's no data, you don't return NULL but you return a 0 length object, you generate space, you waste resources, actually, there's a point here that I think you might miss, and I was confused when I read it, it says that for a zero length array, It's possible that you'll return the same zero-length array every time you call it, because zero-length arrays are immutable, and immutable objects can be shared. If you're a Java wizard, you can see that String is final. Each time you make a change, you are actually recreating and assigning the value, and the original value may be in memory waiting to be reclaimed; That's it.

One more thing, bosses, points out that actually recommend you create a small object, because in our daily development will find sometimes to create an object can solve a lot of trouble, simplify the code, and because the JVM now is very good, the small object creation and recovery is very cheap, everything, and nothing to create objects, believe the JVM;

Although there are many utility classes that provide null-nulling methods, you probably have a method in your code base that can turn null into an empty string.

About (Moment For Technology) is a global community with thousands techies from across the global hang out!Passionate technologists, be it gadget freaks, tech enthusiasts, coders, technopreneurs, or CIOs, you would find them all here.