Comment On Defensive Programming and a Whole Lot More

"Some programmers like to program defensively," wrote Sam, "and then there's some of my coworkers. This is found at the top of nearly every function of our C++ classes." [expand full text]
« PrevPage 1 | Page 2 | Page 3Next »

Re: Defensive Programming and a Whole Lot More

2009-05-15 09:01 • by Code Dependent
if (!comment) return fist;

Re: Defensive Programming and a Whole Lot More

2009-05-15 09:05 • by Scott (unregistered)
global_NewAceUser_Yes=No
global_NewAceUser_No=Yes

That's called default deny. It's mandatory in all security software for Sarbanes Oxley compliance.

Re: Defensive Programming and a Whole Lot More

2009-05-15 09:07 • by Jerry (unregistered)
Josh's predecessor seemed to miss out on the fundamentals the request/response paradigm.

... while Josh, in turn, missed out on the fundamentals the English grammar.

Re: Defensive Programming and a Whole Lot More

2009-05-15 09:13 • by kastein
I bet whoever wrote the "do I exist" C++ class defense noticed that that was checked after "new <whateverclass>" every time, so he figured hey, I can put this code in one place and stop duplicating it! Either that, or it's from some abomination of a mixed-language application and the class is used through some strange wrapper from another language and might not be trusted to actually set the "this" pointer while calling. Either way, WTF?

Re: Defensive Programming and a Whole Lot More

2009-05-15 09:25 • by Blob (unregistered)
262686 in reply to 262669
Jerry:
Josh's predecessor seemed to miss out on the fundamentals the request/response paradigm.

... while Josh, in turn, missed out on the fundamentals the English grammar.


"of" has been deprecated

Re: Defensive Programming and a Whole Lot More

2009-05-15 09:25 • by Code Dependent
// Function to confirm before deletion
function Custom_Confirm(message)
{
// Show confirmation message
var confirmation = confirm(message);

// If confirmed then return false to stop form submit
if (!confirmation)
{
return false;
}
else
{
return true;
}
}
Boy, that's a case of taking the taxi across town to get to your next door neighbor's house.

The logic here all hinges on what is returned for what state by confirm(message). The comment says "If confirmed then return false", but then they return false for ! confirmation. I imagine the comment was supposed to say:
// If not confirmed then return false to stop form submit

So instead of:
var confirmed = Custom_Confirm(messageToConfirm);

...how about this?
var confirmed = confirm(messageToConfirm);

Re: Defensive Programming and a Whole Lot More

2009-05-15 09:28 • by Code Dependent
262690 in reply to 262686
Blob:
Jerry:
Josh's predecessor seemed to miss out on the fundamentals the request/response paradigm.
... while Josh, in turn, missed out on the fundamentals the English grammar.
"of" has been deprecated
Yes, "the" is now used in its place.

Re: Defensive Programming and a Whole Lot More

2009-05-15 09:31 • by Tom C (unregistered)
if (!this) return false;

Gives the optimizer something to work with, making the runtime more efficient.

(And is it just me, or has this site become a lot more boring since TopCod3r went silent?)

Re: Defensive Programming and a Whole Lot More

2009-05-15 09:32 • by Gnubeutel (unregistered)

Boolean answer = new Boolean(
inp.equals("true")
? new Boolean(true)
: new Boolean(false)).booleanValue();


That is wrong on so many levels. It should be used as an example in programming classes.
I count at least three redundant/useless operations and another three things you shouldn't do because there are more efficient ways. And i'm probably missing some more.
I just hope there were a lot of blind mass refactorings involved in the creation of this statement.

Re: Defensive Programming and a Whole Lot More

2009-05-15 09:34 • by Médinoc (unregistered)
262695 in reply to 262677
kastein:
I bet whoever wrote the "do I exist" C++ class defense noticed that that was checked after "new <whateverclass>" every time, so he figured hey, I can put this code in one place and stop duplicating it! Either that, or it's from some abomination of a mixed-language application and the class is used through some strange wrapper from another language and might not be trusted to actually set the "this" pointer while calling. Either way, WTF?

Unlike Java, it's possible in C++ to call a class member function from a null pointer. If the function is not virtual, the program will not crash before entering it, and it won't crash inside the function either if no member variables are accessed.

An Example from a well-known UI class library:
HWND CWnd::GetSafeHwnd()

