Tuesday, May 3, 2016

Inlined if-else assignment

This if-else statement:
AssignmentEnum assignment;
if (loggedUser == onboard.Employee)
    assignment = AssignmentEnum.Employee;
else if (loggedUser == onboard.CreatedBy)
    assignment = AssignmentEnum.Manager;
else
    assignment = 0;

Can be shortened to:
AssignmentEnum assignment = 
    loggedUser == onboard.Employee ?
        AssignmentEnum.Employee
    :loggedUser == onboard.CreatedBy ?
        AssignmentEnum.Manager 
    :
        0;


Here's how to allow the above code structure in ES6:


 
https://stackoverflow.com/questions/32289340/alternative-to-nested-ternary-operator-in-js/72654443#72654443
Happy Coding!

3 comments:

  1. I feel that this reduces readability though. If there was only a if/else, i would approve of this shortening.

    ReplyDelete
    Replies
    1. Sometimes you'll have no choice, you would mentally think if-else, however you can only use if-else in imperative code. The sort of code style above could also be used to simulate if-else in declarative code like Linq.

      Delete
  2. I would format it this way:

    AssignmentEnum assignment =
    (loggedUser == onboard.Employee)
    ?
    AssignmentEnum.Employee
    :
    (loggedUser == onboard.CreatedBy)
    ?
    AssignmentEnum.Manager
    :
    0;

    ReplyDelete