To use <= or to use ==


The conditional checks in the robot use less-than-or-equal-to zero, and in the video those are changed to just checking equality with zero. I get why it still works in this circumstance since the setter clamps the values of health. Still, I was wondering if using <= is of any value for defensive programming reasons? Or is it better NOT to in order to catch errors where you might forget to call change_health(x) and instead manipulate the health property directly from the robot.gd script?

I guess this question is about best practices.

  • f
    functionSam replied


    I think I can answer your question, I haven't followed this specific tutorial, so please take my answer with a grain of salt.

    As you mention, the less than or equals to" is used defensively to ensure that (in this case in regards to health) the value is actually lower or below zero. Rarely are there cases (especially if you use float values) where you want to compare two values that they are an exact match, in this case if you were using double equals to compare if health == 0, there might be scenarios where health can go into the negatives because what you are essentially telling your script to do that something will only happen if these 2 values are an exact match with each other.

    In my experience, using double equals is commonly used for bools to check if something is true or false.

    Unless someone can give a better answer, then I really hope this answers the question that you have.

  • a
    andrewjhaugen replied

    Hi Deverson! Just thought I would give me two cents here. I believe you are right in that <= could be a good defensive programming choice. You are also correct that if we use the == syntax, we could potentially crash the game by not using the health setter correctly. It does end up coming down to a bit of a personal preference and you will likely develop your own taste for striking the balance between programming defensively and programming a bit looser. These choices can also be influenced by factors such as how big of a team you are working with and how well your code self documents.

    1 love