Search code examples
language-agnosticprogram-flow

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 called.
  • 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?


Solution

  • 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.