Android Code Snippet [B4X] Three state Boolean. Or: Is this Boolean variable initialized?

This is a very special snippet, in the sense that I await an approval from Erel or a suggestion on how to do better ?

I "need" to use a Boolean variable but not only to check if it is True or False, even if one of these two values has ever been set, that is, that the variable has been initialized.

Unfortunately, a Boolean variable is initialized by default with False; the ideal would be Undefined or similar, instead.

I could use an Object instead of a Boolean, but that too would cause "problems" (you could mistakenly set it with values of any type).

So I think I'll use this:
B4X:
Type tBoolean(Initialized As Boolean, Value As Boolean)

(and all this very long Snippet ends here ?)

Better (see @OliverA's post below and post #4):
B4X:
Type tBoolean(IsTrue As Boolean)




Please, don't mark this post with too many "Like"s ?
 
Last edited:

OliverA

Expert
Licensed User
Longtime User
Why not use the IsInitialized method of a Type?
B4X:
Type tBoolean(Value As Boolean)
Later
B4X:
Dim tb as tBoolean
Log(tb.IsInitialized)
 

LucaMs

Expert
Licensed User
Longtime User
Another "mad" idea.

If we had:
B4X:
Type tBoolean(Value As Boolean)
then we would usually use:
B4X:
Dim MyVar As tBoolean
MyVar.Initialize
'...
If MyVar.Value Then ' usual but not perfectly explanatory.
    ' Do something
Else
    ' Do something else
End If
or:
B4X:
Dim MyVar As tBoolean
MyVar.Initialize
'...
If MyVar.Value = True Then ' explanatory but longer.
    ' Do something
Else
    ' Do something else
End If

Instead with:
B4X:
Type tBoolean(IsTrue As Boolean)
We would use:
B4X:
Dim MyVar As tBoolean
MyVar.Initialize
'...
If MyVar.IsTrue Then ' explanatory and short.
    ' Do something
Else
    ' Do something else
End If
 

OliverA

Expert
Licensed User
Longtime User
I like the IsTrue part. But... If you are not going to use the IsInitialized for anything (I don't see it in your samples, yet I thought that was part of the need in post#1), then you (in this case) technically do not need to initialize MyVar and can just set IsTrue as you want. But, if that is all you need (a clearer name for a variable), you could have just have named the boolean variable IsTrue. Or did you mean to write something like

B4X:
If MyVar.IsInitialized
    If MyVar.IsTrue Then ' explanatory and short.
        ' Do something
    Else
        ' Do something else
    End If
Else
    'Whatever needs to be done if MyVar is not initialized (the trinary part of this whole exercise)
End If
 

LucaMs

Expert
Licensed User
Longtime User
But... If you are not going to use the IsInitialized for anything
Sure, I need to check if it was initialized, I'm trying to get around the Boolean initialization to False for this reason!

I didn't use it in the examples to write less code and especially to highlight the difference between:
B4X:
If MyVar.Value Then ' usual but not perfectly explanatory.
and:
B4X:
If MyVar.IsTrue Then
 
Top