开发者

How should I format this piece of code?

Here are two ways of calling callscript (in pseudocode):

using duplicate calls

if flag == true
    flag = false
    callscript
    flag = true
else
    callscript
endif

using an extra variable

flag2 = flag
flag = false
callscript
flag = flag2

conditions

  • I have to make sure is that flag is false when the script is c开发者_Go百科alled.
  • Also, the flag value has to be restored to the original value.

Is there a better way to do this than these two? If not, which one of these is a better choice?


The best would be to send the flag along in the call, so that the relation between the flag and the method is clear:

callscript(false)

If that's not an option, and you have to choose between the two, then either one would do. There is no clear winner, readability is about the same for both, so it's just a matter of taste.

The second option would be the better one if the actual call is complicated so that you don't want to repeat it in the code, or if the data type is something more complicated than a boolean.


I would go with variant two with a change to the name of variables to make it a bit more easy to understand.

saved_flag = flag
flag = false
callscript
flag = saved_flag


I like the second one much better, because if you name flag2 in a sensible way (like

backupValueOfFlag = flag
flag = false
callscript
flag = backupValueOfFlag

) it is much clearer what you are doing and why you are doing it.


I think this is why local variables and subroutine parameters have been invented.

Do you really have to work with globals?


I will choose the second one. The first one is too artifical for me - the if there is not for program flow but to preserve the flag value.


As for me, better choice is first one. Because it is more readable and more clear what is going on there.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