Hacker News new | ask | show | jobs
by xyrouter 3018 days ago
Like another commenter on this thread, I too find the second example the most readable and I write code like the second example even though I have many years of experience with Python.

The third example is cool but I don't see the immediate value in writing code that way unless I am designing a framework of some kind.

I am of the opinion that code should be written in as simple manner as possible so that programmers from different background can get up-to-speed with the code with little trouble.

2 comments

An OO language that has the ability to do dispatching on types ought to be exercised in that way.

Checking for the types explicitly in your code creates a brittle system. For a one-off bit of code, fine. For anything that may be extended in the future, it's a bad idea and will have to be refactored to become maintainable.

IMO, having functions that accept different types (when the types are unrelated) is an anti-pattern in most cases, it doesn't matter if you make it more "maintainable" by using single dispatch.

It's fine when you have related types, but in the example `someFunction` accepts both ThisClass and str, which (I assume) have very different functionality.

You see this anti-pattern a lot in dynamically-typed languages. As an example, both these examples are valid and do the same thing in `knex`, an SQL query builder for node:

    knex.select('name', 'email').from('users')
    knex.select(['name', 'email']).from('users')
Second is example is most readable, I agree. What I was trying to convey there was first the use of "type" vs "isinstance", and second the use of non pep8 snake case in Python which is frowned upon. Then I wanted to show there is another way of handling (larger) blocks of "if this type/instance then this, if that then that, etc.". I use it as a getter when I have either an id or an instance and it feels smoother to me. Python's version of overridden methods. Both are fine of course.