How to correctly check item state values - getStateAs, instanceof or directly

As the title aleady says there are different ways of checking item state values. Could somebody please provide some short explanations as to when using one way over the other?

Example 1: (the most obvious one for beginners…)

if (myItem.state == 3.0)
...

Example 2: (not sure, if the syntax is correct)

if ((myItem.state as DecimalType).doubleValue == 3.0)
...

Example 3:

if (myItem.getStateAs(DecimalType) == 3.0)
...

Example 4:

if (myItem instanceof DecimalType) == 3.0)
...
1 Like

A state object is a state object, neither fish nor fowl. Remember valid states can also ON or NULL or 56,75,22 or “banana”, depending on Item type.

DSL rules interpreter will have a guess at what you are trying to do, but sometimes you have to be explicit.
Like -

Java supports lots of different numeric types.
Unless you need some particular form, it is best to treat Number type as DSL “native” type.
if (myItem.state as Number == 3.0)

This one is common failure
if (myItem.state > otherItem.state)
will fail. DSL fails to guess the second one is probably the same type.
if (myItem.state > otherItem.state as Number)
provides enough of a clue for the interpreter.

Nah, broken.
(myItem instanceof DecimalType) is a test, it returns true or false, which will never equal 3.0

Then, this test will never return true, because an Item object is an Item object.
(myItem.state instanceof DecimalType)
is probably what was meant.

1 Like

Many many thanks for your explanations!

yes, I simply forgot to add .state.

ok. I understand that I should „avoid“ #1. But I still do not get which one out of the other three I should preferrably use.
What are you doing in all your rules (but I think you probably do not use DSL, right?)

There simply is no general, valid answer. Everyone has to find out what they feel most comfortable with.
It’s good practice to typecast (... as Number) often and wherever in doubt. Doesn’t even harm if not required.
(well strictly speaking it isn’t typecasting but to provide the DSL interpreter with the hint on data type it might need to properly interpret the code line).

Many thanks Markus.

To me it is not a question of comfortability. In case there are some reason as to why it is recommended to choose one out of the three possibilities, I would adopt this recommendation and simply get used to it.

I certainly do, exclusively.

if (myItem.state == 3.0)
works fine, and uses less ink.

But wait until you discover Units of measurement and Quantity types.

2 Likes

Ultimately it is because you are the programmer. It’s you to write buggy software, and the likelihood of making an error is very much and directly related to how comfortable you feel with a particular choice of programming style.