Why `if (Item.state = ON)` is a really stupid mistake

For a few weeks now I had the strange behavior that State_Vacation would self activate every day - but no time to look into it.
Well, turns out if (Item.state = ON) (assignment) is not the same as if (Item.state == ON) (comparison) - which I did know, but overlooked.
What I didn’t know was, that the first version wouldn’t throw any errors - because hell, who wouldn’t like to make an assignment in an if statement… :flushed:

So every morning my alarm rule wouldn’t check if it should run - no, it would set State_Vacation to ON again… :sob:

4 Likes

Be assured, you are not the first one and certainly not the last to make this mistake. I myself made it more than enough times when programming C… :smirk:

Writing the rules in Python would have avoided at least this mistake… For other languages, like C, you could use a linter but there is probably none available for the openHAB rules DSL.

1 Like

hehe, no, you are not alone :slight_smile:
That and :

if (Item == ON) (assignment)

forgetting the “.state” has caused me quite a lot of fine reading.

2 Likes

The switch to Python (Jython?) is planned for when I find the time to upgrade to openHAB 3.
I’m sure I’ll find ways to make stupid mistakes with Python also :sweat_smile:

Hi @fex,
this bug is a common pattern not only in OpenHAB rules. That is the reason why so many code style guides are written.
My favorit rule is the yoda notation. My colleges always hate it but if you get used to it, it is perfect.
if (ON = item.state) crashes or in other languages does not compile at all.
Easy but otherwise hard to spot.

Hope this syntax gets popular :slight_smile:

2 Likes