I create an object based on a command line option.
In C++
Capture *cc = NULL;
if ( argv[2] == "capture" )
cc = new Capture(<some args>);
Now to use this at different parts of the code, should i create a CaptureStub that contains dummy functions so that null pointer is never accessed. Or is there an easier way?
Thanks
should i create a CaptureStub that contains dummy functions
You mean the Null Object Pattern? Yes that would be fine.
Or is there an easier way?
I'm not sure there's an easier way (Null object patterns is a pretty good way) but a very idiomatic way is to check for NULL
if (cc != NULL)
{
// do something with cc
}
First, your if condition will never be true, since the == compares the address of the string literal capture to the second command line argument. You'll want to change it to something like strcmp("capture", argv[2] == 0) or (string("capture") == string(argv[2])).
Second, I think we need to think through the semantics of what you want. What is the desired behavior if the 'capture' option is not specified? Do noithing? If not, then, as #Doug T. mentions, the Null Object pattern is a good choice, rather than sprinkling your code with comparisons to null.
Capture cc = NULL;
Ugh, that's not a pointer right there. If it compiles it's because the Capture class has an implicit constructor that accepts an int or pointer, or has an operator=.
To correct this use
Capture* cc = NULL;
After that, you should structure your code in a way that you only use the object if it is initialized. If it's not possible, then check every time before you do so.
Related
this is more like an ethical question:
if i have the following code:
void changeInt(int& value)
{
value = 7;
}
and i do:
int number = 3;
changeInt(number);
number will have value 7
I know that when the new stack frame will be created for changeInt function, new variables will be created and &value will point to number.
My concern here is that the caller, if it's not paying attention , can be fooled by thinking that is passing by value which actually, on the function frame , a reference will be created.
I know he can look in the header files and it's a perfect legitimate expression but still I find it unethical a bit :)
i think this should be somehow marked and enforced by syntax. Like in C# where you have ref keyword.
What do you guys think ?
This is one of those things where references are less clear than pointers. However, using pointers may lead to something like this:
changeInt(NULL);
when they actually should have done:
changeInt(&number);
which is just as bad. If the function is as clearly named as this, it's hardly a mystery that it actually changes the value passed in.
Another solution is of course to do:
int calculateNewInt(/* may need some input */)
{
return 7;
}
now
int number = 3;
...
number = calculateNewInt();
is quite obviously (potentially) changing number.
But if the name of the function "sounds like it changes the input value", then it's definitely fair to change the value. If in doubt, read the documentatin. If you write code that has local variables that you don't want to alter, make them const.
const int number = 3;
changeInt(number); /* Makes an error */
(Of course, that means the number is not changeable elsewhere either).
I know he can look in the header files and it's a perfect legitimate expression but still I find it unethical a bit :)
I think that's perfectly normal and part of the language. Actually, this is one of the bad things of C and C++: you have to check the headers all the time when dealing with an unknown API, since when calling a function you don't pass by reference explicitly.
That's not the case for all system languages though. IIRC Rust makes it obligatory to pass references explicitly.
I'm trying to talk to PDFCreator from C++. There seems to be one example of this on various sites with slightly different versions. But something in the example worries me (maybe because I'm not a COM expert)...
PDFCreator::_clsPDFCreatorOptionsPtr opt = pdfObject->GetcOptions();
opt->UseAutosave = 1;
opt->UseAutosaveDirectory = 1;
opt->AutosaveDirectory = "c:\\temp\\";
opt->AutosaveFormat = 0; // for PDF
opt->AutosaveFilename = "gigi13";
pdfObject->PutRefcOptions(opt);
So I get a pointer to the PDFCreator options, set them to what I want, then use PutRefcOptions to set the options inside PDFCreator.
So my stupid question is, if I've got a pointer to the options, aren't I just setting them directly when I, for example, opt->AutoSave = 1 ?
Or does the PDFCreator::_clsPDFCreatorOptionsPtr hold a copy of the options? Maybe it is because PDFCreator::_clsPDFCreatorOptionsPtr is a smart pointer and so holds a copy of the options?
As far as I can tell (now!). opt is a smart pointer which creates a copy of the contents of the pdfObiect.
So I modify that copy and then send it back to pdfCreator. Makes sense.
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?
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.
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().