简体   繁体   中英

How do I write a clean conditional statement

This may be a dumb question but what is an easy way to write a clean condition statement, for example lets say if I have a conditional statement where I only want it to happen before a block of code if it meets the requirement and if it doesn't then I want it to happen after the block of code. But it must happen in that order

EDIT

This code is NOT broken.. I was simply asking if there was a better way of structuring this conditional statement and I found out that putting the //random code in a helper method and combining the two if's into an else if would solve it. See my answer below.

if(number === 250){
    // sameMethod()
}

//random code

if(number !== 250){
    // sameMethod()
}

Solution

function helper() {
    //random code
}

if(number !== 250){
    helper()
    // same code
} else {
    // same code
    helper()
}
if(number == 250){
    // sameMethod()
}

//random code

if(number != 250){
    // sameMethod()
}

For this, and based on the information at hand, I would recommend keeping the code as is. The way you have written this code, an if-else block would have a serious impact on the flow of your application.

Assume that randomCode is a method call, which performs the next operation:

function randomCode() {
  this.number += 5;
}

and you start the code with the state of your application having the value of number as 245.

if ( number == 250 ) { // conditions 245 == 250 evaluates to false
  // sameMethod -> will not be executed
}

randomCode(); // increases the value of number with 5

if ( number != 250 ) { // condition 250 != 250 evaluates to false
  // sameMethod -> will not be executed
}

Just slapping an if-else, like this:

if ( number == 250 ) { // condition 245 == 250 evaluates to false
  // sameMethod
} else {
  randomCode();
  // sameMethod -> here it will be executed, even though number now is 250. Change in behaviour
}

So, there are two things to consider: either the example code you posted was the correct flow, making it correct (but might end up in executing sameMethod twice, or not at all, since the value of number could be altered in the randomCode part, or both sameMethod and randomCode have to be executed (exactly) once, depending on that condition.

If so, the original (pseudo?) code was faultive, but the result would indeed come to:

if ( number == 250 ) {
  sameMethod();
  randomCode();
} else {
  randomCode();
  sameMethod();
}

This is where monads and all that jazz show their ugly mugs.

Assuming you are talking about java, you could for example write a runSequentially method that results in letting you write:

   runSequentially(() -> sameMethod(), () -> {
        // random code
   }, number != 250);

Where runSequentially will first run the first Runnable, then the second Runnable - unless the condition is false, in which case it runs the second, then the first.

In java, this is not, however, local mutable variable, checked exception, and control flow transparent which are sufficient downsides that I'm not sure this is a good idea. Especially considering that apparently execution order matters which usually suggests mutating state. But, if you insist, it'd be something like:

public static void runSequentially(Runnable a, Runnable b, boolean flipOrder) {
    if (flipOrder) { b.run(); a.run(); }
    else { a.run(); b.run(); }
}

Javascript is a lot more laissez-faire (and a totally different language; did you tag it because perhaps you were unaware that 'java' and 'javascript' are completely unrelated? It's a common mistake - in that case, disregard this bit), and doesn't suffer from the transparency issues as much. Javascript has no checked exceptions, javascript lets you mutate outer state (there are some WTFs in javascript-the-language about this, but that's a separate issue). The biggest issue is control flow (you can't as easily break/continue loops in the 'outer' code from within these closures).

Going back to java for a moment, using lambdas (closures) in contexts where:

  • The lambda is run 'in-line', that is, you pass the lambda to some method, and once that method returns, the lambda is 'forgotten about' by said method: That method did not store the lambda in a field, did not pass it to another thread, did not pass it to other code that is going to store it in a field or pass it to another thread).
  • The code in the lambda is not designed 'functional style' (eg it mutates state or does a bunch of I/O), then

you're probably messing up. Lambdas really suck in that environment, those transparency issues are grating then. Note that if the lambda does 'travel' (is stored / moved to another thread), that lack of transparency is in fact a great thing because those 3 'transparencies' become bizarre braintwisters - best to just not allow them.

That's why I recommend against this, if you're writing java. But now you know how one would.

Thanks for all the advice, I should've been more clear about the language since I thought this was a fairly simple solution that might work in both Java and Javascript. I ended up just putting the "random code" in a helper function.

function helper() {
    //random code
}

if(number !== 250){
    helper()
    // same code
} else {
    // same code
    helper()
}

Basically the idea was that, the order of which block of code that gets executed mattered depending on a fixed variable. It was messy without a helper function due to duplicated code so this simple solution fixed it. Let me know if you guys think of a more clever way! Thanks

Maybe you can use the else if statements

if(condition1){
    //method();
} else if(condition2){
    //method();
} else //whathever you want here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM