lundi 15 avril 2019

Should I wrap the method in an if-statement or put an if-statement inside of the method itself?

I have a game loop which runs 60 times a second. Inside of that loop I do various operations which is mainly handling of the game logic. It roughly looks like this:

void Update()
{
    RunLogic();
}

void RunLogic()
{
    // running logic
}

Now I want to call 'RunLogic' only if a condition is true. So I add an if-statement.

void Update()
{
    if (condition == true)
    {
        RunLogic();
    }
}

void RunLogic()
{
    // running logic
}

But it doesn't look good because it adds nesting. So try something like this:

void Update()
{
    RunLogic();
}

void RunLogic()
{
    if (condition == false)
        return;
    // running logic
}

Now the logic is inside, with no nesting due to guard clause. But now it's hard to tell whether or not 'RunLogic' will run all the time by looking at Update loop alone.

Things like these make me juggle between two of these choices and I can't settle on either of solutions.

To add, methods like RunLogic are never reused in other places, only inside of Update loop.

Aucun commentaire:

Enregistrer un commentaire