This is a very general programming question that I just want to put out there and see if anyone has any thoughts on it. It shows up time and time again: I have a function somefunction()
which is called a lot, but the very first time its called I want it to behave just a bit differently. Here's an example:
first_time = true;
somefunction(){
// bunch of code...
if (first_time)
{
first_time = false;
// do it this way...
}
else
{
// do it that way...
}
// bunch of code...
}
3 approaches come to mind:
you can do as in the example above where you the notion of "first time" is explicit. Usually the "first time" check is just a boolean check hence its very cheap - but still, when you are doing this in a timer that fires off every few hundred milliseconds, it feels hack-ish.
You duplicate the function and just change the few lines of code that need to be changed when its called the first time and call one function at the start and the other function every other time. Especially if the function is big this looks really ugly IMO.
You break up
somefunction()
and create separate functions for where the code is exactly the same. You then create wrapper functions for the first time and everytime else that utilize these smaller functions. I think this approach is best and is what I'm going to use in my situation involving a timer.
Thoughts? Its my first time asking a general question like this and I hope it creates some interesting discussion :)