For those unfamiliar with contracting:
A contract is a set of conditions which a function or set of statements must agree to uphold. Preconditions are specified which must be met in order for the subsequent statements to be processed. Post conditions must be met at the closing of the contract. If either part of this contract is violated it is an error, it shouldnt happen and means that the function was passed invalid data, thus making contracts a debugging tool.
Here is my admitedly weird and brewt force approach to contracting in C++
//CONTRACT.H
#ifndef _CONTRACT
#define _CONTRACT
class Test_Condition_Violation
{
public:
Test_Condition_Violation(int nLINE, const char*nFILE) : LINE(nLINE), FILE(nFILE)
{
}
int LINE;
const char* FILE;
};
class Contract
{
public:
Contract(const char* nfile, int nline) : file(nfile), line(nline)
{
}
void Test_Conditions(bool a, bool b = true, bool c = true, bool d = true, bool e = true, bool f = true, bool g = true, bool h = true, bool i = true,
bool j = true, bool k = true, bool l = true, bool m = true, bool n = true, bool o = true, bool p = true, bool q = true, bool r = true,
bool s = true, bool t = true, bool u = true, bool v = true, bool w = true, bool x = true, bool y = true, bool z = true,
bool a1 = true, bool b1 = true, bool c1 = true, bool d1 = true)
{
if(a && b && c && d && e && f && g && h && i && j && k && l && m
&& n && o && p && q && r && s && t && u && v && w && x && y && z && a1 && b1 && c1 && d1)
{
}
else
{
Test_Condition_Violation Violation(line, file);
throw(Violation);
}
}
const char* file;
int line;
};
#define Contract Contract Binding(__FILE__, __LINE__); Binding.Test_Conditions
#define Close_Contract Binding.line = __LINE__; Binding.file = __FILE__; Binding.Test_Conditions
#endif
everything next to Contract in parenthesis are the preconditions
everything next to Close_Contract is the post conditions
a violation of either will throw exception Test_Condition_Violation
//EXAMPLE
#include "contractor.h"
#include <iostream>
using namespace std;
int main()
{
int X = 0;
int Y = 0;
try
{
Contract(X == 0);
X += 9;
Close_Contract(X == 10);
}
catch(Test_Condition_Violation &e)
{
cout << "Contract violation at line " << e.LINE << endl << e.FILE<< endl;
}
system("pause");
return 0;
}
the maximum number of contract arguments are 30, I would like any feed back on this, even if its "just accept that c++ isnt a DBC language and move on"
thanks for your time [smile]
[Edited by - raptorstrike on July 4, 2006 3:49:04 PM]
____________________________"This just in, 9 out of 10 americans agree that 1 out of 10 americans will disagree with the other 9"- Colin Mochrie