News for hackers. Stuff that matters.
Re:Stop writing classes... by scott_s on Saturday March 17, 2012 @07:59PM (#3718616)
I still think classes have value. For example, Python's standard library provides csv.writer and csv.reader objects for reading and writing csv files. Making them objects, rather than just functions, allows one to use them like so (assuming the csv file contains "value,average,stddevs" on each line):

   vals = []
   avgs = []
   stds = []
   file = csv.reader(open('data.csv', 'r'))
   for row in file:
      vals.append(row[0])
      avgs.append(row[1])
      stds.append(row[2])
Providing this abstraction without using objects would be difficult, I think. The key differentiator is, I think: is what you want to represent with a class a concrete thing with a clear interface? If those two things don't hold, then it may be better not to represent the concept with a class.

Again, I have to break this reasoning all the time in C++. I try to use free functions as much as possible, but when I want behavior based on runtime values, I often have to represent abstract concepts using classes because those are the tools that C++ gives me.

Re:Stop writing classes... by pjscott on Saturday March 17, 2012 @08:51PM (#3718721)
In Python, you can get that exact same behavior by writing a generator function. I'm sure this code has shortcomings -- it doesn't handle comment lines, for example -- but something like this will parse basic CSV:

    def readcsv(file):
        for line in file:
            if line:
                yield tuple(field.strip() for field in line.split(','))
No explicit class definitions necessary! And you can write the same kind of code. Or, if you want to be a bit too clever for your own good, you can shorten it to this:

    rows = readcsv(open('data.csv', 'r'))
    vals, avgs, stds = zip(*[map(int, row) for row in rows])
At no point here have I used the "class" keyword!
Re:Stop writing classes... by scott_s on Sunday March 18, 2012 @11:29AM (#3719876)
You and jules provided excellent examples for how to do my example without classes - but you do assume that the csv parser never needs to peek across lines. That's probably fine for csv files, but in general, lexers/parsers may need to. My point is, you're taking advantage of the fact that files are already objects which can be processed line by line. You can't always do this. I think that things like files and sockets are very nice to have as objects.
Re:Stop writing classes... by tomp on Sunday March 18, 2012 @12:19PM (#3719998)
I a way, you could think of the generator function as an object with a specific interface.

In fact, I think that's how generators are implemented in python, the language just hides this fact away from the programmer.

Re:Stop writing classes... by pjscott on Sunday March 18, 2012 @03:44PM (#3720676)
Everything in Python is an object under the scenes. If you look at the CPython extension API, it turns out that pretty much everything is a PyObject.
Re:Stop writing classes... by jules on Saturday March 17, 2012 @08:44PM (#3718710)
Why would it be difficult? That's just a lazy sequence or iterator in Python terms. In fact the standard way of writing that in Python is with a function and `yield` or a generator expression, not with a class.

    def read_csv(file):
      for line in file:
        yield parse_csv_line(line)
-or-

    def read_csv(file):
       return (parse_csv_line(line) for line in file)
-or-

    def read_csv(file):
       return map(parse_csv_line, file)
-or-

    from functools import partial
    read_csv = partial(map,parse_csv_line)
None of which involve defining a class.
Re:Stop writing classes... by pjscott on Saturday March 17, 2012 @10:26PM (#3718919)
I notice that your first and second versions return an iterator, while your third and fourth versions return a list. So, you know, be aware of that. (If you want a version of map that doesn't force its arguments and produce a list, you can use itertools.imap. I wish it were a standard function so I didn't have to import it.)
Re:Stop writing classes... by masklinn on Sunday March 18, 2012 @04:45AM (#3719384)
> you can use itertools.imap. I wish it were a standard function so I didn't have to import it.)

In Python 3 it is (the `map` builtin is lazy, it's essentially `itertools.imap` and the old eager `map` has disappeared)

Re:Stop writing classes... by gruseom on Saturday March 17, 2012 @08:09PM (#3718634)
Couldn't you just do something like this?

  (let ((reader (csv-reader "data.csv")))
    (loop :for row = (reader) :while row
      :collect row[0] :into vals
      :collect row[1] :into avgs
      :collect row[2] :into stds
      :finally (list vals avgs stds)))
That's in the bastardized Lisp that I favour, but any language with closures should allow it. The point is, no classes.

I don't want to seem fanatical about this - your example is a fine use of objects. But unless I'm missing something, one can do just as fine without them, and with a little less code (since you don't have to define a class).

I (maybe!) have no problem with classes for things that, as you say, are concrete and have clear interfaces. But then, when things are concrete and have clear interfaces, there are a lot of nice ways to do things. Making things well-defined and clear in the first place is the hard part.

Re:Stop writing classes... by barrkel on Saturday March 17, 2012 @11:43PM (#3719031)
Objects are collections of closures that share state. As soon as your interface has more than one closure, you've more or less reinvented objects to solve that problem.
Re:Stop writing classes... by gruseom on Sunday March 18, 2012 @12:19AM (#3719088)
But (a) classes demand names, and that's critical, and (b) I almost never need more than one closure. Oh, and (c) this is far from the organizing principle of the system.
Re:Stop writing classes... by barrkel on Sunday March 18, 2012 @01:18AM (#3719180)
Dictionaries, lists, tuples and other structures also demand names. Getting away from classes does not free you from the need for names; and in a dynamically typed language, it requires even more attention to names - see my other comment http://news.ycombinator.com/item?id=3719056

I almost invariably find I need more than one closure down the road, outside of simple predicates handed off to algorithms. Even for such simple things as specifying a sink for output (out :: string -> ()), later on I find myself wanting a flush() routine. That's just my experience: problems grow thornier over time, and starting out with something more object-like adapts to that growth more gracefully than a closure does.

I think a lot of the problem comes from the syntactic weight of classes. I've implemented closures in a commercial compiler; the actual implementation, when it uses captured state, is very similar to a class, and in fact the implementation method I chose behind the scenes was a class. So I tend to view closures (rather than simple function literals that don't capture state) as just a concise way of declaring and instantiating an object.

I've had some success with blending the two. For example, a read-only collection facade is often implemented in .NET with ReadOnlyCollection<T>. But the normal way of implementing that thing is to pass off an IList<T>, which you may need to implement wholly if the logical read-only collection is not already a list. I think that's a complete waste of time; instead, I wrote a function that takes two closure arguments, getCount :: () -> int and getItem :: int -> T, and henceforth I can create a new collection with new behaviour without worrying about the "name" of the descendant, but with the benefits of a class for flexibility down the road.

Re:Stop writing classes... by sixbrx on Sunday March 18, 2012 @11:18AM (#3719849)
> Dictionaries, lists, tuples and other structures also demand names.

Those are just names for values though, we don't have to create a name for a new general principle just to use one.

Not to mention values often do not need names at all, in an expression oriented style where function calls are composed.

Re:Stop writing classes... by barrkel on Sunday March 18, 2012 @03:39PM (#3720656)
Any time you have a dictionary or list of something, there must be some regularity in the entries, otherwise you can't do anything meaningful with them; call that regularity a type, and you can give it a name (or choose not to). If you don't give the type a name, you'll probably give it a name via the variable (or else have very cryptic code). In any case, it has a name, irrespective of whether it's a type or a value.
Re:Stop writing classes... by sixbrx on Sunday March 18, 2012 @07:00PM (#3721324)
> you'll probably give it a name via the variable

Variables are easier to name than the more general notion of class or type (being specific to what is immediately at hand and thus not a distraction), which I think was the original point.

And even assuming that my structures will be named is assuming too much. Consider common uses of the fold function, e.g. which act on the pair of (accumulated-value, item). It's common that the pair isn't named. It's parts are named usually, but that's beside the point, I wasn't forced to name the structure itself, much less create a "AccumulatedSumWithNextItem" class.

Re:Stop writing classes... by barrkel on Monday March 19, 2012 @03:08PM (#3725602)
If your problems are trivial enough that they reduce to folds, sure, these concerns go away; but AccumulatedSumWithNextItem would be a terrible name in any case, because it only describes the type, not its intent.

For example, List<Customer> describes both the type and its semantic content. List<Tuple<string,DateTime,int>> just describes a type; it's a lot less self-documenting, and code using it will be cryptic. In a dynamic language it will probably be customer_list or somesuch. Point being, "customer" is a name and it crops up somewhere, whether it's in the variable or the type.

Re:Stop writing classes... by krig on Sunday March 18, 2012 @09:08AM (#3719650)
This is horribly off-topic, but perhaps relevant still: Can you share the details of this bastardized Lisp that you favour? Is it a lisp that is generally available, or one that you made up on the spot? I'm curious.

I don't know the ins and outs of the loop macro, only that it has a lot of them, so perhaps this is simply Common Lisp and I need to keep reading my CL books, but the "row[0]" sugar makes me think that there is something else going on.

Re:Stop writing classes... by gruseom on Sunday March 18, 2012 @03:51PM (#3720694)
I made that example up (it's CL, except for row[0]), but it's the Lisp I want. I'd love to share the details because they're very specific and come directly from the application I'm writing. But we probably shouldn't go so far off-topic here. You're always welcome to email.
Re:Stop writing classes... by scott_s on Saturday March 17, 2012 @08:32PM (#3718684)
Honestly, I'm not sure if you can do that in Python - one of the side-effects of not writing classes in Python is that I'm also ignorant of the behind-the-scenes stuff that goes on with them.

You may be able to get something close to what I wrote with a function that returns a closure, but I don't think you can get exactly the for x in y syntax. As explained in another post on HN's front page, "A Guide to Python's Magic Methods": http://www.rafekettler.com/magicmethods.html#sequence, you need to define the __iter__(self) method on an object to support that style of iteration. (And that method needs to return an iterator object.)

And that brings us back to the same point I already made, but I think it's so important that I'll say it again: the abstractions you choose to represent concepts in your program will be determined by what is easy in the language you're using.

Re:Stop writing classes... by gruseom on Saturday March 17, 2012 @08:37PM (#3718694)
Ah I didn't realize Python's limitations (if it has them here) were part of the mix. I strongly agree with your general point and will go one further: this has a huge impact on the kind of system that over time gets developed in that language. It conditions what gets written, which conditions what's easy to do next and eventually what's possible to do next. By making different things easy, languages bias the programmer toward thinking different thoughts. I wish more people would figure this out: it would make discussion of these things much more interesting. (Instead, all we really do is comparison of code snippets in different languages, which kind of misses the whole point.)
Re:Stop writing classes... by scott_s on Sunday March 18, 2012 @04:30PM (#3720833)
Something that the objects I had in mind have in common: they're resources. They fundamentally require a handle, and associated functions that accept that handle as a parameter. There already is a tight coupling between the resource handle and those functions. Such resources, off the top of my head: files, sockets, locks, condition variables.
Re:Stop writing classes... by empthought on Sunday March 18, 2012 @09:57AM (#3719701)
Check it out...

     def fibonacci_sequence():
         a, b, c = 0, 0, 1
         while True:
             a = b; b = c; c = a + b
             yield b

     >>> fibonacci_sequence()
     <generator object fibonacci_sequence at 0x108055550>
     >>> list(itertools.islice(fibonacci_sequence(), 0, 10))
     [1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
     >>>

     for n in fibonacci_sequence():
         print n
         if n > 13:
             break

     1
     1
     2
     3
     5
     8
     13
     21
     >>>
Re:Stop writing classes... by scott_s on Sunday March 18, 2012 @11:33AM (#3719884)
Yes, I had forgotten about generators, pjscott and jules provide great examples for the csv case above.
Re:Stop writing classes... by BrandonM on Sunday March 18, 2012 @05:48AM (#3719433)
A function that yields instead of returning values results in an iterator. One does not need to define a class at all.
Re:Stop writing classes... by icebraining on Saturday March 17, 2012 @08:50PM (#3718719)
A closure is essentially just a class by another name and with slightly different syntax. Yeah, you can replace classes with them, but to what purpose except to be able to say "no classes"?