Hacker News new | ask | show | jobs
by stcredzero 5172 days ago
Blocks in other languages can help maintain encapsulation, if they can access variables from their local scope. They can also enable programmers to write their own control structures which look like natural first class control structures in the host language. I don't see this as a natural way of doing either.
1 comments

Nested functions can access variables from local scope in Python, so this isn't a huge issue. It's a bit wonky in python (see discussion of the nonlocal keyword, Python did this wrong from the start) but it solves your encapsulation problem.

    def sorted_by(xs, attr):
        def cmp_attr(a, b):
            return cmp(getattr(a, attr), getattr(b, attr))
        return sorted(xs, cmp_attr)
It takes a little more vertical space and requires you to give a name to something that might otherwise be anonymous, but in the long term it's actually beneficial in my opinion. I've actually taken to using the same pattern in my JavaScript development, giving all of my callbacks names, because it makes maintenance so much easier later.

    var load_into = function (url, elem) {
        var handle_response = function (response) {
            $(elem).html(response);
        };

        $.get(url, handle_response);
    };
That's not bad. I agree named functions are fine for many solutions for maintaining encapsulation. They're not that great for writing your own control structures. How would you implement my ifTrue:ifFalse:ifMaybe: example?