user19013398
user19013398

Reputation:

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

Upvotes: 0

Views: 91

Answers (3)

Victor
Victor

Reputation: 2371

This may be an option:

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

Upvotes: 1

Nicholas Carey
Nicholas Carey

Reputation: 74375

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

Upvotes: 0

gunr2171
gunr2171

Reputation: 17579

  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.

Upvotes: 0

Related Questions