{ return this ? m_hWnd : null; }

Re: Defensive Programming and a Whole Lot More

2009-05-15 09:34 • by Jamie (unregistered)
262696 in reply to 262686
Blob:
Jerry:
Josh's predecessor seemed to miss out on the fundamentals the request/response paradigm.

... while Josh, in turn, missed out on the fundamentals the English grammar.


"of" has been depreciated


FTFY

Re: Defensive Programming and a Whole Lot More

2009-05-15 09:36 • by Henning Makholm (unregistered)
I'm not convinced that "if(!this)" is a WTF. For a nonvirtual function, most compilers would probably be happy to produce code that called the function through a null pointer. (This is probably undefined behavior at runtime, but by far the most common *actual* behavior must be to attempt to execute the function body with this being null).

On the other hand, silently returning false as a defensive action is a lot more questionable. That just exchanges a segfault-and-core-dump here and now with wrong results further down the road that could be a lot harder to debug.

Perhaps the product of faulty metrics, such as "the programmer in whose code the segfault occurred is to be blamed for the bug"?

Re: Defensive Programming and a Whole Lot More

2009-05-15 09:36 • by jspenguin
The C++ one is obviously some kind of attempt to defend against dereferencing NULL pointers. It fails miserably under the following conditions:

1. Member access
2. Virtual methods
3. Multiple inheritance, when the method is in a base class that is *not* the first class:


class A {
public:
int a;
virtual ~A() { }
};

class B {
public:
int b;
virtual ~B() { }
bool nullprotect() {
if (!this) return false;
return (b != 0);
}
};

class C : public A, public B {
public:
int c;
};

int main() {
B* pb = NULL;
C* pc = NULL;

cout << "pb: " << pb->nullprotect() << endl; // prints "pb: false"
cout << "pc: " << pc->nullprotect() << endl; // segfault!

}



The reason is that in order to get a pointer to B from a pointer to C, you have to add a constant offset (8 bytes on a 32-bit system), so when pc->nullprotect() is called, this is (B*)0x8.

If nullprotect were virtual, the compiler would actually generate a tiny "thunk" function that adds a constant value to this and jumps to the original function.

Re: Defensive Programming and a Whole Lot More

2009-05-15 09:38 • by AC (unregistered)
262700 in reply to 262699
It's like running across those branches that begin with a comment saying "this should never happen"

Re: Defensive Programming and a Whole Lot More

2009-05-15 09:40 • by amischiefr
global_NewAceUser_Yes=No
global_NewAceUser_No=Yes

This was obviously written by a woman. When they say yes it means no and when they say no it means yes. At least that's what I told the judge.

Re: Defensive Programming and a Whole Lot More

2009-05-15 09:46 • by Tom C (unregistered)
262703 in reply to 262701
amischiefr:
global_NewAceUser_Yes=No
global_NewAceUser_No=Yes

This was obviously written by a woman. When they say yes it means no and when they say no it means yes. At least that's what I told the judge.

I hope, for your sake, the "jury of your peers" was all male.

Then again...

Judge: Guilty?

Male jurors: No.

Female jurors: Yes.

So, you're fine.

Re: Defensive Programming and a Whole Lot More

2009-05-15 09:49 • by Buddy (unregistered)
if (!this) return false;

It's perfectly legitimate because it's entirely possible to cast NULL to an object and use it to call non-virtual functions. Not smart or safe, but you'll see it throughout MS code.

E.g.

HDC hdc = ((CDC *)NULL)->GetSafeHdc();

Yet another gotcha of C++...





Re: Defensive Programming and a Whole Lot More

2009-05-15 09:55 • by Leo (unregistered)
The Real WTF is caring whether code works in IE6 or not. Bet it doesn't work in Lynx, SlipKnot, or Netscape 3 either.

Re: Defensive Programming and a Whole Lot More

2009-05-15 09:55 • by Vollhorst (unregistered)
262707 in reply to 262704
Buddy:
if (!this) return false;

It's perfectly legitimate ...

Yet another gotcha of C++...
Aye, it is a simple solution of null pointer problems. It is no good design but sometimes it really makes sense.

Some people simply forget that member functions of classes are nothing else then normal class-less functions with a hidden parameter (this).

Re: Defensive Programming and a Whole Lot More

