53

Just a quick one, Is there anyway to shorthand this?

It's basically determining the direction left or right, 1 for left, 0 for right

In C#:

if (column == 0) { direction = 0; }
else if (column == _gridSize - 1) { direction = 1; }
else { direction = rand.Next(2); }

The statement following this will be:

if (direction == 1)
{
    // do something
}
else
{
    // do something else
}

If there isn't, it doesn't really matter! just curious:)

6
  • 12
    Why would you want to shorten this? It's very readable in its current format which is a key thing to strive for when writing code. Commented May 20, 2011 at 14:46
  • 3
    @Peter Smith - actually it's not immediately obvious that every branch of the if/else is assigning a different value to the same variable. The part direction = is repeated three times. By bringing that out, it makes it objectively clear (not just a matter of opinion, but a fact based on the reduction of needless repetition). Commented May 20, 2011 at 14:48
  • 2
    I agree with @Peter, all the solutions so far are far less readable than what you have. I see no reason to change. Commented May 20, 2011 at 14:48
  • 2
    @Daniel I have no problem with the repetition of direction, because nested ternaries are much harder to parse when reading. I would also say that the repetition of direction makes it more obvious that it is the same variable getting different values in each branch. Commented May 20, 2011 at 14:59
  • 2
    You have that totally backwards. If it has to be literally repeated, then there is an unnecessary degree of freedom: any of the branches may be different to the others. You have to inspect them to make sure they're the same - it makes the pattern less obvious. Whereas if the statement starts with direction =, that makes it immediately obvious from the start that we are assigning something to direction, and hence the rest of the statement must be an expression producing the value to be assigned. The only problem would be if the person reading the code is not aware of how ? : works. Commented May 21, 2011 at 13:44

4 Answers 4

55

To use shorthand to get the direction:

int direction = column == 0
                ? 0
                : (column == _gridSize - 1 ? 1 : rand.Next(2));

To simplify the code entirely:

if (column == gridSize - 1 || rand.Next(2) == 1)
{
}
else
{
}
44

Use the ternary operator

direction == 1 ? dosomething () : dosomethingelse ();
4
  • 2
    return type of dosomething() & dosomethingelse() both must be same. Commented May 20, 2011 at 14:47
  • @Javed Akram No they do not. Copypasta this and compile it, it runs without problems: #include "stdio.h" char* getString () { return "String"; } int getInt () { return 5; } void main () { printf ("%s %d", 1 ? getString () : getInt (), 0 ? getString () : getInt () ); } Commented May 20, 2011 at 15:16
  • 5
    your example makes the compiler really angry. This wasn't a C question! Commented May 20, 2011 at 15:20
  • 6
    Ashes on my Head! My bad! My bad! I didn't see the tiny hash after the C. And angry compilers are not to be trifled with. Commented May 20, 2011 at 15:23
32

Yes. Use the ternary operator.

condition ? true_expression : false_expression;
1
  • 2
    You could write better-> condition ? true_expression: false_expression;
    – Tommix
    Commented Jan 28, 2016 at 12:24
5

Recently, I really enjoy shorthand if else statements as a swtich case replacement. In my opinion, this is better in read and take less place. Just take a look:

var redirectUrl =
      status == LoginStatusEnum.Success ? "/SecretPage"
    : status == LoginStatusEnum.Failure ? "/LoginFailed"
    : status == LoginStatusEnum.Sms ? "/2-StepSms"
    : status == LoginStatusEnum.EmailNotConfirmed ? "/EmailNotConfirmed"
    : "/404-Error";

instead of

string redirectUrl;
switch (status)
{
    case LoginStatusEnum.Success:
        redirectUrl = "/SecretPage";
        break;
    case LoginStatusEnum.Failure:
        redirectUrl = "/LoginFailed";
        break;
    case LoginStatusEnum.Sms:
        redirectUrl = "/2-StepSms";
        break;
    case LoginStatusEnum.EmailNotConfirmed:
        redirectUrl = "/EmailNotConfirmed";
        break;
    default:
        redirectUrl = "/404-Error";
        break;
}
7
  • 5
    switch looks more clear and more dev friendly. And compiler just doesn't give a f#$# :)
    – Tommix
    Commented Jan 28, 2016 at 12:25
  • 1
    Maybe if you haven't seen ternaries before. Spend a little time with them and the ternaries become way more readable, and with less eye-strain too. I like to line up the ?s because I'm fancy :) Commented Jun 28, 2018 at 20:17
  • 1
    The first one is like you have to find the end of the single spaghetti's pasta in a 1 ton spaghetti plate. Second one is much simpler. Commented Nov 27, 2020 at 23:11
  • 1
    I prefer the 2nd. It is more maintainable (easy debug) and expandable.
    – mjb
    Commented Jan 13, 2021 at 16:38
  • 1st one. Looks good visually. You'll know this goes with this. But when you try to trace something, well A lot would prefer the second. Extract it to a method.
    – Yorro
    Commented May 9, 2021 at 3:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.