Search code examples
if-statementlanguage-agnosticcode-organization

Is there a neat way to organize uni-conditional code that exists at different sections of a program?


For example, I'd like to have something like this:

If(condition) object.start();

// Do some unrelated processing

If(condition) object.stop();

As a simple example of what I would like to happen. Are there any language agnostic ways to organize this, especially as you have more conditional lines of code?


Solution

  • I suppose you're asking this because the condition is expensive or non-repeatable.

    One typical solution would be to set a boolean variable in the first IF, and let the second IF check that boolean variable instead of re-executing the condition.

    boolVar=false
    if (condition) {
      boolVar=true
      object.start()
    }
    // do unrelated stuff
    if (boolVar) {
      object.stop()
    }
    

    Another typical solution would be something like this :

    if (condition) {
      object.start()
      doSomething()
      object.end()
    } else {
      doSomething()
    }
    

    Don't be afraid of simple solutions, if they're good enough. :)