Search code examples
performanceif-statementcoding-styleequation

Instead of using if's, would it better to write an 'equation' that gives you the results you want? (in cases where it makes sense)


Instead of:

float dotProduct = Vector3.Dot(dir, transform.right);
int front = 0;
int back = 0;

if (dotProduct > 0)
{
    // right
    front = 1;
    back = -1;
}
else if (dotProduct < 0)
{
    // left
    front = -1;
    back = 1;
}

Rotate(front, back, angle);

Having something like

float dotProduct = Vector3.Dot(dir, transform.right);
int front = Mathf.Abs(dotProduct) ...;
int back = Mathf.Abs(dotProduct) ...;
Rotate(front, back, angle);

Errh, I know int front = Mathf.Abs(dotProduct) ...; wont give me either 1 or -1, but I think you understand what I'm thinking, instead of using if's, I'd be "funneling" through an equation that would give me either 1 or -1.


Solution

  • I would either expect you to bring real example in question or just don't bother about it unless you want to do something beyond just if/else. Your original code is fine. It can be written in shorter way, however. That's using ternary operator.

    float dotProduct = Vector3.Dot(dir, transform.right);
    int front = dotProduct > 0 ? 1 : -1;
    int back = dotProduct < 0 ? 1 : -1;
    Rotate(front, back, angle);
    

    You see just 4 lines. Almost every programmer knows ternary operator. So this new code does not introduce any complexity for your peers. In fact it's cleaner.