using Boolean Object - java

i'm having issues trying to get the result I wish. Basically what I want to do is have a Boolean object which will allow me to have 3 choices, if a mailer is old i want it to be set to false (meaning does not contain "mapQ.cmd" and "add-coid.cmd" file)
if a mailer is new I want it to set to true (if it is new it will contain "mapQ.cmd" and "add-coid.cmd" file in the directory), and if it is neither an old or new mailer (meaning not a mailer) then I wish for it to be null.
This is what I have, I want to place an elseif instead of the else, and do an else inside that to set the null value, meaning non of the above, then i wish to return the boolean.
local-build-deploy.cmd is used in the example but i wish to use the above file names
private boolean isOldMailer(File mailerFolder) {
File localBuildAndDeploy = new File(mailerFolder,"test/local-build-deploy.cmd");
if (localBuildAndDeploy.exists()) {
return true;
} else {
return false;
}
}

There are 2 ways that you can do this.
If you insist on using Boolean, use the capital B version instead of lower case b. Capital B Boolean is an object and can be set to null and do what you describe. Lower case b boolean is a primitive and can not be set to null.
However, there is a better way that does not rely on using a boolean for 3 values when it is designed for 2.
Using an enum, you can define your types just how you want them and have exactly as many as you need. Here is an example and how you would use it.
public enum Status { NEW, OLD, NEITHER }
private Status isOldMailer(File mailerFolder) {
File localBuildAndDeploy = new File(mailerFolder,"test/local-build-deploy.cmd");
if (localBuildAndDeploy.exists())
return Status.NEW;
else if (/*Something else*/)
return Status.OLD
else
return Status.NEITHER;
}

This is ternary logic, not binary logic. It's typically used in relational databases.
Boolean is binary, of course - just true or false.
If you want ternary logic, wrap it in your own type.

(I'll go over three common options and then suggest the third).
The first option is to use a Boolean and set it to true, false or null. This has a few benefits:
Assuming you first check to ensure the value is not null, you can use it directly in boolean expressions.
It's a somewhat controversial point, but null really isn't too far off from "none of the possible values" (i.e. neither true nor false), so it's a reasonable model. Many disagree.
Concise.
However, some people, reasonably or not, expect a Boolean to be either true or false, and do not consider the null possibility, which can easily lead to bugs.
The second option is to use an enum:
No real risk of misuse, since null is not an option, but...
You lose the boolean semantics.
Depending on what you're modelling, it may or may not be aesthetic to introduce a custom enum.
The third--and recommended--option is to use an Optional< Boolean > from Google's excellent Guava library:
It's a very common library.
It's self-documenting.
It has well-defined semantics.
Null is not an issue.
Boolean semantics are just a get away.
Converting to/from the null-based model in the first option, above, is very concise and easy-to-read.

Use Boolean - the wrapper object on primitive boolean. In that way, you can set the reference to null or true or false.

Related

When to use true and when to use Boolean.TRUE? [duplicate]

This question already has answers here:
What is the difference between Boolean.TRUE and true in Java?
(7 answers)
Closed 9 days ago.
I had written a code of which a rough snippet is as follows:
boolean isCalledFromAction = Optional.ofNullable(requestParams.get(IS_CALLED_FROM_ACTION))
.map(val -> true)
.orElse(false);
My team lead said to always use existing classes and insisted to use Boolean class like below:
boolean isCalledFromAction = Optional.ofNullable(requestParams.get(IS_CALLED_FROM_ACTION))
.map(val -> Boolean.TRUE)
.orElse(Boolean.FALSE);
My question is I see Boolean.TRUE will make unnecessary a Boolean type object. When to use true and when to use Boolean.TRUE? Why in first place, Boolean.java class contains a wrapper object for true and false? I mean, they have auto-boxing so they can directly do like Boolean x = true; instead of Boolean x = Boolean.TRUE.
I have read answers on existing questions on SO related to performance but here I am interested in their usage scenarios.
At first something general
The main difference between boolean and Boolean is that a Boolean can be null, while a boolean cannot. So when you have a check if(a) {...}, with a being a Boolean, this might lead to a nullpointer exception. In this case, you would prefer to have if(Boolean.TRUE.equals(a)) {...}, because the equals method of Boolean would return false in case a is null.
Your specific case
What you suggested there is equivalent to
isCalledFromAction = Optional.ofNullable(requestParams.get(IS_CALLED_FROM_ACTION)).isPresent();
Not that isPresent actually returns a boolean and not a Boolean, as do most of the JDK internal methods that I've come across. Apart of that, I would say using true or false vs. Boolean.TRUE or Boolean.FALSE shouldn't make a real difference in most of the cases and might even be considered a matter of taste. In a large project, though, you would want to use one or the other consistently to not end up with a mess.
Constant, just one immutable object
You asked:
My question is I see Boolean.TRUE will make unnecessary a Boolean type object.
No, multiple objects are not created.
As commented by Culloca, Boolean.TRUE is a constant, referring to a singe object instantiated once when the class loads. As an immutable object, there is no need to have more than one.
Let’s look at the implementation found in the open source code at the OpenJDK project.
public static final Boolean FALSE = new Boolean(false);
The static means an instance is created when the class loads. The final means the reference named FALSE will never be re-assigned to another object. So one, and only one, object.
Avoid excessive auto-boxing
You are right to be concerned about unnecessary auto-boxing. Boxing is not magic; it takes CPU cycles to execute.
Going out of your way to use Boolean.FALSE where you know the primitive false is needed is pointless and a bit silly.
Such a practice is often harmless. If the code is infrequently executed, then you’ll see no significant impact on performance. And in some situations I would guess that the compiler might optimize away the boxing, though that is just a guess on my part.
FYI… Work is underway by the Java team to blur the sharp distinction between primitives and objects created by Java’s two parallel type systems. So the nature and impact of boxing may change in future versions of Java.
No need for Optional
Your code is overly elaborate.
You commented:
The type returned by requestParams.get(IS_CALLED_FROM_ACTION) is a string. If it is not null, I want to set isCalledFromAction to true.
Change this:
boolean isCalledFromAction = Optional.ofNullable(requestParams.get(IS_CALLED_FROM_ACTION))
.map(val -> true)
.orElse(false);
… to use Objects.nonNull:
boolean isCalledFromAction =
Objects
.nonNull (
requestParams.get( IS_CALLED_FROM_ACTION )
) ;

Java template for checking that value was set

In Java I have a bunch of variables (of different types) that I would like to check that they have been set before using them, and if they have not then the result is always the same and I want to throw an error that'll be caught higher up. In theory the code is designed that this should NEVER happen, but the consequences of a bug making it happen are too great to leave it to just unit testing.
I was thinking of just making a template that has a get() and set() function. The set would set the value and set a boolean to let it know it has been set and the get() would check the boolean and return the value or throw an error. something like:
Class ImportantInfo<T> {
private T t;
private beenSet = false;
public T get(){
if(beenSet) return t;
else throw error;
}
public void set(T value){
t =value;
beenSet = true;
}
}
Is this the correct and best approach? Are there other, possibly better, ways? I worry I am over engineering the solution or that a template this straightforward might already exist in Java?
One approach to do this would be to use Java Optionals. Optionals represent a value that may or may not be present.
Optional.empty() represents a value that is not present
The .get() method gets a value if it is present
The isPresent() checks if a value has been set or not.
The main advantage of using Optional over simply checking for null is that optional forces you to use .get() so you don't accidentally call a null value that hasn't been set.
In your particular case, I would initialize all the values at the top of the class to Optional.empty() and then use .isPresent to make sure they were set.
Note: This will only work with Java 8
(Apparently Guava Optional will work in versions less than 8 (see Tom's comment - I have no experience with this)
there are many ways, but the approaches that I would normally find useful:
checking if its null, personally I just use this, if null I assume its not been set otherwise its been set, then you can also give the user the responsibilities (optional)
instead of having setter method, you can use the constructor. this way you ensure that the value has been set before even being able to use the get method.

Java Class that can be used to represent null and absent differently

I am wondering if there is a ready made Java class that can be used similarly with Guava's Optional but treats null and absent differently.
I have use case that requires to pass a method parameter with String value, null value or absent (does not provide anything). Null is a purely valid value and carries special meaning.
I tried to use Guava's Optional but found that it cannot differentiate null and absent. Passwing null to Optional means absent.
I am wondering if there is a ready made Java utility that can be used for my usecase: It can carry a value, null value or no value (absent).
many thanks
The java language can do it: Use a token object to represent "absent".
Say it's a String type:
private static final String ABSENT = new String(""); // not interned
private String attribute = ABSENT;
public boolean attributeIsSet() {
return attribute == ABSENT; // identity comparison
}
public String getAttribute() {
if (attributeIsSet())
return attribute;
throw new IllegalStateException(); // or whatever
}
This allows null to be a valid value.
You should use Optional.
Optional is you know that something is either present or not. Add the meaning null to Optional by returning... null.
Optional<A> a = Optional.of(new A()); // We know that A is present.
Optional<B> b = Optional.absent(); // We know that B is absent.
Optional<C> c = null; // We don't know if C is present or absent.
Working with null isn't bad: it's error-prone. So be careful, document properly what you want to do and how null should be interpreted.
Null ... carries special meaning.
Whenever you find yourself saying this, it should be a red flag that your design merits re-thinking, as null by definition carries no meaning. Lets step back and look at your requirements (feel free to update the question with better descriptions of your intent if this is inaccurate):
Absence: Indicates we've nothing to do here at all
null: Indicates a "special value", such as DEFAULT or FALLBACK, which should be handled specially
Value: A "normal" value, including the empty string, that can be handled directly
This is not an unusual problem, (particularly when working with nullable database columns, as I think you are) and Optional can quite successfully represent this, but we need to structure it better.
While we can't avoid NULLs in databases, we can strive to restrict their scope to the minimal code surrounding our database access behavior, and expose it no further than that. We conceptually do this by converting nullable fields to Optionals, as you know. So col VARCHAR NULL should always be converted into Java as an Optional<String> col as soon as possible.
But now we need to represent the absence case, such as when we SELECT col FROM table LIMIT 1 and get nothing back from our query. Obviously, this should be handled differently than if we get back a NULL.
We have a couple of choices, but they all boil down to wrapping our Optional<String> in another layer somehow.
In many cases you can simply use a List or other Collection. By passing back a non-null collection we can generally handle the absent case trivially, as our code will simply not enter whatever loop would otherwise process the data if the List is empty. So List<Optional<String>> is one option.
If that's not possible, and you really want to limit the behavior to one-or-none, such as in the LIMIT 1 example above, simply wrap it in another Optional, i.e. Optional<Optional<String>>. This clearly conveys the difference between absence of a result, and absence of a value in a type-safe manner.
A little more work, but even better is to properly represent this structure in its own class (any time you have generics inside generics, consider creating a proper holding class), since really what we're talking about is a optional piece of data, which may itself contain an optional piece of data.
public class Row {
private final Optional<String> col;
public Row(#Nullable String col) {
this.col = Optional.fromNullable(col);
}
public Optional<String> getCol() {
return col;
}
}
Then you pass around Optional<Row> objects, which very clearly either exists or doesn't, and either contain a result, or not. All type-safe, and no nulls needed.
tl;dr: This can be rationally represented with Optional<Optional<String>>, or see above for additional suggestions.
Isn't an empty String ("") the same as 'no value' for a string? Obviously this wouldn't work for numbers, but you're specifically talking about a String.

How to know if a boolean has not been set(or unset) at all?

I have a peculiar problem. I work with Thrift with java at the backend and php on the front end. We have a situation where I ask the user for a boolean value for three variables. The user can either set them to true or false, or not set them at all. On the backend, I store these three values as three bits of a char(1) byte. When I checked, upon initialization, Thrift assigns a false value by default to these variables.
The problem I am facing is, that I want to know when the user does not touch (set or unset) a particular boolean at all. A lot of my bit manipulations depend on this. I don't want to make changes at the user end for this, and rather handle it on my own.
For these kinds of problems, you should use user-defined data-type i.e. enums.
Define enums which can hold three value => (TRUE, FALSE and NOT_SET)
This would solve your problem
For handling tri-state booleans in java you have a couple of options.
use Boolean object: null means it is unset
use and int: 1 for true, '0' for false and '-1' for unset
use an additional flag next to the boolean value to signal unset
note: since Java 5 you can even use the autoboxing for the first option like this:
Boolean myFlag = null;
if (myFlag==null) {
// unset
}
else if (myFlag) {
// true
}
else {
// false
}
Issue is Thrift if nothing is defined for variable, Thrift defaults to optinReqOut (Optional In, Required Out). Therefore, when you are deserializing, it sees it as missing and sets default value.
Explicitly make the variables optional.
https://twitter.github.io/scrooge/Semantics.html
It seems to work in Java:
I definition a variable named flag in IDL file like this:
optional bool flag;
And I use it in a Java class file like this:
if (request.isSetFlag()) {
boolean flag = request.isFlag();
if (flag) {do something when flag is true;}
else {do something when flag is false;}
}else{
do something when flag is null;
}

Check if null Boolean is true results in exception

I have the following code:
Boolean bool = null;
try
{
if (bool)
{
//DoSomething
}
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
Why does my check up on the Boolean variable "bool" result in an exception?
Shouldn't it just jump right past the if statement when it "sees" that it isn't true?
When I remove the if statement or check up on if it's NOT null, the exception goes away.
If you don't like extra null checks:
if (Boolean.TRUE.equals(value)) {...}
When you have a boolean it can be either true or false. Yet when you have a Boolean it can be either Boolean.TRUE, Boolean.FALSE or null as any other object.
In your particular case, your Boolean is null and the if statement triggers an implicit conversion to boolean that produces the NullPointerException. You may need instead:
if(bool != null && bool) { ... }
Use the Apache BooleanUtils.
(If peak performance is the most important priority in your project then look at one of the other answers for a native solution that doesn't require including an external library.)
Don't reinvent the wheel. Leverage what's already been built and use isTrue():
BooleanUtils.isTrue( bool );
Checks if a Boolean value is true, handling null by returning false.
If you're not limited to the libraries you're "allowed" to include, there are a bunch of great helper functions for all sorts of use-cases, including Booleans and Strings. I suggest you peruse the various Apache libraries and see what they already offer.
Or with the power of Java 8 Optional, you also can do such trick:
Optional.ofNullable(boolValue).orElse(false)
:)
Boolean types can be null. You need to do a null check as you have set it to null.
if (bool != null && bool)
{
//DoSomething
}
if (bool) will be compiled to if (bool.booleanValue()) aka unboxing and that would throw a NullPointerException if bool is null.
Other solutions for nullable boxed Boolean evaluation:
JDK 9+ requireNonNullElse(obj, defaultObj)
import static java.util.Objects.requireNonNullElse;
if (requireNonNullElse(bool, false)) {
// DoSomething
Google Guava 18+ firstNonNull(first, second)
import static com.google.common.base.MoreObjects.firstNonNull;
if (firstNonNull(bool, false)) {
// DoSomething
false is used as the default for the null-case here.
as your variable bool is pointing to a null, you will always get a NullPointerException, you need to initialize the variable first somewhere with a not null value, and then modify it.
Objects.equals()
There is nothing wrong with the accepted answer by K-ballo. If you prefer a single simple condition and like me you don’t like Yoda conditions, since java 1.7 the answer is
if (Objects.equals(bool, true)) {
or if at the same time you prefer to be really explicit
if (Objects.equals(bool, Boolean.TRUE)) {
Or better: avoid the issue
It’s not recommended to use Boolean objects thereby allowing a Boolean reference to be null in the first place. The risk of a NullPointerException like the one you saw is too great. If you need a kind of tri-state logic, it’s better to define an enum with three values. For example
enum MyTristateBoolean { FALSE, DONT_KNOW, TRUE }
Now we don’t need null at all. The middle constant should probably be named UNKNOWN, UNDEFINED, NOT_EXISTING or something else depending on your exact situation. You may even name it NULL if appropriate. Now depending on taste your comparison becomes one of the following two.
if (myBool.equals(MyTristateBoolean.TRUE)) {
if (myBool == MyTristateBoolean.TRUE) {
The latter works since the compiler guarantees that you will only have one instance of each enum constant. As most of you know == doesn’t work for comparing objects of non-enum type for equality.

Categories