Submit Your Site For Free!

Email Address:
* URL:
*
*Indicates Mandatory Field

Terms & Conditions

CProgramTrends
FlashNewz
DevWebPro








Writing A Quality Function Driver

By Bryan Young
Expert Author
Article Date: 2010-12-02

After my last article on writing stubs, I figured I would follow up with how to write function drivers. Where stubs are miniature functions used to test your main code, a driver is a miniature main code to test your functions. Knowing how to write an effective driver is a key tool in producing valuable functions.

Let's take our function from the last article, getGradeFor() and write our function to return our student's grade.


int getGradeFor( string studentName )
{
int grade = -1;
string name = "";
ifstream fin;
if ( !fin.open( "grades.txt" ) )
return -1; // -1 indicates failure

fin >> name >> grade;
while ( fin )
{
if ( studentName == name )
return grade;
}

return -1;
}


For a function like this, we need to be able to test several names and figure out if our function is returning the correct values, so we write a driver separate from out actual code to just test our function.


int main()
{
cout << "Bryan's grade is " << getStudentGrade( "Bryan" ) << endl;
cout << "Mike's grade is " << getStudentGrade( "Mike" ) << endl;
cout << "Taylor's grade is " << getStudentGrade( "Taylor" ) << endl;

return 0;
}


This main code will test that we are pulling the correct values for these three students. We can also feed it names that are not in the file to see that it returns our invalid indicator.

Writing drivers is an important part of the testing process because it allows the programmer to run a function without the overhead of the full main code. It also allows the programmer to be certain of the data that is being passed to and returned from the function, to make testing exact cases accurate.

About the Author:
Bryan Young is a staff writer for WebProNews.



Newsletter Archive | Article Archive | Submit Article | Advertising Information | About Us | Contact

C Programming Trends is an iEntry, Inc. ® publication - All Rights Reserved Privacy Policy and Legal