Java – defines a string as null or empty

I'm from C # Net background, whenever I have a string, I declare it as string Empty

String myStr = null;

I don't like it. What's worse, he assigns values to these strings in the "if" block, which may not even meet the conditions, and then calls mystr. At the end of the method Length () is in them

So my question is, what is the preferred way in Java? You think we should define them as string Empty better or keep them as null before calling them. Empty check before length()?

Solution

In general, using null values is a bad idea, especially if they are returned from a method or passed to another method It is better to use null object pattern. In the case of string, null object is an empty string By consistently avoiding null values, NullPointerException is less likely to be obtained and the code becomes more readable (this is discussed in detail in Chapter 7 of clean code, pages 110-112)

In Java string, s = "" does not allocate any memory, because the JVM will implement string literals, so there is even no performance difference (even if there is, it will be a premature optimization)

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>