Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading