Should I use assert to validate a third party function?

I am using some third party function that, based on a filter, returns a specified number of objects:

//void GetObjects(std::vector<T>&, Filter, int /*objectsNumber*/)

GetObjects(vec, filter, 1);

if(vec.empty())
{
   throw ObjectNotFound();
}

assert(vec.size() == 1);

      

Should I use assert like above? Is this a typical approval scenario?

+3


source to share


2 answers


How you handle errors in your program depends on you and the nature of your program.

In a production environment, you usually try not to assert because then that means your application dies. In other cases, the process running your program would mean that your program died and then restart it.

If it's just for teaching / learning, validating with the correct message is a good way to find your problem quickly and quickly.



Bottom line - it really depends on you. There is no right or wrong here.

If you want to argue, usually you only do so when some very basic invariant / condition is not met, when your program simply cannot know how to proceed from that point.

+1


source


Well, assert()

it's a macro that allows you to turn off validation code for production code, so while ensuring that the outer function conforms to the interface contract, it is a good practice to use assert to enforce the function specification.



Either way, you will get better results using mock instances and some unit testing units as it allows you to contract with a finer impact on external errors. I recommend to you and , and glad to see these ideas circulating in these environments :)

0


source







All Articles