51

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:)

Saurabh Gokhale
  • 53,625
  • 36
  • 139
  • 164
AlexMorley-Finch
  • 6,785
  • 15
  • 68
  • 103
  • 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. – Peter Smith May 20 '11 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). – Daniel Earwicker May 20 '11 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. – D'Arcy Rittich May 20 '11 at 14:48
  • 1
    @RedFilter - did you see the way that `direction =` is repeated three times in the original code? – Daniel Earwicker May 20 '11 at 14:50
  • 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. – D'Arcy Rittich May 20 '11 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. – Daniel Earwicker May 21 '11 at 13:44

4 Answers4

53

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
{
}
Mike Dour
  • 3,616
  • 2
  • 22
  • 24
44

Use the ternary operator

direction == 1 ? dosomething () : dosomethingelse ();
Hyperboreus
  • 822
  • 5
  • 4
  • 2
    return type of `dosomething()` & `dosomethingelse()` both must be same. – Javed Akram May 20 '11 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 () ); } – Hyperboreus May 20 '11 at 15:16
  • 5
    [your example](http://www.ideone.com/IAmFW) makes the compiler really angry. This wasn't a C question! – R. Martinho Fernandes May 20 '11 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. – Hyperboreus May 20 '11 at 15:23
32

Yes. Use the ternary operator.

condition ? true_expression : false_expression;
maracuja-juice
  • 994
  • 2
  • 14
  • 33
Saurabh Gokhale
  • 53,625
  • 36
  • 139
  • 164
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;
}
Piotr Kwiatek
  • 687
  • 8
  • 10
  • 5
    switch looks more clear and more dev friendly. And compiler just doesn't give a f#$# :) – Tommix Jan 28 '16 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 :) – Jaimie Knox Jun 28 '18 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. – jaysonragasa Nov 27 '20 at 23:11
  • 1
    I prefer the 2nd. It is more maintainable (easy debug) and expandable. – mjb Jan 13 '21 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 May 09 '21 at 03:03
  • This could be better solved by having a command pattern, and maybe build a set of response holding objects, that will initialized based on your if else /switch statement, so you ensure you only have 1 switch statement across the entire system. You can't avoid them entirely, but you should always wrap if/else trees or switch case statements in a "component" that is reused via an interface, like in the strategy pattern, so that you NEVER have the same switch state twice. But ideally solving it with polymorphism is better. – Morten Bork Jan 14 '22 at 13:57
  • The problem is your logic eventually runs away and causes your WTF pr minutes to rise when you read the code. This doesn't baby step it, but it hints at what you are doing, without using a switch case. https://stackoverflow.com/questions/13609579/polymorphism-in-web-api-single-endpoint-possible – Morten Bork Jan 14 '22 at 14:04