Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

It seems strange (to me)--maybe in a good way, but would it be preferable to use the JSON literal over the if statement (for the sake of the argument assume in javascript if returns a value)?

val = if (person === "Homer") { return expr } else if (person === "Bart") { return expr } ...

----

val = { "Homer": expr ,

"Bart": expr , ... }[person];

Would the literal be simpler because it uses data over syntax, or rules instead of conditionals?



I frequently use the latter in Python. I like that it's easy to construct programatically (because it's data) and it more explicitly handles the various cases (especially the default case).


Agree, I do it a lot as a way of selecting functions in a switch statement:

    handlers = {
        'dave'  : call_dave(),
        'ted'   : call_ted(),
        'julie' : contact('julie') }

    handlers['dave']()   # Call dave
    handlers['julie']()  # Contact julie

    [handlers[person]() for person in ['dave', 'julie', 'ted']] # Contact all three




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: