tags:

views:

56

answers:

3

I have some data being loaded from a server, but there's no guarantee that I'll have it all when the UI starts to display it to the user. Every frame there's a tick function. When new data is received a flag is set so I know that it's time to load it into my data structure. Which of the following ways is a more sane way to decide when to actually run the function?

AddNewStuffToList()
{
    // Clear the list and reload it with new data
}

Foo_Tick()
{
    if (updated)
        AddNewStuffToList();

    // Rest of tick function
}

Versus:

AddNewStuffToList()
{
    if (updated)
    { 
        // Clear the list and reload it with new data
    }
}

Foo_Tick()
{
    AddNewStuffToList();

    // Rest of tick function
}

I've omitted a lot of the irrelevant details for the sake of the example.

A: 

You should probably not run the function until it is updated. That way, the function can be used for more purposes.

Let's say you have 2 calls that both are going to come and put in data to the list. With the first set up, checking the variable inside of the function, you could only check if one call has came in. Instead, if you check it in the function that calls the data, you can have as many input sources as you want, without having to change the beginning function.

Functions should be really precise on what they are doing, and should avoid needing information created by another function unless it is passed in.

Chacha102
+1  A: 

IMHO first one. This version separates:

  • when to update data (Foo_Tick)

FROM

  • how to loading data (AddNewStuffToList()).

2nd option just mixing all things together.

dimba
A: 

In the first version the simple variable check "updated" will be checked each time and only if true would AddNewStuffToList be called.

With the second version you will call AddNewStuffToList followed by a check to "updated" every time.

In this particular instance, given that function calls are generally expensive compared to a variable check I personally prefer the first version.

However, there are situations when a check inside the function would be better. e.g.

doSomething(Pointer *p){
  p->doSomethingElse(); 
}

FooTick(){
  Pointer *p = new Pointer();
  // do stuff ...
  // lets do something 

  if (p){
    doSomething(p);
  }
}

This is clumbsy because every time you call doSomething you should really check you're not passing in a bad pointer. What if this is forgotten? we could get an access violation. In this case, the following is better as you're only writing the check in one place and there is no extra overhead added because we always want to ensure we're not passing in a bad pointer.

doSomething(Pointer *p){
  if (p){
    p->doSomethingElse(); 
  }
}

So in general, it depends on the situation. There are no right and wrong answers, just pros and cons here.

Matt H