Table-driven approach

All

During my reading I came to the Table-driven approach is very interesting and sometimes can be useful instead of using a complicated logic approach [1]. The site [2] is very useful too.

This approach uses the table as forms to represent relationships, I think the book gives a more complex example the but example in the site is very interesting and smaller.

Python approach

For python we can actually use a dictionary the same way, as table converting specific values, as key-value operation. In python you can also use functions within data structures and this makes it very powerful.

Function in Dictionary in Python

I remember we were dealing with 4 kinds of results in an array and for each kind of result one different funtion would be called. So my first approach was to use the typeof() way, i.e. open the array and for each element see the type and call the different one. But actually, as one collegue taught me, we can store the function within a dictionary and do so much magic with a clean code passing a function as argument.

   Key into callable

Well, I cant put my company code here, but I will steal from here [3], with some changes thanks Martijn Pieters.

def bark(self, name):
    return 'Bark!'.format(name)

def meow(self, name):
    return 'Meow'.(name)

dispatch = {
    'cat': meow,
    'doc': bark,
}

def animal_sound(animal, arg):
    send(dispatch[animal](arg))

 

The example above is very simple and lack of meaning, since one could basically create one function and send the sound as parameter, but I think you will understand my point. You can put a callable in a dictionary! hahaha!!

 I hope I helped!

[1]: Code Complete, by Steve McConell

[2]: https://www.techopedia.com/definition/30408/table-driven-design

[3]https://softwareengineering.stackexchange.com/questions/182093/why-store-a-function-inside-a-python-dictionary

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s