Logical (Object) getters in java

Suppose I have a class foo in which I have a variable Boolean (not Boolean ) bar :

 class foo { Boolean bar; Boolean isBar(){ return bar; } boolean isBar(){ return bar.booleanValue(); } } 

Which of the above methods is the correct way in Java.

I know that both will work, but I want to know what is the Java coding convention on this?

+4
source share
3 answers

if you will use the boolean type, your method should be

 Boolean getBar(){ return bar; } 

otherwise your field should be a primitive boolean type.

+10
source

a boolean is primitive, it can be true or false . Boolean is an object wrapper for boolean . boolean can be true, false and null. If you don't need this null , use boolean as it is cheaper for memory.

boolean has many helper methods, for example, you can have a Boolean from a String using Boolean.valueOf(theString); , which may be false or true, instead of executing

 if("true".equals(theString)) primitiveBoolean = true; 
+2
source

If bar can be null , and this is what you want to model in your class, I would use:

 class foo { boolean bar; boolean isBar(){ return bar; } } 

It is simpler, faster, and cannot have NullPointerException s.

If, however, null is a valid value and you need a model, you should use Boolean / Boolean .

Please note that your code is:

 Boolean bar; boolean isBar() { return bar.booleanValue(); } 

Or even an autoboxing option:

 Boolean bar; boolean isBar() { return bar; } 

... may throw NullPointerException s. Especially the last one is very confusing.

+1
source

Source: https://habr.com/ru/post/1485947/


All Articles