A co-worker asked me to change a signature from using a primitive "boolean" to using a classed "Boolean". He didn't offer a very good explanation why?
Have any of you heard of this and can any of you explain why it matters or doesn't matter?
Edit: He mentioned that it was good practice for public methods.
The use of the field is just a flag that tells me whether to call one flow or another depending on whether it's true or false.
Is it database-related? If you have a boolean value in a database, it can hold one of THREE values -- true, false, and null. The Boolean object would let you mimic that behavior.
Basically, it's a matter of whether you want to deal with "null" as a potential input value.
Actually I tend to err on the side of passing small-b boolean instead, because I know that a primitive boolean is never going to be null. I'm sure there are valid reasons for using the Boolean type, but I'd want to think about its use in each case.
Actually, in general, it's good practice to use regular primitives unless there's a specific reason not to. It will be slightly faster/less wasteful, though you'd need to be moving a lot of objects around for that to really matter.
In response to your edit, I've never heard of it being good practice for public methods. In the often-cited Effective Java by Josh Bloch, there's an entire item "Prefer primitive types to boxed primitives" (item 49, if you can get your hands on a copy). It sounds like your specific case has no reason to favor of using a big-b Boolean, and using objects creates pitfalls like poor interaction with old code that, for example, uses == rather than equals() (which isn't even possible for a primitive).
The main advantage of Boolean over primitive booleans is that they allow you to have a null value. This is particularly effective for return values but can sometimes be used for an "optional" argument in Java.
Make sure your JavaDocs (and code) can deal with the null
Never heard of any valid reason to prefer Boolean over boolean.
Given a chance, always stick with primitives. Boolean variables can be null; and thus can introduce an unexpected behavior in your method. Your co-worker may have some specific reasons based on program implementation/logic.
I typically try to make use of the primitive boolean wherever possible.
The only possibility that I can think for a developer to want the Boolean class is boxing/unboxing (but I would think you'd want to prevent boxing/unboxing whenever possible rather than encourage it everywhere) and the possibility for null values.
If you control both sides of the interface (i.e. the calling code and the called method) then you should simply be consistent. You actually incur a bit of overhead if you force the compiler to autobox the variable for you.
If the method in question is one of a set of methods with similar signatures, and all others pass an object of some kind in the position where your boolean goes, then using an object rather than a primitive might simply be a matter of being a bit more consistent.
EDIT: Re-reading the question, if that boolean parameter is really just there to control an if (which is exactly what the primitive is there for), then using the object form is simply a waste of CPU time and memory. I can't think of a sensible reason why it should be an object rather than a primitive.
Keep it simple. Using Boolean:
adds an extra layer of complexity
takes a true/false state boolean and converts it to a true/false/null state variable
offers no advantages if used as a logic flag (assuming there is no database interaction as mentioned by BlairHippo)
potentially requires additional lines of code to box/unbox booleans in Java 1.4
Are you using any kind of data-binding framework in your app? I recently had to deal with a case where a boolean in a model object needed to be bound to a form. The field in the form was required, but we didn't want to default the value to true or false (because it was important for the user to choose the correct value for the specific case, if there was a default, you'd easily get a lot of incorrect values.) However, before the object could be validated, values from the form had to be bound to it. Of course, if the user hadn't selected a value, it would attempt to bind null to the field, and an exception would be thrown during the bind. So we changed it to a Boolean so that null could be bound to the field temporarily, and then validation could report that the field was required.
If you use Boolean, then you can either pass a boolean or a Boolean to the method
public void setX(boolean b) //only takes boolean
public void setX(Boolean b) //takes Boolean or boolean
This is due to the autoboxing of the booleans into the function.
EDIT: The autoboxing only works in 1.5+
Related
When I should go for wrapper class over primitive types? Or On what circumstance I should choose between wrapper / Primitive types?
Others have mentioned that certain constructs such as Collections require objects and that objects have more overhead than their primitive counterparts (memory & boxing).
Another consideration is:
It can be handy to initialize Objects to null or send null parameters into a method/constructor to indicate state or function. This can't be done with primitives.
Many programmers initialize numbers to 0 (default) or -1 to signify this, but depending on the scenario, this may be incorrect or misleading.
This will also set the scene for a NullPointerException when something is being used incorrectly, which is much more programmer-friendly than some arbitrary bug down the line.
Generally, you should use primitive types unless you need an object for some reason (e.g. to put in a collection). Even then, consider a different approach that doesn't require a object if you want to maximize numeric performance. This is advised by the documentation, and this article demonstrates how auto-boxing can cause a large performance difference.
In my opinion, if my class members are wrapper variables, it does not rely on default values, which is developer friendly behavior.
1.
class Person {
int SSN ; // gets initialized to zero by default
}
2.
class PersonBetter {
Integer SSN; //gets initialized to null by default
}
In the first case, you cannot keep SSN value uninitialized. It may hurt if you are not checking if the value was set before you attempt to use it.
In the second case, you can keep SSN initialized with null. Which can lead to NullPointerException but it is better than unknowingly inserting default values(zero) as SSN into to the database whenever you attempt to use it without initializing SSN field.
I would only use the wrapper types if you have to.
In using them you don't gain much, besides the fact that they are Objects.
And, you lose overhead in memory usage and time spent boxing/unboxing.
Practically I had encountered a situation where use of wrapper class can be explained.
I created a service class which had a long type variable
If the variable is of type long - when not initialized, it will be set to 0 - this will be confusing to the user when displayed in GUI
If the variable is of type Long - when not initialized, it will be set to null - this null value won't show up in GUI.
This applies to Boolean as well where values can be more confusing when we use primitive boolean(as default value is false).
Collections are the typical case for the simple Java wrapper objects. However, you might consider giving the Wrapper a more specific meaning in the code (value object).
IMHO there's almost always a benefit to use value objects when it boils down to readability and maintainance of the code. Wrapping simple data structures inside of objects when they have certain responsibilities often simplifies the code. This is something that is very important in Domain-Driven Design.
There is of course the performance issue, but I tend to ignore that until I have the possibility to measure the performance with proper data and do more directed actions towards the problematic area. It might also be easier to understand the performance issue if the code is easy to understand as well.
performance of applications that are dominated by numerical calculations can benefit greatly from the use of primitives.
primitive types, one uses the == operator, but for wrapper the preferred choice is to call the equals() method.
"Primitive types considered harmful" because they mix "procedural semantics into an otherwise uniform object-oriented model.
Many programmers initialize numbers to 0 (default) or -1 to signify this, but depending on the scenario, this may be incorrect or misleading.
If you want to use Collections, you must use Wrapper classes.
Primitive types, are used for arrays. Also, to represent data that has no behaviour,for example, a counter, or a boolean condition.
Since autoboxing, the "when to use primitive or wrapper" frontier has become quite fuzzy.
But remember, Wrappers are objects, so you get all the fancy Java features. For example, you can use reflexion to create Integer objects, but not int values. Wrapper classes also have methods such as valueOf.
When to Use Primitive Types
When doing a large amount of calculations, primitive types are always faster — they have much less overhead.
When you don’t want the variable to be able to be null.
When you don’t want the default value to be null.
If the method must return a value
When to Use Wrapper Class
When you are using Collections or Generics — it is required
If you want the MIN_SIZE or MAX_SIZE of a type.
When you want the variable to be able to be null.
When you want to default value to be null.
If sometimes the method can return a null value.
from https://medium.com/#bpnorlander/java-understanding-primitive-types-and-wrapper-objects-a6798fb2afe9
If you want to create a value type. Something like a ProductSKU or AirportCode.
When a primitive type (string in my examples) defines equality, you'll want to override equality.
Primitive values in Java are not object. In order to manipulate these values as object the java.lang package provides a wrapper class for each of the primitive data type.
All Wrapper classes are final. The object of all wrapper classes that can be initiated are immutable that means the value in the wrapper object can not be changed.
Although, the void class is considered a wrapper class but it does not wrap any primitive values and is not initiable. It does not have public constructor, it just denotes a class object representing the keyword void.
In c++, I'd usually pass a byRef variable as a parameter to the function to get the information that I need returned, and I'd return a boolean or int value from the function to determine if the function was executed successfully (no errors occurred at any point).
I can't do that in Java since you can only pass byVal, and can get one thing returned.
I guess you can return some array or list, but I feel like that's bad coding practice.
What are some proper ways to deal with this problem?
If you want to do it exactly like in c++, you can pass a primitive by reference via its wrapper-class (e.g. class Integer for primitive int). But I agree with the comments below the question that the 'proper way' of doing this in Java is to throw an exception in case of failure. In case you do not like both ideas, you can still use static variables in the class that implements the method you are executing, let them be set by that method and read by the invoking method/class, but this is no good coding practice either and should not be done unless there is no other option for whatever reasons.
I'm doing refactoring/review of a Java application
When I'm doing that I show that some of method has
return values such as Object, String, Boolean, etc., but
return values are not used in any places. Only have done the method calling.
So, I'm just wandering keeping them as it is will cause the
performance issue for application.
Should I change them to void or keep them as it is?
Moreover than being a performance hit its an inappropriate construction of a method.
If the method's returned value has no use in the program then there is no reason to return it, and so the method's return type should be made void.
I do not think that there would be a performance penalty to keeping the return types like they are.
That being said, I think that you should still remove them. The reason is that they are essentially dead code. There might be unknown bugs lurking in those methods revolving around the return types - unknown because they are not used. This is a potential danger if someone decides to use them one day.
Furthermore, the maintenance burden is increased if you keep them: Everytime someone touches one of these methods, she has to (unnecessarily) think about the return type.
This essentially boils down to YAGNI.
In my opinion, either the API is being incorrectly used or it is incorrectly designed.
If the API is correctly designed then why are the API users not using the method return types? In this case the users must be wrong.
On the other hand if the API is incorrectly designed, what is the point of using it in its current state? If the returned information is superfluous then fix the API and make the methods void.
I think that performance considerations would be of little importance when compared to a good API design. Performance can always be improved later, but APIs are very difficult and expensive to change.
Should not return a value if the value in not used. Use void instead. Sometimes I see some getters that is not used but actually they are used by the web framework. It's difficult to determine if the method is unused. Even if it's used but the return value is ignored. There's no restriction to not ignore the return value.
When using JDBC and accessing primitive types via a result set, is there a more elegant way to deal with the null/0 than the following:
int myInt = rs.getInt(columnNumber)
if(rs.wasNull())?
{
// Treat as null
} else
{
// Treat as 0
}
I personally cringe whenever I see this sort of code. I fail to see why ResultSet was not defined to return the boxed integer types (except, perhaps, performance) or at least provide both. Bonus points if anyone can convince me that the current API design is great :)
My personal solution was to write a wrapper that returns an Integer (I care more about elegance of client code than performance), but I'm wondering if I'm missing a better way to do this.
Just to clarify, what bothers me about this code is not the length, but the fact that a it creates a state dependency between subsequent calls, and what appears like a simple getter actually has a side effect within the same row.
The JDBC API was designed for performance. Remember that it dates back to Java 1.1, when a large turnover of objects was a JVM killer (it wasn't until the Hotspot JVMs in Java 1.2+ that you could relax this kind of limitation). Using boxed types would have ruined the performance of high volume applications at the time.
Now, it can't be changed because of backwards compatibility. So no, it's not ideal any more, but it's a pretty minor thing to workaround.
If you want to avoid the type of code you mentioned, you can always use getObject() instead of getInt(), which will return an object of one of the subtypes of java.lang.Number, probably Integer or BigInteger, depending on the specific SQL type.
When I should go for wrapper class over primitive types? Or On what circumstance I should choose between wrapper / Primitive types?
Others have mentioned that certain constructs such as Collections require objects and that objects have more overhead than their primitive counterparts (memory & boxing).
Another consideration is:
It can be handy to initialize Objects to null or send null parameters into a method/constructor to indicate state or function. This can't be done with primitives.
Many programmers initialize numbers to 0 (default) or -1 to signify this, but depending on the scenario, this may be incorrect or misleading.
This will also set the scene for a NullPointerException when something is being used incorrectly, which is much more programmer-friendly than some arbitrary bug down the line.
Generally, you should use primitive types unless you need an object for some reason (e.g. to put in a collection). Even then, consider a different approach that doesn't require a object if you want to maximize numeric performance. This is advised by the documentation, and this article demonstrates how auto-boxing can cause a large performance difference.
In my opinion, if my class members are wrapper variables, it does not rely on default values, which is developer friendly behavior.
1.
class Person {
int SSN ; // gets initialized to zero by default
}
2.
class PersonBetter {
Integer SSN; //gets initialized to null by default
}
In the first case, you cannot keep SSN value uninitialized. It may hurt if you are not checking if the value was set before you attempt to use it.
In the second case, you can keep SSN initialized with null. Which can lead to NullPointerException but it is better than unknowingly inserting default values(zero) as SSN into to the database whenever you attempt to use it without initializing SSN field.
I would only use the wrapper types if you have to.
In using them you don't gain much, besides the fact that they are Objects.
And, you lose overhead in memory usage and time spent boxing/unboxing.
Practically I had encountered a situation where use of wrapper class can be explained.
I created a service class which had a long type variable
If the variable is of type long - when not initialized, it will be set to 0 - this will be confusing to the user when displayed in GUI
If the variable is of type Long - when not initialized, it will be set to null - this null value won't show up in GUI.
This applies to Boolean as well where values can be more confusing when we use primitive boolean(as default value is false).
Collections are the typical case for the simple Java wrapper objects. However, you might consider giving the Wrapper a more specific meaning in the code (value object).
IMHO there's almost always a benefit to use value objects when it boils down to readability and maintainance of the code. Wrapping simple data structures inside of objects when they have certain responsibilities often simplifies the code. This is something that is very important in Domain-Driven Design.
There is of course the performance issue, but I tend to ignore that until I have the possibility to measure the performance with proper data and do more directed actions towards the problematic area. It might also be easier to understand the performance issue if the code is easy to understand as well.
performance of applications that are dominated by numerical calculations can benefit greatly from the use of primitives.
primitive types, one uses the == operator, but for wrapper the preferred choice is to call the equals() method.
"Primitive types considered harmful" because they mix "procedural semantics into an otherwise uniform object-oriented model.
Many programmers initialize numbers to 0 (default) or -1 to signify this, but depending on the scenario, this may be incorrect or misleading.
If you want to use Collections, you must use Wrapper classes.
Primitive types, are used for arrays. Also, to represent data that has no behaviour,for example, a counter, or a boolean condition.
Since autoboxing, the "when to use primitive or wrapper" frontier has become quite fuzzy.
But remember, Wrappers are objects, so you get all the fancy Java features. For example, you can use reflexion to create Integer objects, but not int values. Wrapper classes also have methods such as valueOf.
When to Use Primitive Types
When doing a large amount of calculations, primitive types are always faster — they have much less overhead.
When you don’t want the variable to be able to be null.
When you don’t want the default value to be null.
If the method must return a value
When to Use Wrapper Class
When you are using Collections or Generics — it is required
If you want the MIN_SIZE or MAX_SIZE of a type.
When you want the variable to be able to be null.
When you want to default value to be null.
If sometimes the method can return a null value.
from https://medium.com/#bpnorlander/java-understanding-primitive-types-and-wrapper-objects-a6798fb2afe9
If you want to create a value type. Something like a ProductSKU or AirportCode.
When a primitive type (string in my examples) defines equality, you'll want to override equality.
Primitive values in Java are not object. In order to manipulate these values as object the java.lang package provides a wrapper class for each of the primitive data type.
All Wrapper classes are final. The object of all wrapper classes that can be initiated are immutable that means the value in the wrapper object can not be changed.
Although, the void class is considered a wrapper class but it does not wrap any primitive values and is not initiable. It does not have public constructor, it just denotes a class object representing the keyword void.