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

I see this at a micro level frequently when coding. Very often code that is a complex bunch of if / else statements is dramatically simplified by turning it into a map / dictionary with pointers to either data or functions to handle that type of data (object oriented polymorphism being an instance of this).

There are also interesting parallels with REST vs RPC as well. You can create a rich API of function calls for accessing and manipulating data, but it's nearly always less flexible than just exposing the data and letting people manipulate it directly.

I think the tendency to favor algorithms when it might otherwise not be wise to do so comes from how our minds work: we remember things primarily in terms of stories, scenarios, sequences of events. This causes us to interpret the world in terms of behavior as if behavior is the primary construct on which the universe is modeled. But of course behavior is not primary, data is primary, things are primary - behavior is just a fiction we impose on them. This often leads our instincts in the wrong direction.




Hmmm replacing if/else statements with a map/dictionary with pointers to either data or functions. A little off topic here but how do you propose to do this? Assuming we know what polymorphism is. Your map/dictionary style is quite interesting.


For languages with first-class functions, it looks like this:

    # Algorithms
    def double(x): return x*2
    def square(x): return x*x
    def fact(x): return (x*fact(x-1) if x > 1 else 1)

    # Data
    choices = { 'A': double, 'B': square, 'C': fact }

    # I/O
    choice = raw_input('Choose A, B or C: ')
    x = input('Enter a number: ')
    if choice in choices:
        print choices[choice](x)
    else:
        print 'Initiating self-destruct sequence.'
It's actually similar to how a switch block works, if each case in the switch statement just calls a function or evaluates one expression.

Also worthwhile: Instead of functions, let the dictionary values be lists of arguments for another (multi-argument) function. Then the lookup is like choosing from a set of possible configurations for that function. A little redundancy is OK, since the table is so easy to read and edit.


Parse tables or regex compiling are a perfect example of this style. Lookup tables are another good example.




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

Search: