How to refactor this if statement?

is that a way to refactor the code below

var foot = foot.transform.position;
var hand = hand.transform.position;
if (distance > 0.5)
        {
          foot = hand;
          foot.transform.Translate(x , y  0);
        }
        else
        {
          foot.transform.Translate(x , y , 0);
         }

like thie below

var foot = foot.transform.position;
var hand = hand.transform.position;
distance > 0.5 ? {
          foot = hand,
          foot.transform.Translate(x , y  0)
                 } 
       : foot.transform.Translate(x , y  0);

or more clean code/.?

>Solution :

  1. There’s no reason to have the same line of code in both the if and else, it can be moved after that logic control.
  2. There’s no reason to have the else, because after we remove the only line, there’d be no lines left.
  3. From Jerry’s comment, it’s better to have descriptive variable names, and make it semantically clear when doing reassignment.
var limb = foot.transform.position;

if (distance > 0.5)
{
    limb = hand.transform.position;
}

limb.transform.Translate(x, y, 0);

No need for ternary operators either.

Leave a Reply