Nested If (x) checks - Better way to write this? - c++

There are places where I check for valid pointers before I perform an operation with them; these checks can be nested pretty deeply sometimes.
For example, I have
if (a)
{
if (a->b())
{
if (a->b()->c())
{
a->b()->c()->DoSomething();
}
}
}
I really don't like the look of this. Is there a way to turn this into something more readable? Ideally,
if (a && a->b() && a->b()->c() )
{
...
}
would be great, but obviously would not work.
EDIT - nvm the example that I put up DOES work as everybody has pointed out. I did test it out to see if this works, but there was a bug in my code in my test. duh!

Why would the latter not work?
In C, && is a short-circuit operator, so it is evaluated from left to right, and if any evaluation is false, evaluation stops.
In fact, you could write:
a && a->b() && a->b()->c() && a->b()->c()->DoSomething();

Quoting from K&R1:
Expressions connected by && or || are evaluated from left to right, and it is guaranteed that evaluation will stop as soon as the truth or falsehood is known.
Therefore the latter example will work perfectly, as WhirlWind has noted.
1 The C Programming Language, Second Edition, Page 21.

Your second example does work in C/C++. It short circuits when the first FALSE value is hit.

You've seen from the other answers that using && will work, and will short-circuit the evaluation when a null pointer is encountered.
The uneasy programmer in me likes to avoid repeating method calls for tests like this since it avoids worrying if they are idempotent or not. One option is to rewrite like this
A* a;
B* b;
C* c;
if ((a=a()) && (b=a->b()) && (c=b->c())) {
c->doSomething();
}
Admittedly verbose and a bit clunky, but at least you know each method is called just once.

Why 'obviously would not work'? Since the && operator only evaluates the right term if the left is valid, the rewrite is perfectly safe.

Since you've already received the direct answer to your question I'll just mention that long chains of calls like you've got there are a code smell and you might consider a better design. Such a design might, in this case, include use of the null object pattern so that your call might just boil down to:
a->CDoSomething();

Chaining works, but it's not necessarily the best general-case answer, particularly because it obscures the failure point. I would instead suggest flattening the tests by inverting the logic so that it exits on failure.
if (!pa)
return Fail("No pa");
B* pb = pa->b();
if (!pb)
return Fail("No pb");
C* pc = b->c();
if (!pc)
return Fail("No pc");
pc->DoSomething();
Same thing, but flat and easy to read. Also, because it immediately handles the failure case, that doesn't get relegated to an else that you might never get around to writing.
In this example, I assumed you didn't want to just silently fail, so I added Fail as a helper that logs the text and returns false. You could also just throw an exception. In fact, if the various methods signaled their failure by throwing an appropriate exception instead of returning null, then all this would be unnecessary. If silent failure was desirable, then a null object pattern would be appropriate.

if (a && a->b() && a->b()->c()) { a->b()->c()->DoSomething(); }
C++ performs lazy evaluation so this will work. First, a would be evaluated and if it's 0 the whole condition is false so there will be no evaluation of the other parts.
This works for the || operator as well. If you write if (a || b), b won't be evaluated if a is true.

Second one will work provided you want to call only DoSomething().

Related

What are the advantages or implications of using assert vs exit or vice versa?

