Home > Mobile >  How to refactor this if statement?
How to refactor this if statement?

Time:05-03

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/.?

CodePudding user response:

This may be an option:

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

CodePudding user response:

  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.

CodePudding user response:

I might take this:

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);
}

and refactor it to something like this:

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

Because conciseness of expression has a utility all its own.

You could even make it a "one-liner", but it just reads weird:

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

The former reads better

  • Related