jeudi 10 juin 2021

Best Practice: stop counter with if or just let it go

I have a very general and simple question. If I have a counter which only should be used when certain conditions are met. Should I stop it from counting when those conditions are off, with an if clause, or should I just leave it counting. What is better: best practice, speed, readability and so on.

Example:

public void activateCount() {
   counter = 0;
   counterMatters = true;
}

public void manipulateCount() {
   
   // this will involve only one if but continue to increment the counter
   // until it is reset with the activateCount() function

   if (counterMatters && counter > 100) {
      //stop counting
      counterMatters = false;
   }
   count++;
   doStuff();

  
   // OR
   // this would include two if's but it would not have the counter continue

   if (countMatters) {
      if (count > 100) {
         // stop counting
         countMatters = false;
      }
      count++;
      doStuff();
   }
 
}

I personally like the first one more because I believe that an if can be slow, less code and it does not affect the code because in this case the counter is reset when necessary.

Aucun commentaire:

Enregistrer un commentaire