2009-05-15 10:01 • by methinks (unregistered)
262710 in reply to 262693

Boolean answer = new Boolean(
inp.equals("true")
? new Boolean(true)
: new Boolean(false)).booleanValue();
"We had a strange problem wherein a procedure wasn't always returning the expected value," writes Jake T, "upon digging through the procedure's code, it was pretty apparent why."
ALTER FUNCTION [CMM].[FetchItemCode]
(
)
RETURNS bigint
AS
BEGIN
RETURN 29654
END


Well, unless of course you expect 29654 as the answer, which the OP doesn't say isn't the case...

Re: Defensive Programming and a Whole Lot More

2009-05-15 10:04 • by Stilgar
262711 in reply to 262693
The real WTF is Java's boxing model!

Re: Defensive Programming and a Whole Lot More

2009-05-15 10:04 • by Rootbeer
262712 in reply to 262706
Leo:
The Real WTF is caring whether code works in IE6 or not. Bet it doesn't work in Lynx, SlipKnot, or Netscape 3 either.


IE6 still accounts for 15% of the traffic to the site I operate at my day job. Do you think management would be happy if sales were to drop by 15%?

Booleans a-go-go

2009-05-15 10:08 • by Georgem (unregistered)
Mine's bigger

Boolean[] values = new Boolean[new Boolean(Boolean.TRUE), new Boolean(Boolean.FALSE)]

Re: Defensive Programming and a Whole Lot More

2009-05-15 10:08 • by Tom C (unregistered)
262714 in reply to 262706
Leo:
The Real WTF is caring whether code works in IE6 or not. Bet it doesn't work in Lynx, SlipKnot, or Netscape 3 either.

I attended a two hour information security class last night. When I saw all their computers were running IE6.0, I concluded I wasn't going to be learning anything useful from them. And this indeed turned out to be the case.

More peculiar was that when I pointed it out to the others in the class -- all alleged security pros -- the most common response was "what version should it be?"

Re: Defensive Programming and a Whole Lot More

2009-05-15 10:11 • by pete (unregistered)
262716 in reply to 262712
Rootbeer:
IE6 still accounts for 15% of the traffic to the site I operate at my day job. Do you think management would be happy if sales were to drop by 15%?

They seem to be happy -- obsessed even -- with eliminating the sales from Firefox users, Mac users, etc...

Re: Defensive Programming and a Whole Lot More

2009-05-15 10:22 • by Tim Smith (unregistered)
I wouldn't depend on the (!this) stuff since the standard specifically states that the behavior is undefined. You can invoke a static function from a null pointer, but that is it.

Re: Defensive Programming and a Whole Lot More

2009-05-15 10:28 • by Anonymous (unregistered)
262719 in reply to 262706
Leo:
The Real WTF is caring whether code works in IE6 or not. Bet it doesn't work in Lynx, SlipKnot, or Netscape 3 either.
Simply compare the market share of IE6, Lynx, SlipKnot and Netscape 3 - then you will see exactly why people still care about IE6.

I would say "bad troll" but we all bit, so maybe it wasn't such a bad troll after all.

Re: Defensive Programming and a Whole Lot More

2009-05-15 10:55 • by Charles400
"I was going over some code from a SDK released by you know who," Tammie Kong wrote. "There were a few questionable things in it, but then I found a single line that made me pause. I realize string.format() has its advantages and all, but this just seemed ridiculous."

No, I don't know who. Who?

Re: Defensive Programming and a Whole Lot More

2009-05-15 10:56 • by Pedant (unregistered)
The real WTF is that someone thinks that "!this" is a WTF in C++. Please do us a favor and stay far away from C++ until you learn what you are doing.

Bjarne Stroustrup uses "if (this==0)" twice on page 605 of "Programming: Principles and Practice using C++". It isn't needed in every method, but it isn't automatically a WTF.

Re: Defensive Programming and a Whole Lot More

2009-05-15 10:59 • by Steve (unregistered)
262726 in reply to 262696
[quote user="Jamie"]
[quote user="Blob"]
[quote user="Jerry"]
Josh's predecessor seemed to miss out on the fundamentals the request/response paradigm.[/quote]
... while Josh, in turn, missed out on the fundamentals the English grammar.[/quote]
"of" has been depreciated
[/quote]
FTFY
[/quote]
No, you didn't.