As far as I understand, a call to assert(e), where e is a boolean expression, executes something roughly like if (!e) { printf("%s:%d: failed assertion `%s'\n", __FILE__, __LINE__, e); abort(); } which terminates the program abruptly if the given expression is not true.
On the other hand, instead of using assert, I could probably write something like if (!e) { fprintf(stderr, "custom error message.\n"); exit(1); } which naively feels like a more cleaner, nicer thing to do.
Ignoring that assert can be turned off globally using the NDEBUG flag, what other advantage do you think one has over the other? Have I got the distinction right, or are there conceptual differences between the two which I am unaware of that let the two ways of conditional program termination have their own niche use cases? If the latter, please explain. Thank you.
The biggest advantage of assert is that it makes one's intentions clear. If you see assert(some_condition) then you know what the author's intent was (i.e., some_condition is always true). With your inlined version, I can't assume intention until I actually read your if block, and realize you're going to display an error message and terminate the program.
Less important reasons include that assert reduces copy/paste errors, some_condition is turned into a string automatically (including preservation of variable names), and that tooling can understand it.
what other advantage do you think one has over the other?
A macro is used because you want to be able to remove it via conditional compilation. In other words, you don't want the code to even appear in the binary.
Have I got the distinction right, or are there conceptual differences between the two which I am unaware of that let the two ways of conditional program termination have their own niche use cases?
Well, exit() and abort() don't behave the same way even if you use 1 as a "unsuccessful" exit code. The latter is intended to kill the program right away without further work and possibly trigger a debugging prompt or save an image of the process space (although exactly what it does depends on the vendor providing it). The former calls the registered functions by atexit(). There are other ways of stopping, too, see quick_exit() and _Exit().
For C++, there are way more considerations on the behavioral difference, e.g. whether destructors for variables in the stack frame(s) are run, whether global destructors are run, what happens if an exception is thrown while doing that, etc.
'assert' is a code autotesting tool. Sometimes the program should not stop its work with on client side (release version) even if the condition leading to the execution of the assert was met.
For example:
switch(color)
{
case red:
//...
break;
case green:
//...
break;
default:
assert(false && "unexpected color value. 'enum color' was modified?");
}
another example:
if ( OkOrFailEnum::OK != result )
{
assert(false && "data access fail");
throw std::runtime_error("Can not get index " + std::to_string(index));
}
At the same time, 'assert' is a code commenting tool.
inline unsigned Sum(unsigned* pPos, unsigned* pOffset)
{
assert(nullptr != pPos); // \
assert(nullptr != pOffset); // | preconditions
assert(*pPos + *pOffset < *pOffset && "Overflow?"); // /
return *pPos + *pOffset;
}
The assert:
assert(*pPos + *pOffset < *pOffset && "Overflow?");
means, that the Sum(..) function does not works correctly with big sums and it have to do some check before call the function.

Evaluate expressions until one returns true

