Suppose you have a method submit 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))
{
.....
}
}
.....

No comments:
Post a Comment