Re: Defensive Programming and a Whole Lot More

2009-05-15 11:00 • by Steve (unregistered)
262728 in reply to 262696
Jamie:
Blob:
Jerry:
Josh's predecessor seemed to miss out on the fundamentals the request/response paradigm.

... while Josh, in turn, missed out on the fundamentals the English grammar.

"of" has been depreciated

FTFY

No, you didn't.

Re: Defensive Programming and a Whole Lot More

2009-05-15 11:10 • by awfwefewa (unregistered)
ALTER FUNCTION [CMM].[FetchItemCode]
(
)
RETURNS bigint
AS
BEGIN
RETURN 29654
END
TDD mocking?

Re: Defensive Programming and a Whole Lot More

2009-05-15 11:22 • by CAT (unregistered)
262734 in reply to 262706
Leo:
The Real WTF is caring whether code works in IE6 or not. Bet it doesn't work in Lynx, SlipKnot, or Netscape 3 either.


The Real WTF are sites which rely on JS (or Flash, Java, ...) for basic functionality.

Re: Defensive Programming and a Whole Lot More

2009-05-15 11:27 • by anon (unregistered)
262736 in reply to 262700
AC:
It's like running across those branches that begin with a comment saying "this should never happen"

As long as this case is properly handled, there's nothing wrong with it. Think of external input that will be between -10 and 10. If it leaves those bounds (power surge, earthquake, sensor failure etc.) than there is no correct response from the program, which may therefore (gracefully) shut down.

Now, if you didn't have that branch, the program would still happily continue with wrong values.

Re: Defensive Programming and a Whole Lot More

2009-05-15 11:41 • by Jamie (unregistered)
262739 in reply to 262728
Steve:
Jamie:
Blob:
Jerry:
Josh's predecessor seemed to miss out on the fundamentals the request/response paradigm.

... while Josh, in turn, missed out on the fundamentals the English grammar.

"of" has been depreciated

FTFY

No, you didn't.


Sorry... I guess you had to be here yesterday....
I was just running the script provided by "Language Nazi"

Re: Defensive Programming and a Whole Lot More

2009-05-15 12:12 • by SCJP (unregistered)
Boolean answer = new Boolean(
inp.equals("true")
? new Boolean(true)
: new Boolean(false)).booleanValue();
For those not familiar with Java:
Boolean answer = new Boolean(inp);
...simply does the trick.

I don't see Andy Goth's problem

2009-05-15 12:19 • by DaveK

the actual code and it was a even more surprising than I had remembered."

#define NEGATIVE_ONE 0

What's surprising about that? When it comes to boolean values, zero is the negative one. And '1' is the positive one. See?

Re: Defensive Programming and a Whole Lot More

2009-05-15 12:20 • by Code Dependent
262746 in reply to 262743
SCJP:
Boolean answer = new Boolean(
inp.equals("true")
? new Boolean(true)
: new Boolean(false)).booleanValue();
For those not familiar with Java:
Boolean answer = new Boolean(inp);
...simply does the trick.
return new Boolean(
"Boolean answer = new Boolean(inp);" ...simply does the trick
? new Boolean(true)
: new Boolean(false)).booleanValue();

Re: Defensive Programming and a Whole Lot More

2009-05-15 12:33 • by lolwtf
262749 in reply to 262690
Code Dependent:
Blob:
Jerry:
Josh's predecessor seemed to miss out on the fundamentals the request/response paradigm.
... while Josh, in turn, missed out on the fundamentals the English grammar.
"of" has been deprecated
Yes, "the" is now used in its place.
What a load the nonsense. I'd rant about it, but I have to log thef.

Re: Defensive Programming and a Whole Lot More

2009-05-15 12:37 • by shadowman
I don't get the String.format() one.

Re: Defensive Programming and a Whole Lot More

2009-05-15 12:41 • by Tom (unregistered)
Someone explain to me the javascript one. Is the WTF that the comment and the if (!confirmed) don't match? I'm going crazy trying to see what is wrong with this (maybe just because it is Friday...)

Re: Defensive Programming and a Whole Lot More

2009-05-15 12:45 • by Tom (unregistered)
262754 in reply to 262752
Tom:
Someone explain to me the javascript one. Is the WTF that the comment and the if (!confirmed) don't match? I'm going crazy trying to see what is wrong with this (maybe just because it is Friday...)