I have a savePotentiometerState(...) -function, which returns true if the there were changes to save, and false if nothing was done. Further, I know that on any single pass through my main loop, at most one of the potentiometers may have changed (due to the way they're read out).
This is on a very time-constrained embedded platform, so it's important (or at least matters) that I don't call savePotentiometerState more often than I have to. However, the code I come up with naturally seems silly, something likely to end up at thedailywtf:
if (!savePotentiometerState(pot1))
if (!savePotentiometerState(pot2))
...
if (!savePotentiometerState(potn));
Another way to do this would be to use short-circuit evaluation:
const bool retval = savePotentiometerState(pot1) || savePotentiometerState(pot2) || ... || savePotentiometerState(potn);
I suppose I could even drop the assignment here. But this doesn't feel like good style either, since I'm abusing the short circuiting of the || operator.
The various potn objects are member variables of the containing class, so there's no obvious way to write this as a loop.
I feel like I'm missing something obvious here, so my question is: is there an idiomatic/easy to read way to do this, which doesn't sacrifice efficiency? If it matters, I'm using C++17.
Loop seems the way to go:
for (auto& pot : {std::ref(pot1), std::ref(pot2), /*..,*/ std::ref(potn)}) {
if (savePotentiometerState(pot)) {
break;
}
}
Since you can use C++17 you can leverage fold expressions and write a helper function to do the evaluation for you.
template<typename... Args>
bool returtnPotentiometerState(Args&&... args)
{
return (... || savePotentiometerState(args));
}
and then you would call it like
if (returtnPotentiometerState(pot1, pot2, ..., potn))
This means you don't have a loop, and you get short circuiting.
Personally - I'd avoid the algorithm you're using.
I'd save the state for every pot all the time; and track the current and previous values; and then only call a given callback if if the value had changed.
This way, savePotState is always as fast as it needs to be for a given pot; and you'll never get into the state where pot1 to pot(n-1) can block potn from being read.

Assert() - what is it good for ?

I don't understand the purpose of assert() .
My lecturer says that the purpose of assert is to find bugs .
For example :
double divide(int a , int b )
{
assert (0 != b);
return a/b;
}
Does the above assert justified ? I think that the answer is yes , because if my program
doesn't supposed to work with 0 (the number zero) , but somehow a zero does find its way into the b variable , then something is wrong with the code .
Am I correct ?
Can you show me some examples for a justified assert() ?
Regards
assert is used to validate things that should always be true if the
program is correct. Whether assert is justified in your example
depends on the specification of divide: if b != 0 is a precondition,
then the assert is usually the preferred way of verifying it: if
someone calls the function without fulfilling the preconditions, it is a
programming error, and you should terminate the program with extreme
prejudice, doing as little additional work as possible. (Usually.
There are applications where this is not the case, and where it is
better to throw an exception, and stumble along, hoping for the best.)
If, however, the specification of divide defines somw behavior when b
== 0 (e.g. return +/-Inf), then you should implement this instead of
using assert.
Also, it's possible to turn the assert off, if it turns out that it
takes too much runtime. Generally, however, this should only be done in
critical sections of code, and only if the profiler shows that you
really need it.
FWIW: not related to your question, but the code you've posted will
return 0.0 for divide( 1, 3 ). Somehow, I don't think that this is
what you wanted.
Another aspect of assertions:
They are also a kind of documentation.
Instead of comments like
// ptr is never NULL
// vec has now n elements
better write
assert(ptr!=0);
assert(vec.size()==n);
Comments may become outdated over time and will cause confusion.
But assertions are verified all the time.
Comments can be ignored. Assertions cannot.
You're pretty much spot-on in your assesment of assert, except for the fact you typically use assert during a debug-phase ... This is because you don't want an assert to trigger during production code ... throwing exceptions (and properly handling them) is the proper method for run-time error-management in production level code.
In general though, assert is used for testing an assumption. If an assumed condition is not met in the code during the debugging phase, especially when you are getting values that are out-of-bound for the desired input, you want your program to bail out at the point that the error is encountered so you can fix it. For instance, suppose you were calling a function that returned a pointer, and that function should never return a NULL pointer value. In other words returning a NULL value is not just some indicator of an error-condition, but it means that the assumption of how you imagine your code works is wrong. That is a good place to use assert ... you assume your program will work one way, and if it doesn't then you don't want that error propagating to cause some crazy hard-to-find bug somewhere else ... you want to nix it right when it occurs.
Finally, you can combine built in macros with assert such as __LINE__ and __FILE__ that will give you the file and line number in the code where the assert took place to help you quickly identify the problem area.
The purpose of an assert is to signal out unexpected behavior during debugging (as it's only available in a debug build). Your example is a justified case of assert. The next line would probably crash, but with the assert there you have the option to break execution right before the line is hit, and do some debugging.
This is usually done in parallel with exceptions - you assert to signal that something is wrong, and throw an exception to treat the case gracefully (even exiting the program):
double divide(int a , int b )
{
assert (0 != b);
if ( b )
return a/b;
throw division_by_0_exception();
}
There are cases where you want to continue execution, but still want to signal that something went wrong.
Assert is used to test assumptions about your code in a debug environment. Asserts generally have no effect on your final build.
Whether or not it is a valid test is another matter entirely. We can't answer that without intimate knowledge of your application.
Asserts should never fail. If you see any possibility that the assertion could fail, then you need an if statement instead to handle those cases where the condition is not true. Assertions are only for conditions that you believe will never fail.
Asserts are used to check invariants during code execution, those are the conditions that are assumed by programmer to always stay the same, if they differ from assumptions then there is a bug in the code.
Asserts can be also used for checking preconditions and postconditions, the first is checked before some code block and verifies if provided data/state is correct, the second one checks whether the outcome of some calculations are correct. This helps to narrow where problems/bugs might be located:
assert( /*preconditions*/ );
/*here some algorithm - and maybe more asserts checking invariants*/
assert( /*postconditions*/ );
Some examples of justified asserts:
Checking function return value, for example if you call some external API function and you know that it returns some error value only in case of programming error:
WinAPI Thread32First function requires that provided LPTHREADENTRY32 structure has properly assigned dwSize field, in case of error it fails. This failure should be catched by assert.
If function accepts pointer to some data, then add assert at the start of function to verify that it is non-null. This makes sense if this function cannot work on null pointer.
If you have a lock on mutex with set timeout then if this timeout ends then you can use assert to indicate possible race condition / deadlock
... and many many more
Nice trick with asserts is to add some info inside, ex.:
assert(false && "Reason for this assert");
"Reason for this assert" will show up to you in a message box
You might also want to know that we also have static asserts that indicate errors during compilation.

What is the meaning of NULL != value in C++? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
What is the difference between these (bCondition == NULL) and (NULL==bCondition)?
I was going through a piece of C++ code and came across a code like
if (NULL != threadInfo)
{
...
...
}
I was just wondering is there any difference between using the expression
if (threadInfo != NULL)
{
...
...
}
what is said above.
While reading the first one reads " If NULL not equals to ThreadInfo" and the second one reads "If threadInfo not equals to NULL". To me the second one makes more sense.
No, there is no difference. In case of == there might be some difference. The thing is that if you accidentally write = instead of == the compiler will give an error in the first case.
if (threadInfo = NULL) //always false. The compiler will give you a warning at best
if (NULL = threadInfo) //Compiler error
I personally hate that practice and think it's better to write code that can be read in a normal human language, not Yoda language.
It's for safety, so you don't accidentally write
threadInfo = NULL
instead of
threadInfo == NULL
For the != there's no need to do this, but it's consistent.
If threadInfo is of a type that overrides operator !=, and the owner of that class has not provided a symmetric free function that handles the case where the two arguments are swapped, there might be a difference (there might also be a need to fire that programmer).
Otherwise, it's a matter of taste. Probably it will be preferred by people who write if(42 == answer) instead of if(answer == 42) -- this protects you from mistyping an assignment operator instead of an equals check. But since modern compilers warn you when you do that, it's debatable whether this approach offers anything.
There is no difference. The point of writing NULL != ... is that if you instead make a typo and write NULL = ... the code won't compile. If you had ... = NULL it could be a valid assignment and the error could go unnoticed (but most compilers detect this and warn you). Somebody once tried to insert a backdoor into the Linux kernel using this technique.
Also note that most persons don't code like that.
There is no difference, EXCEPT that the first option cannot be mistyped as:
if (threadInfo = NULL)
{
...
...
}
And some people don't know how to use compiler switches to check this (and some compilers don't have them).
No difference, this is so called Yoda coding convention.
if (NULL != threadInfo)
is equivalent to
if (threadInfo != NULL)
and to
if (threadInfo)
This is usually used as a convention, and has no distinct meaning by itself.
Because assignment occurs to lvals, and NULL is unassignable, this protects against the dreaded threadInfo = NULL when you meant threadInfo == NULL or threadInfo != NULL bug.
For more detail, see this wikipedia article section on left-hand comparisons
Both do the same thing. It is a style convention that was used to avoid typing mistakes as:
if (value=NULL) // assignment instead of == operator
{
}
These are exact equivalents in terms of logic.
The second is more intutive, when one may see the first is seen as more safe as it doesn't allows writing (threadInfo = NULL) erroneously, leading to a bug.
Null is a reference in the memory contains nothing but that nothing have an address to access it.
By that you can make a comparisons behind null to check if a certain object have a value or nothing.
I don't see any difference. However, the practice of writing NULL == someVar would save you from writing NULL = someVar if you forget typing the second =.

Is it good practice to check for null and check object properties in the same if statement

Is it good practice to check for null and check object properties in the same if statement?
Consider the following code:
if (jamesBlunt != null && jamesBlunt.isReallyBad()) {
// Don't buy his records
}
This particular code is in java and I know the expression is evaluated from left to right so technically it won't throw a NullPointerException but in general is this good practice in any language?
As you are using an OR statement there will be a NullPointerException if jamesBlunt is null. You should use and, because if the left statement is false, the whole expression will be false.
Use:
if (jamesBlunt != null && jamesBlunt.isReallyBad()) {
// Don't buy his records
}
When Java 7 is out, you could use the shortcut
if(jamesBlunt?.isReallyBad() {
// Don't buy his records
}
But until then the explicit check for null would be best practice. (In fact it would be best practice to not use jamesBlunt objects...)
I'll assume the || is a typo and you meant && :)
To answer your question: it depends.
Does it make sense for jamesBlunt to ever be null? If not, then it would be better practice to have something like this:
void buyARecord(Artist jamesBlunt) {
if (jamesBlunt == null) {
throw new IllegalArgumentException("James should never be null!");
}
}
If it does make sense for jamesBlunt to be null then your approach is fine, assuming null and isReallyBad mean the same thing semantically. If they mean different things semantically then you should probably not be combining them on one line.
You do need to be careful in other languages. Many (Java, C++, C# etc) will behave the same way, but some may evaluate from right-to-left or evaluate lazily. Take particular care with functional languages like Lisp and Scheme as they tend to behave differently to object oriented languages like Java and C#.
You want to use && instead of OR.
Yes, it is good practice to check for null in the same if statement, the alternative (nesting two ifs) is ugly because adds more indentation.
But checking before is also OK: specially if you want to do some error checking.
Personally, I would separate these. Null checking is the kind of thing one would do at the beginning of a function and is usually done to verify function parameters and are generally called "guard clauses". These checks will often raise an exception or return an error code as defined by the function.
These can lead to cleaner code below, avoiding multiple levels of nesting. It also prevents the need to repeat the null checks if there are other things you wish to test for on the object in question.