In terms of best/most common practices for programming, where should code go that prevents certain functions from being called, while keeping performance in mind?
for example, if I have a function that can break if called at the wrong time, which of these approaches is most common?
A:
Data *someData = new Data;
while(running)
{
ProcessData(someData);
};
void ProcessData(Data *data)
{
if(data)
data->member = 5;
}
B:
Data *someData = new Data;
while(running)
{
if(someData)
ProcessData(someData);
};
void ProcessData(Data *data)
{
data->member = 5;
}
edit: to clarify, I am asking whether functions should do their own validation, or rely on the client code not to call the function while in the wrong state.
In the case where a function could be 5 calls deep, adding validation to each function could add quite a bit of extra bulk to the code, and potentially hurt performance, but more importantly reduce the readability of the code.
so I am asking what the average developer would expect in this situation
Validating method calls for valid parameters has a performance cost but there’s also a ‘cost’ when errors occur. For example kernel functions can’t allow things to crash internally — it can bring down the entire system.
Generally what I do is look how tightly coupled the caller and callee are. If they are both under your direct control than the callee can probably trust it’s not invoked with crap. But if you have have less control then it may need more validation.