I mean, other than the fact that there is a lot of unnecessary code (assuming that the comment is incorrect, but the code is right...)

Sorry for the double-post, can't edit since I am not registered...

Re: Defensive Programming and a Whole Lot More

2009-05-15 12:45 • by SCJP (unregistered)
262755 in reply to 262750
shadowman:
I don't get the String.format() one.
Splitting the SQL string into four parts first and let String.Format() put it together afterwards is somehow senseless.

Re: Defensive Programming and a Whole Lot More

2009-05-15 12:49 • by wrtlprnft (unregistered)
if(!this) {
throw new NullPointerException();
}

Re: Defensive Programming and a Whole Lot More

2009-05-15 12:50 • by Code Dependent
262759 in reply to 262754
Tom:
Tom:
Someone explain to me the javascript one. Is the WTF that the comment and the if (!confirmed) don't match? I'm going crazy trying to see what is wrong with this (maybe just because it is Friday...)


I mean, other than the fact that there is a lot of unnecessary code (assuming that the comment is incorrect, but the code is right...)

Sorry for the double-post, can't edit since I am not registered...
The entire method is superfluous. See my comment on that above.

Re: Defensive Programming and a Whole Lot More

2009-05-15 12:51 • by shadowman
262760 in reply to 262752
Tom:
Someone explain to me the javascript one. Is the WTF that the comment and the if (!confirmed) don't match? I'm going crazy trying to see what is wrong with this (maybe just because it is Friday...)


The whole function is an unnecessary wrapper around

var confirmation = confirm(message);

It doesn't add anything beyond that one line.

Re: Defensive Programming and a Whole Lot More

2009-05-15 12:52 • by Code Dependent
262761 in reply to 262755
SCJP:
shadowman:
I don't get the String.format() one.
Splitting the SQL string into four parts first and let String.Format() put it together afterwards is somehow senseless.
No kidding. Somebody ought to put it up on a website somewhere that features stuff like that.

Re: Defensive Programming and a Whole Lot More

2009-05-15 12:52 • by Rich (unregistered)
262762 in reply to 262699

We did something similar to this back in our Windows 3.1 programming days. But it was

assert(this);

at the top of every method. We were using the Borland compiler.

The problem was that you could call non virtual methods without a valid "this" pointer (because those methods weren't put into the virtual table) and we would end up with segfaults or other assertions farther down in the code.

Not all class methods touched the "this" pointer, but we wanted to assert() the failure sooner rather than later.

Moving the assert(this) higher up in the stack showed the developer immediately that he was dealing with a null pointer. Not that he shouldn't have been asserting his pointer earlier.. but in win16 programming we believed in belts AND suspenders!

And yes, it doesn't work for virtual functions in subclasses. But virtual functions weren't what we were trying to protect! Ideally you should segfault when the compiler indexes into the bad virtual table pointer. (And then often bring down your Windows 3.1 with it!)

Re: Defensive Programming and a Whole Lot More

2009-05-15 12:57 • by Jay (unregistered)
262763 in reply to 262736
anon:
AC:
It's like running across those branches that begin with a comment saying "this should never happen"

As long as this case is properly handled, there's nothing wrong with it. Think of external input that will be between -10 and 10. If it leaves those bounds (power surge, earthquake, sensor failure etc.) than there is no correct response from the program, which may therefore (gracefully) shut down.

Now, if you didn't have that branch, the program would still happily continue with wrong values.


It's like, Why do we waste money hiring police? After all, people SHOULD never break the law.

Re: Defensive Programming and a Whole Lot More

2009-05-15 12:59 • by Steven Noonan (unregistered)
The whole
if (!this) dieHorribly();
thing actually does make sense. Something like
assert(this);
would make more sense, but the rationale for it is fairly simple. Let's say you have some badly written code like this:
SomeClass *instance = NULL;

instance = getSomeInstance(someParameter);
instance->badFunctionCall();
The return value of 'getSomeInstance' isn't checked, so it could return NULL. Instead of segfaulting on the badFunctionCall() it will just hit an assertion failure in the case that you have an assertion on the 'this' pointer, because 'this' would be NULL. It's even' better if you have a custom assertion function that prints debugging info, because you can easily figure out where you made a mistake in your program.
« PrevPage 1 | Page 2 | Page 3Next »

Add Comment