A Journey 2 Eternity

A good technique to prevent unnecessary NULL Checking in virtual methods of an inherited class

Posted on: December 1, 2008

Suppose you have a method in a class called BOOL CommandProcessor::Submit (CCommand* pCommand), which calls a method virtual BOOL CommandProcessor::DoCommand (CEMCCommand* cmd). The code in the Submit Method goes like this:

BOOL CCmdProcessor::Submit(CCommand* pCommand)
{
	if (pCommand != NULL) {
		if(DoCommand(pCommand)) {
			…..
		}
	}

	…..
}

Now somebody when overriding the DoCommand method in his inherited class might write a code such as this

virtual CInheritedCmdProcessor::DoCommand(CCommand* pCommand)
{
	if(pCommand != NULL) { // -> line X
		pCommand->Execute();
	}
}

As you can see, the NULL checking in line X is totally unnecessary since we are already checking for NULL in the parent class’s CCmdProcessor::Submit method.

But the developer cannot be blamed, since he is receiving a pointer, his first intention would be Safety Checking. Therefore, you can just modify your architecture a little to make sure, unnecessary checking is reduced. Just simply pass a reference instead of a pointer in the DoCommand. Therefore, the developer who is inheriting your class is certain that a valid object is coming and no need to check for NULL memory. Therefore your DoCommand method should be as follows:

virtual CCmdProcessor::DoCommand(CCommand& cmd) and the code in the Submit method should be like this:

BOOL CCmdProcessor::Submit(CCommand* pCommand)
{
	if(pCommand != NULL) {
		if(DoCommand(*pCommand)) {
			…..
		}
	}
	
	…..
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Pages

Categories

December 2008
M T W T F S S
« Sep   Apr »
1234567
891011121314
15161718192021
22232425262728
293031  

Blog Stats

  • 27,176 hits
%d bloggers like this: