开发者

Condition check inside a function or before its call?

Which of these 2 program开发者_如何转开发ming styles do you prefer? Why? Are there particular advantages to one over the other?

// Style 1
if (doBorder)
    doTheBorder();
if (doFrame)
    doTheFrame();
if (doDraw)
    doTheDraw();

void doTheBorder()
{
  // ...
}

void doTheFrame()
{
  // ...
}

void doTheDraw()
{
  // ...
}

// Style 2
doTheBorder();
doTheFrame();
doTheDraw();

void doTheBorder()
{
  if (!doBorder)
    return;
  // ...
}

void doTheFrame()
{
  if (!doFrame)
    return;
  // ...
}

void doTheDraw()
{
  if (!doDraw)
    return;
  // ...
}


The first. The second seems to be... lacking in confidence. Why call doTheBorder() if you don't even know if you want the border to be done? IMO, you should assert that the border really needs doing, and then call doTheBorder() with confidence!

...Also, from a more technical point of view: if doTheBorder() is in a closed API, a developer in the distant future might call it and if the second style is employed, they may wonder why the border didn't get done, despite their call to doTheBorder(). Of course, sometimes certain circumstances or restrictions or limitations may dictate that the second style be used, but I'd avoid it when possible.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