Hacker News new | past | comments | ask | show | jobs | submit login

Getting rid of if/else is nothing but moving the if/else to somewhere else.



This is only true in a very technical sense.

    function getColor(str){
       if(str=='blue'){ return '#0000ff'; }
       if(str=='red') { return '#ff0000'; }
    }
    
    getColor = {
      blue: '#0000ff',
      red: '#ffoooo'
    }

The second one also has if statements inside the implementation of the hash map, but it isn't actually polluting your business logic. The question is no longer "what do you do when the input is like this or like that", but "lookup the corresponding output".

The distinction is nice because I know that getColor[thing] will likely have no side effects. I can treat it, on a theoretical level, strictly as a map.

Of course if the problem is "implement this on a machine without branching" this isn't super useful but most problems are not that.


I agree. For example when you are using some form of polymorphism, the compiler/runtime are handling your if/else for you. But, still in terms of understanding what a piece of code is doing you will have to consider all the possible branches whether they are explicit in code as if/else statements or hidden under some abstraction like map/dictionary.

Edit: The conditional abstractions like map are useful in the sense that the conditions that they support are very simple, in case of map it is if supplied key equals that key, whereas if/else statements can be used to create any kind of complex conditions.




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

Search: