For example:
void Date::month(unsigned int inMonth) {
assert(inMonth <= 12);
_month = inMonth;
}
If this is not good practice, what is the correct way to go about this?
You shouldn't use assert to ensure that an argument to a public member function is valid. The reason is that there's no way for clients of your class to react to a failed assertion in any meaningful way (the fact that asserts are removed from release builds does not help either).
As a rule of thumb, assert should only be used for things that are strictly under your control (e.g., an argument of a private method).
In this case you're better off throwing a std::invalid_argument exception:
void Date::month(unsigned int month)
{
if(month == 0 || month > 12)
{
throw std::invalid_argument("a month must be in the [1-12] range");
}
_month = month;
}
Yes it is.
This is the right way.
Although I would call it setMonth() rather than month()
Also bare in mind that assert() is preprocessed into nothing in release builds. so if you want something that also works in release then either write your own assert or do a proper run-time check.
Another way that also gives the code more readability would be defining an enumerated type for month:
enum e_Month {
e_Month_January,
e_Month_February,
e_Month_March,
// etc..
e_Month_December
};
Now your assignment becomes:
void Date::month(e_Month inMonth) { _month = inMonth; }
Most compilers will cause an error for assigning another type to enum so you get compile time safety that it will always be in range.
That's fine, you can assert whenever it's unexpected input in your application.
In addition throw an exception something like ArgumentException in addition since you don't want to set an invalid month value.
Related
Is there any way to "force" a function parameter to follow some rule in C++ ?
For the sake of example, let say I want to write a function which computes the n'th derivative of a mathematical function. Let suppose the signature of the function is this one :
double computeNthDerivative(double x, unsigned int n);
Now, let say I want to forbid users to input 0 for n. I could just use an assert or test the value and throw an exception if the user input is 0.
But is there any other way of doing this kind of stuff ?
Edit : Conditions would be set at compile time, but the check must be done at the run-time.
You can prevent the use of 0 at compile time, using templates.
template <int N>
double computeNthDerivative(double x)
{
// Disallow its usage for 0 by using static_assert.
static_assert(N != 0, "Using 0 is not allowed");
// Implement the logic for non-zero N
}
To prevent the use of the function for 0 at run time, it's best to throw an exception.
double computeNthDerivative(double x, unsinged int n)
{
if ( n == 0 )
{
throw std::out_of_range("Use of the function for n = 0 is not allowed.");
}
// Implement the logic for non-zero n
}
class Policy {
private:
String myPolicy;
public :
Policy(String regEx) : myPolicy(regEx) {
}
void verify(int n) {
regEx strtok , sprintf, blah, blah n
};
class Asserted {
private:
Policy policy;
public:
Asserted(Policy policy, int n) throw AAAHHHHH {
policy.verify(n);
}
};
Then finally
Asserted assert = new Asserted(Policy("[1-9]", 8))
double computeNthDerivative(2.6, assert);
I think the best way here is to throw an exception. This is what exceptions are for, even the name seems to suggest this.
As to the assert macro, there is one important caveat. If you use the assert macro, the program will abort if the assertion is not met. However, if you ever make a release build where the NDEBUG macro is set, all assertions will be removed during compilation. This means that you cannot check for valid user input with this macro (because you should build a release build).
The only rules are that you give in. If users are the ones that you want to restrict, you have to check what they give in.
Same goes for the functions, however in your case what you showed as an example it is better to check the variable after the cin (or whatever imput you prefer) rather than checking it in the function itself. For this i would just go
if n!=0;
your function
else break;
So if you are looking for a "Policy" based solution you could create a separate class which accepts a defining regular expression (or whatever you define as a policy) and the input, in this case n, which would then be used as the input to your function.
Imaging a class which is doing the following thing
class AClass
{
AClass() : mode(0) {}
void a()
{
if (mode != 0) throw ("Error mode should be 0");
// we pass the test, so now do something
...
mode = 1;
}
void b()
{
if (mode != 1) throw("Error mode should be 1");
// we pass the test, so now do something
...
}
int mode;
};
The class contains many methods (easily than 20) and for each one of these methods we need to do a check on the value of mode which is obviously a lot of code duplication. Furthermore, we can identify two categories of methods, those who will throw an error if mode !=0 and those who will throw an error if mode != 1. Could it somehow be possible to group these methods in two categories (category A = method who throw an error if mode != 0) and category B for method who throw an error if mode != 1)?
EDIT: Looking at the current answers I realise the way I formulate the question and the problem is probably not clear enough. What I want to avoid is to have to call for a function in each method of the class. Whether we write code at the beginning of the methods or put this code in a function and call this function is not the problem. The question is whether we can avoid this all together. Whether there is a technique that would help to automatically check whether the call to a method of a class is valid depending on some context.
AClass is actually an API in the context of my project. a(), b(), etc. are some functions that the programmer can call if she/he wants to use the API however some of these methods can only be called in some precise order. For example you can see in the code that a() sets mode = 1. So the programmer could do something like this:
a(); // mode = 0 so it's good
b(); // mode = 1 so it's good
but this code needs to fail (it will compile of course but at execution time I need to throw an error mentioning that the context in which b() was called was wrong.
b(); // mode 0 so it won't work
a(); // it will compile but throw an exception
I tried to see if any pattern could work for doing this but couldn't find anything at all. It seems impossible to me and I believe the only option is really to write the necessary code. Could anyone though suggest something? Thank you very much.
Just add private member functions:
void assert_mode_0() {
assert_mode(0);
}
void assert_mode_1() {
assert_mode(1);
}
void assert_mode(int m) {
if (mode != m)
throw msg[m];
}
with a suitable definition of msg, of course.
Aside from implementing the check in a dedicated method (a great suggestion), you could also consider decomposing the behavior in AClass into two distinct classes, or delegate the specific portion to a new pair of classes. This seems especially appropriate if the mode is invariant for an instance (as it is in the example).
Well I guess the simplest solution would be defining a macro or some inline function like this:
#define checkErrorMode0(x) \
if ((x) != 0) throw ("Error mode should be 0");
#define checkErrorMode1(x) \
if ((x) != 1) throw ("Error mode should be 1");
// or, probably within your class
inline void checkErrorMode0(int x){
if ( x != 0 ) throw ("Error mode should be 0");
}
inline void checkErrorMode1(int x){
if ( x != 1 ) throw ("Error mode should be 1");
}
So you could simply call one of these methods inside of the functions that require them.
But most likely there is a more elegant workaround for what you want to do.
After looking into the problem a bit more, it seems that the closest helpful answer is (by Nick):
Try looking into Aspect Oriented Software Development en.wikipedia.org/wiki/Aspect-oriented_software_development – Nick
The Wikipedia page is not easy to read and doesn't provide a C++ example, so it stays very abstract at first, but if you search for Aspect Oriented Programming and C++ you will find links with examples.
The idea behind it (and it just a very quick summary) is to find a way of adding "services" or "functionalities" to a class. These services can notably be added at compile time through the use of templates. This is what I was intuitively experimenting with as an attempt at solving my problem, and I am glad to see this technique has been around for many years.
This document is a good reference:
Aspect-Oriented Programming & C++ By Christopher Diggins, August 01, 2004.
And I found this link with example useful to understand the concept:
Implementing Aspects using Generative Programming by Calum Grant.
I am looking for someones opinion about the usage of std::logic_error instead of using a complicated list of nested if/elseif return true/false.
I would like to move from a lot of similar function like the one below
bool validate_data(){
std::vector<int> v;
//fill with data
if( v.find(10) == v.end() ){
return false;
}
// other checks that return false
}
to
bool validate_data(){
std::vector<int> v;
//fill with data
if( v.find(10) == v.end() ){
throw std::logic_error("error message");
}
// other checks that return false
}
and call all this list of functions in a single try-catch block.
Since it is a derived from std::exception probably I don't know if it is a good idea.
Is anyone using like the example below?
Thanks a lot
AFG
You should only use exceptions for exceptional circumstances. Using (and checking) return values is far more efficient when the chances of it being true or false are non-trivial. Exceptions are more efficient only when the chance of throwing is so small as to out-weigh the cost of the return-value check.
So if the chances of invalid data are very very low, then go with exceptions. Otherwise, the current solution should not only be fine, but slightly more efficient as well (As throwing and handling is relatively expensive).
Only use exceptions for exceptional situations.
Is not finding the value 10 an exceptional situation? Or is it just a normal situation?
Renaming your method from validate_data to is_data_valid makes it much clearer. If the method returns true, it's valid. If it returns false, it isn't. No need to use exceptions for this.
Since your function is called validate_data() I'd only throw an exception if there is any internal error within the function and use true or false to indicate that the function did validate the input, but it was either valid (return true) or invalid (return false).
This will not prevent you from having multiple if() else if() else constructs but it will make the code cleaner and easier to distinguish if the data were invalid or an internal error happened.
try {
bool valid = validate_data(foo);
/* process data or break if invalid */
} catch (std::exception &ex) {
/* internal error happened */
}
as you can see it will make your code longer, IMHO cleaner.
I have a setup that looks like this.
class Checker
{ // member data
Results m_results; // see below
public:
bool Check();
private:
bool Check1();
bool Check2();
// .. so on
};
Checker is a class that performs lengthy check computations for engineering analysis. Each type of check has a resultant double that the checker stores. (see below)
bool Checker::Check()
{ // initilisations etc.
Check1();
Check2();
// ... so on
}
A typical Check function would look like this:
bool Checker::Check1()
{ double result;
// lots of code
m_results.SetCheck1Result(result);
}
And the results class looks something like this:
class Results
{ double m_check1Result;
double m_check2Result;
// ...
public:
void SetCheck1Result(double d);
double GetOverallResult()
{ return max(m_check1Result, m_check2Result, ...); }
};
Note: all code is oversimplified.
The Checker and Result classes were initially written to perform all checks and return an overall double result. There is now a new requirement where I only need to know if any of the results exceeds 1. If it does, subsequent checks need not be carried out(it's an optimisation). To achieve this, I could either:
Modify every CheckN function to keep check for result and return. The parent Check function would keep checking m_results. OR
In the Results::SetCheckNResults(), throw an exception if the value exceeds 1 and catch it at the end of Checker::Check().
The first is tedious, error prone and sub-optimal because every CheckN function further branches out into sub-checks etc.
The second is non-intrusive and quick. One disadvantage is I can think of is that the Checker code may not necessarily be exception-safe(although there is no other exception being thrown anywhere else). Is there anything else that's obvious that I'm overlooking? What about the cost of throwing exceptions and stack unwinding?
Is there a better 3rd option?
I don't think this is a good idea. Exceptions should be limited to, well, exceptional situations. Yours is a question of normal control flow.
It seems you could very well move all the redundant code dealing with the result out of the checks and into the calling function. The resulting code would be cleaner and probably much easier to understand than non-exceptional exceptions.
Change your CheckX() functions to return the double they produce and leave dealing with the result to the caller. The caller can more easily do this in a way that doesn't involve redundancy.
If you want to be really fancy, put those functions into an array of function pointers and iterate over that. Then the code for dealing with the results would all be in a loop. Something like:
bool Checker::Check()
{
for( std::size_t id=0; idx<sizeof(check_tbl)/sizeof(check_tbl[0]); ++idx ) {
double result = check_tbl[idx]();
if( result > 1 )
return false; // or whichever way your logic is (an enum might be better)
}
return true;
}
Edit: I had overlooked that you need to call any of N SetCheckResultX() functions, too, which would be impossible to incorporate into my sample code. So either you can shoehorn this into an array, too, (change them to SetCheckResult(std::size_t idx, double result)) or you would have to have two function pointers in each table entry:
struct check_tbl_entry {
check_fnc_t checker;
set_result_fnc_t setter;
};
check_tbl_entry check_tbl[] = { { &Checker::Check1, &Checker::SetCheck1Result }
, { &Checker::Check2, &Checker::SetCheck2Result }
// ...
};
bool Checker::Check()
{
for( std::size_t id=0; idx<sizeof(check_tbl)/sizeof(check_tbl[0]); ++idx ) {
double result = check_tbl[idx].checker();
check_tbl[idx].setter(result);
if( result > 1 )
return false; // or whichever way your logic is (an enum might be better)
}
return true;
}
(And, no, I'm not going to attempt to write down the correct syntax for a member function pointer's type. I've always had to look this up and still never ot this right the first time... But I know it's doable.)
Exceptions are meant for cases that shouldn't happen during normal operation. They're hardly non-intrusive; their very nature involves unwinding the call stack, calling destructors all over the place, yanking the control to a whole other section of code, etc. That stuff can be expensive, depending on how much of it you end up doing.
Even if it were free, though, using exceptions as a normal flow control mechanism is a bad idea for one other, very big reason: exceptions aren't meant to be used that way, so people don't use them that way, so they'll be looking at your code and scratching their heads trying to figure out why you're throwing what looks to them like an error. Head-scratching usually means you're doing something more "clever" than you should be.
I have come to something of a crossroads. I recently wrote a 10,000 line application with no TDD (a mistake I know). I definitely ran into a very large amount of errors but now I want to retrofit the project. Here is the problem I ran into though. Lets take a example of a function that does division:
public int divide (int var1, int var2){
if (var1 == 0 || var2 == 0)
throw new RuntimeException("One of the parameters is zero");
return var1 / var2;
}
In this situation I'm throwing a runtime error so that I can fail and at least find out that my code is broke somewhere. The question is 2 fold. First, am I making the correct use of the exceptions here? Secondly how do I write a test to work with this exception? Obviously I want it to pass the test but in this case it's going to throw an exception.
Not too sure how one would work that out. Is there a different way that this is generally handled with TDD?
Thanks
First, your first argument (the numerator) being zero probably shouldn't cause an exception to be thrown. The answer should just be zero. Only throw an exception when a user tries to divide by zero.
Second, there are two ways (using JUnit) to test that exceptions are thrown when they should be. The first "classic" method:
#Test
public void testForExpectedExceptionWithTryCatch()
throws Exception {
try {
divide (1, 0);
fail("division by zero should throw an exception!");
} catch (RuntimeException expected) {
// this is exactly what you expect so
// just ignore it and let the test pass
}
}
The newer method in JUnit 4 uses annotations to cut down on the amount of code you need to write:
#Test(expected = RuntimeException.class)
public void testForExpectedExceptionWithAnnotation()
throws Exception {
divide (1, 0);
}
Here, because we added (expected = RuntimeException.class) to the annotation, the test will fail if the call to divide doesn't throw a RuntimeException.
To answer your first question:
If it's quite likely the denominator argument to divide will be 0 then you shouldn't be using exception handling to trap the error. Exceptions are expensive and shouldn't be used to control program flow. So you should still check, but return an error code (or use a nullable type as the return value) and your calling code should check on this and handle it appropriately.
public int? divide (int var1, int var2)
{
if (var2 == 0)
{
return null; // Calling method must check for this
}
return var1 / var2;
}
If zeros are truly the exception - e.g. there should be no way that they can be passed - then do as you do now.
To answer your second question:
In your test methods that check the failure code you need an exception handler:
try
{
divide (1, 0);
// If it gets here the test failed
}
catch (RuntimeException ex)
{
// If it gets here the test passed
}
I am not answering your main question.
I would suggest using ArgumentException instead of RuntimeException.
EDIT: I am assuming .net :)
Your question was language-agnostic, so my answer might not apply, but NUnit in .NET (and I believe JUnit too) have a specific notation for testing exceptions. In NUnit, your test would look like this:
[Test]
[ExpectedException(typeof(RuntimeException))]
public void DivideByZeroShouldThrow()
{
divide(1,0);
}
The test will fail if the right type of exception is not thrown during the execution.
The try/catch approach works too, and has its advantages (you can pinpoint exactly where you expect the exception to occur), but it can end up being pretty tedious to write.
The first question is answered well by ChrisF and Bill the Lizard.
I just want to add an alternative to the exception test, with C++11 you can use a lambda directly in your test.
Assert::ExpectException<std::invalid_argument>([] { return divide(1,0); }, "Division by zero should throw an exception.");
This is equivalent to:
try
{
divide(1,0);
Assert::Fail("Division by zero should throw an exception.");
}
catch(std::invalid_argument)
{
//test passed
}