Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redundant comparison & "if" before assignment

Here is the example:

if(value != ageValue) {   ageValue = value; } 

I mean, if we assign the value of a variable to another one, why would we need to check if they have anyway the same value?

That confuses me. Here is the broader context:

private double ageValue; public double Age {   get {     return ageValue;   }    set {     if(value != ageValue) {       ageValue = value;     }   } } 
like image 845
TheOrlexx Avatar asked Mar 22 '19 12:03

TheOrlexx


1 Answers

Here is a code sample when the check is quite useful:

 public class MyClass {     ...     int ageValue = 0;      public int AgeValue {       get {         return ageValue       }       protected set {         ... // value validation here          // your code starts         if (value != ageValue) {            ageValue = value;          }         // your code ends         else           return; // do nothing since value == ageValue          // ageValue has been changed         // Time (or / and memory) consuming process         SaveToRDBMS();         InvalidateCache();          ...       }      }    ...  

More natural implementation, however, is to check in the very beginning in order to avoid unnecessary computation.

    protected set {       if (ageValue == value)         return;        ... // value validation here       ageValue = value;         // ageValue has been changed       // Time (or / and memory) consuming process       SaveToRDBMS();       InvalidateCache();         ...     } 
like image 100
Dmitry Bychenko Avatar answered Sep 19 '22 14:09

Dmitry Bychenko