Better form of flow control

I'm not sure there is an absolute correct way of doing things and it probably depends on context, but I was wondering which is considered better.

This:
1
2
3
4
5
6
7
8
9
10
11
12
foo()
{
    bar();
}

bar()
{
    if(true)
    {
        // execute
    }
}


or this:
1
2
3
4
5
6
7
8
9
10
11
12
foo()
{
    if(true)
    {
        bar();
    }
}

bar()
{
    // execute
}


The first way makes it so bar() is always called but only executes some code if its if condition is true.

The second way makes it so that bar() is only called if foo()s if condition is true.

Mostly I tend to write code the first way. Which way is considered cleaner or generally better and why? Thanks.
Does no-one have an opinion on this?
Bump.
Patience is a virtue.
Patient bump.
You are right that it depends.

Where does the condition come from? Is it inherent to the input, or does it have to be passed into the function separately?

How many code points call bar()? Is the condition so complex that repeating it in N parts of code makes no sense?

Which is easier to maintain? Which keeps the code more generic and re-usable?
Thanks keskiverto, you make some good points.

How many code points call bar()?

I hadn't considered that. If it's being called in different places, it's probably best to leave the conditional checking to the caller, as each caller will probably have a different condition for calling the function. This way you have greater flexibility in how you use bar() and leave its implementation clean.


Which is easier to maintain? Which keeps the code more generic and re-usable?

Well, it depends I think. For a function like sayHello(), you keep that modular by letting it execute its task and nothing else. The caller can take care of when it's called. However, for a function like handleKeyInput(), I would think it's best to call it every frame regardless of whether or not there was any input from the user and let it do its own key checking. This would be easier to maintain as you have a neat reusable package that can be applied anywhere you want to handle user key input. At least that's how I see it. Am I thinking along the right lines?
Topic archived. No new replies allowed.