News for hackers. Stuff that matters.
Re:Stop writing classes... by gruseom on Saturday March 17, 2012 @05:09PM (#3718215)
A few years ago, I quit organizing my code in terms of classes altogether. Everything got so much simpler that for me that whole way of looking at programming is now a gigantic mistake. It's true that you have to have a powerful enough language to get away with writing only functions, or at least one that doesn't impose classes on you, but that's true of lots of languages nowadays.

Freud said sometimes a cigar is only a cigar. I say sometimes a function is only a function.

Classes get in the way between the programmer and the problem. They force you to reify your thinking into "things" (classes) that demand names and citizenship rights, so to speak, in the system. These "things" don't really exist, but we act like they do, and so increasingly see the problem in terms of the classes we've defined. This is a distorting filter that we can ill afford when the problem is complex (if it's not complex, who cares - anything will work ok). The solution is not to define such pseudo-things in the first place, but rather to focus at all times on the problem at hand. Functions, for me, are the right level of abstraction to do this. They don't get in the way.

Once a bunch of classes have taken residence in your system and your brain, it's hard to remember that they aren't real, and thus the pain threshold is quite high before you realize that they're causing problems. At that point they're hard to change: you have to replace the old class hierarchy with a new class hierarchy. The difference between that and reworking a few functions is the difference between working in concrete and clay.

There's also the cognitive tax of having to think about what classes to create and what to name them. This too is overhead we can ill afford given our limited mental resources. If you've ever found yourself putting some code in a new class (perhaps because the old one got too big, or because you need to use it from two places) and gotten stopped in your tracks by the question, "What should I name it? What is this thing?" you are experiencing the overhead I'm talking about. It's the programming equivalent of Mr. Heavyfoot: http://www.youtube.com/watch?v=R9d2Y1We-d0. There is no such thing; you're just working in a way that forces you to pretend that there is and fulfill a bunch of duties towards it.

These two issues together are a double-whammy: you pay up front for what you pay for later.

It is shocking to see how much simpler systems become when we stop doing the things that make them complicated.

Re:Stop writing classes... by haberman on Saturday March 17, 2012 @09:13PM (#3718764)
I couldn't disagree more.

Classes are nothing but:

  1. a group of data attributes, and
  2. a defined set of operations that can happen on instances
     of those data attributes.
If you are opposed to classes, which of these characteristics are you opposed to? Since I think it would be pretty much impossible to be a programmer and be opposed to structs or tuples, it must be the latter that you don't like: giving structs an associated set of methods that operate on them.

But having a set of methods that define the state transitions that are possible on an object is incredibly useful, for so many reasons. It helps organize your code. It provides nicer, more intuitive syntax. But most importantly, it reduces program complexity by narrowing down the set of code that can directly modify the attributes of an object.

Without this encapsulation, any piece of code anywhere in the program could be modifying data attributes in any way, and it is extremely difficult to reason about the state transitions that any particular struct could be taking.

There is no rule that says classes have to be in any kind of hierarchy at all, and in fact "prefer composition over inheritance" has been common wisdom for years now.

I recently rewrote a very useful but hard to follow JavaScript library in a more object-oriented style. The old code has a bunch of maps everywhere that can be read or written by any part of the code, and it's very difficult to follow. In a more object-oriented style the structure of the code is far more obvious, and the state transitions that each object can take are far more clear.

Re:Stop writing classes... by gruseom on Saturday March 17, 2012 @10:32PM (#3718926)
Upvoted, but I disagree with every paragraph :)

I don't accept your breakdown of what classes are "nothing but". You've omitted at least one critical thing: the name. But even if the list were complete, it's a fallacy to say "if you dislike the combination, you must be opposed to one of its components".

(The name is critical because the human mind leaps irresistibly from names to things, something you appear not to be considering. But I already wrote about that.)

Organizing code, making it nicer, reducing complexity? all I can say is that my own programs got far better when I stopped organizing them into classes. They became shorter, easier to write, easier to test, easier to change, and more fun to produce. But we're in YMMV territory here. I do feel like stating, though, that I worked for years in the style you describe. I even taught it. And I said and believed many of the same things. Should that count for something? Maybe not. Maybe I just got bored and went off.

Encapsulation? The most grossly overrated allegedly simplifying mechanism ever. But "any code could be modifying blah"? Any code can do a lot of horrible things. Trying to rely on technical constructs to prevent it just adds weight and bloat and impediments. Let's have flexible languages and be good programmers.

Difficult to reason about? The hardest code I've ever tried to understand has been complex object models where Thingy depends on Fooey which needs a Bingy and a Batty, and to construct a Batty you need a... Compared to this sort of conceptual glob, bad procedural code has always, in my experience, been easier to understand.

Inheritance vs. composition? Not relevant here. Maybe I should have said "graph" instead of "hierarchy". Whether A "is" or "has" a B, that's still an edge in a graph, and it's those object graphs I'm talking about. They are much harder to rework than functions. The trouble is that when we believe that programming is making object graphs, we assume that difficulty to be part of the problem and don't notice it.

Rewriting? You rewrote something to be clearer and more intuitive to you and maybe to others who share your beliefs. That it happened to come out in objects is a consequence, not a cause, of what you find clear. It's a lot harder to judge clarity across assumption sets. For example, I work a lot in JS and defining JS objects is the one thing I never do. Maybe if each of us put our code in front of the other we'd recoil to exactly the same distance :)

Re:Stop writing classes... by tfb on Saturday March 17, 2012 @11:56PM (#3719052)
I'm glad to see this discussion on HN, because I've always wondered if there was something I was really missing regarding OO programming and whether or not coding in that style exclusively would make me a better programmer. Obviously it's all subjective and somewhat dependent on the task at hand, but my concern is probably more with whether that "style" of thinking is beneficial.

Then, fairly recently, I dabbled in some OO programming when I was making a mod for Unreal Tournament (I've also coded in C++ in the past, but not extensively); and I realized that I had already been using the same line of thinking with my functional programming in the way I was using structs, tuples, etc. When you really get down to it, it's really all just syntax and semantics.

For whatever reason, my brain has always naturally leaned towards the functional style; and it's just my opinion (of which gruseom seems to agree) and my opinion is probably only the result of how my brain works, but something about OO programming always seemed unnecessary for me. It seems to me like it's just another way for people with different thought processes than my own to represent their program logic. To me it seems a little too verbose and entirely too repetitive, and I always felt like the overhead required to "classify" everything wasn't worth it; but it's all in how you look at it, how your brain works or what you're used to. So what seems unnecessary to me (and makes it harder for me personally to trace the program's logic) might be perfectly comprehensible code for someone else; and some of the relatively minimalistic code I attempt to write might seem perfect to me, while an OO-minded programmer might feel like it's scattered about and hard to understand.

Good code is good code, regardless of the paradigm.

Re:Stop writing classes... by usaar333 on Sunday March 18, 2012 @12:38AM (#3719120)
> I dabbled in some OO programming when I was making a mod for Unreal Tournament

> but something about OO programming always seemed unnecessary for me.

I actually learned to program making mods for Unreal Tournament (1999). I'd love to hear more about your feelings about how OO seems unnecessary.

For me, UT was a prime example of OOP (both the general bundling data and functions together as well as inheritance) being used to simplify things. Key is that any instance of 'actor' is a single physical object rendered in the world. A subclass of 'actor' is "inventory" - items that can be picked up and held by players. Below that is the "weapon" class; which a player can switch between, fire, and are rendered in 1st and 3rd person views.

Obviously you don't need to be OO to pull off a game; many FPS games are not. But it makes things so easy to handle. If you build a new weapon, all of the functions to handle picking it up, rendering it, etc. are written in super-classes. But if you want, you can over-ride those. Furthermore, the weapon interface is well-defined to external entities; e.g. the 'playerpawn' knows his weapon has a 'fire' method.

I'm not sure how you could build an equally powerful and customizable engine without using OOP techniques at some level. Sure a weapon could be a struct, but how would you know what associated fire() method you would call? Unless you want a bunch of non-extensible case statements, you'd need a function pointer in the struct itself.. and once you couple the data and methods, you are getting close to OOP.

One thing I loved about UT compared to Quake-engine games was its extensibility. OOP allowed reflection; just 'spawn weaponpackage.weapon' and you can use a custom weapon. This also allowed gameplay "mutators" to blend together. Quake games in the day required a custom -game argument at startup; and consequently custom content could not easily be merged together.

Of course, this is how I learned to program so my brain may be overly-wired that way.

Re:Stop writing classes... by chipsy on Sunday March 18, 2012 @03:31AM (#3719329)
As someone who works in games, I should point out that the industry has rejected the hierarchical OO model in new engines because it doesn't remain maintainable at scale.

The influence that is driving the new stuff - component systems and composable entities - can be seen as derivative of the actor model. Actor models go beyond what is present in most game engines, which tend to stay well on the imperative side of the line. It takes a heavy dose of purity to grok actors in full, but it dovetails well with functional style as an alternative view of computation. (I also recommend the Tim Sweeney POPL06 "Next Mainstream Language" talk to see exactly what problems are motivating the changes)

First, aim to never store values on objects - prefer instead listeners that return values independent of the objects themselves. Suddenly you start to enjoy "code=data" just as in Lisp, because the semantics of getting data and processing data are identical and interchangeable - you can take a getter on one object and copy it to a different one, and they'll return the same data, even if their other methods are completely unrelated!

Decoupling occurs naturally in such a system - instances can be as similar or different as desired. The usage of classes shackles these abilities into monolithic, heavily-coupled data structures again, which is the core point of difference from "OO" as we know it in industry.

If you also stay purely asynchronous at all times, there is no longer a difference between "now" and "later" to the callee, so order-dependent operations can naturally transition from one-to-one mappings into arbitrary ordering and queuing. Pure asynchronicity was lost when actor-style systems first tried to enter industry(e.g. Smalltalk-80 opted for a synchonous system - a concession to single-threaded performance), but it's come back into vogue in this heavily-parallelized era.

Fortuitously, it's straightforward to achieve these properties in languages that support closures and reflection. And you don't have to write entirely in this style; raw data structures can be written imperatively, and then tied together using actors. The listeners can access a common database to look up values. You can mix and match.

State-of-the-art game entity systems aim to cut down this level of power into a palette of performance/power options for composition, but if you can live with high overhead, taking all the power is pretty simple to do. I wrote a prototype for it yesterday - 169 lines of Haxe.

Re:Stop writing classes... by timruffles on Sunday March 18, 2012 @05:30AM (#3719419)
That is fascinating, and I for one would get a lot out of seeing some code. Any chance of posting your prototype in a gist please? :)
Re:Stop writing classes... by chipsy on Sunday March 18, 2012 @06:27PM (#3721214)
You(and the other commenters) prompted me to do something I've been meaning to do for a while: Get my code on github.

The actor system (Haxe highlighting is broken): https://github.com/triplefox/triad/blob/master/dev/com/ludam... And example: https://github.com/triplefox/triad/blob/master/examples/Sour...

Re:Stop writing classes... by paperwork on Sunday March 18, 2012 @10:19AM (#3719731)
I was thinking the same thing while reading the post :) Code or more fleshed out critique (even pointers to others' critiques) will be great.
Re:Stop writing classes... by ericflo on Sunday March 18, 2012 @06:53AM (#3719486)
Agreed--I'd love to see this as well.
Re:Stop writing classes... by noonat on Sunday March 18, 2012 @11:40AM (#3719903)
I learned a lot from Quake 1. QuakeC [1] was not object oriented, although it had one struct type: an entity. The entity struct had function pointers that were used to attach handlers for various events (touch, think, etc.), but there weren't methods per say, or a class hierarchy. The code was very procedural. You could not define new types, and could only make limited modifications to the entity struct's definition.

This restriction was often frustrating, but limited types meant the language was very approachable for beginners. Once a programmer understood the entity and its attributes, they knew what they had to work with. They only needed to find interesting ways to transform data, not interesting ways to organize data.

While sometimes frustrating, the simple type system rarely limited the creativity of developers. This is evident in the wealth of mods that were created for the game. People built Diablo style RPGs [2] with it, racing games [3], and much more.

In Quake's sequels, the modding system grew more flexible (and also more complex). The number of mods seemed to decrease. The amount of mod content for Quake 2 was less than 1, and Quake 3's was far less than 2. The mods that were released were often far more polished, but I think this is representative of the skill level and determination that was required to actually build mods for those games.

Garry's Mod [4] is only modern game I've seen with a similar level of successful modding activity. It also uses a scripting language (Lua). Garry's Mod defines a strict set of structs that you use to interact with the host game engine (effects, entities, tools, and weapons). It feels very Quake-like.

I personally feel like these kinds of restrictions create flatter code, and structure that is easier to hold in my head. I find myself concentrating more on features, rather than on code organization.

[1] http://www.inside3d.com/qcspecs/qc-menu.htm

[2] http://www.inside3d.com/prydongate/

[3] http://www.quakewiki.net/archives/qca/reviews/patch70.htm

[4] http://garrysmod.com/

Re:Stop writing classes... by andrewflnr on Sunday March 18, 2012 @12:33PM (#3720028)
Nitpick: "per se".
Re:Stop writing classes... by overgard on Sunday March 18, 2012 @01:48AM (#3719226)
As a person who has written games, I think games are one of those weird cases where OO really shines, but I don't think it's representative of most general programming problems. In my experience OO makes a ton of sense when you have a lot of mutable state that actually represents a tangible real world object or metaphor. So that works great for games, which are all about simulation, and where you actually have a lot of things that really do map to an "object".

But, outside of simulations, a lot of programming problems come down to things that don't have a convenient real world mapping. A lot of it is just data transformations, and data transformations are awkward in an OO setting, because the focus is on the object rather than the process. This is where more functional styles really shine, (for instance, in compilers and such), where the existance of an object would be incredibly transient and short lived, because the goal is to transform one set of data into another representation. OOP basically sucks at this.

Objects are certainly useful, but I think they've been fetishized to a weird degree.

Re:Stop writing classes... by wladimir on Sunday March 18, 2012 @08:52AM (#3719625)
OOP works very well for UI code. I got introduced introduced to it in that way, back with Turbo Pascal. When you bought a compiler you got this wall-filling poster with the class hierarchy. Great fun. Nowadays, this is still reflected in toolkits such as Qt.

It also tends to work for things that can be represented as opaque handles (such as files, sockets, ...). Polymorphism helps there to be be able to treat different but similar objects in the same way. No need for deep, nested hierarchies there though.

But I agree that outside the domain of UIs it quickly diminishes in value.

Re:Stop writing classes... by kls on Sunday March 18, 2012 @02:30PM (#3720399)
I agree, I think where we went wrong is in these one size fits all type designs. I like OO and events for UI, I feel that it is more powerful than other paradigms like say controller / template. I think black box widgets that respond and emit events and that can be inherited work in a manner that reflects my thought process. For example I always use a select box, where you have the standard select box and via extension or mixing in, you can create a filtering select box that adds the behavior of filtering type ahead. To me this works very well and promoted loose coupling of the interface as well as reusability of components.

Once I move past the UI though I really start to feel the burden of OO start to drag me down as far as productivity goes. It requires a lot of organizational overhead to force overtly service based functionality into OO structures, something like getUserList is functional at it's simplest form and should remain so. When working with Java I tend to discard OO by creating static functional classes that acts as a service and util layer. I find that doing so simplifies the architecture of the system and eliminates a lot of spaghetti code that has to be written to deal with making functional logic OO.

For that reason I tend to prefer languages that can do both, or that don't force a pattern on you at all, and that leave it up to the library developers to work out patterns. JavaScript despite it warts is a good example of the library developers building out that layer of the language. I also find myself writing more and more back end code in Clojure for that reason, while it is a functional language it does not preclude the ability to write OO code if it is the right pattern for a particular problem set. I like not having to fight the language to break free of the constraint.

Re:Stop writing classes... by telent on Sunday March 18, 2012 @06:32AM (#3719465)
> the focus is on the object rather than the process

From a business apps point of view, this is exactly it. You might find that methods are subordinate to objects, but in the business domain itself, the objects themselves are manipulated by processes. It's a whole other layer above the OO layer, and failure to realise this means you either end up with lots of FooManager classes, or you push overarching responsiblities back down into low-level objects that don't really want them, and find you have too much coupling and not enough Demeter

(Of course, you might be writing FooManager classes with this upper layer explicitly in mind - in which case fair enough and you'll probably like DCI. But I think there's still a lot of mileage in plain ordinary functions that don't have to belong to anything)

Re:Stop writing classes... by telemachos on Saturday March 17, 2012 @11:06PM (#3718977)
To follow up on gruseom's comment that YMMV, I would point you to Joe Armstrong's (Erlang creator) "Why OO Sucks"[1]. The title isn't great, and you may hate the content, but the interesting thing (to me) is that he makes a lot of the same basic points as you and then he draws all the opposite conclusions.

Maybe a reasonable conclusion is that there is no silver bullet for managing complexity and making things easier to reason about.

[1]: http://www.sics.se/~joe/bluetail/vol1/v1_oo.html

Re:Stop writing classes... by loup-vaillant on Sunday March 18, 2012 @02:50PM (#3720492)
No silver bullet? Check this out: http://vpri.org/html/work/ifnct.htm

They already have some results: http://www.vpri.org/pdf/tr2011004_steps11.pdf

To sum it up, they do "personal computing" in about 4 orders of magnitude less code than current mainstream systems (from more than 200 millions lines to about 20,000). That includes the self-implementing compilers. The only thing they left out was the device drivers (which by the way takes less than 0.5% the size of current systems).

Now the Complexity Werewolf just went from "Unspeakably Awful Indescribable Horror" to "Cute puppy".

Re:Stop writing classes... by Alexandervn on Sunday March 18, 2012 @05:46AM (#3719432)
That's a really interesting article. Too bad the <title> of that document is 'Test page', making it practically unfindable with Google, SEO-wise.
Re:Stop writing classes... by anamax on Saturday March 17, 2012 @10:37PM (#3718938)
> Classes are nothing but:

> 1. a group of data attributes, and

> 2. a defined set of operations that can happen on instances of those data attributes.

It must be nice to live in a world where a given piece of data belongs in only one group.

Re:Stop writing classes... by hackinthebochs on Sunday March 18, 2012 @04:38PM (#3720870)
The point you're implying here is unclear. Can you expand on it?
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"?
Re:Stop writing classes... by pnathan on Saturday March 17, 2012 @06:53PM (#3718456)
I have a similar approach. I only use classes when I find myself passing around an object that is starting looking suspiciously class-like. While this adds a refactoring burden, it turns out most of the time, OO is a waste of time, and a few arguments is all you need. Some things are objects, in and of their nature. So it turns out that they transform into classes very nicely. But most of the time, you have data, and you have things that work on that data, and it really does you no good to nounize the world too far. You wind up going off into this ontological modelling foolishness, and as a rule of thumb, you wasted your time.
Re:Stop writing classes... by gruseom on Saturday March 17, 2012 @06:55PM (#3718462)
In what language do you find it easiest to make classes only when you feel like it?

most of the time, OO is a waste of time, and a few arguments is all you need

That reminds me of another key point. I try not to let function signatures have more than a few arguments, and I try to keep those arguments primitive. (A good litmus test is how easy it is to call from the REPL.) When my code starts to break these guidelines, that's a sign of design weakness, and I do what it takes to break up the complexity. It still amazes me how far you can get in terms of simple, decoupled design just by doing this.

The widespread OO practice of factoring some of those arguments into a new class, so that now you need pass only one thing (the new composite object) instead of several old ones, does nothing to solve the problem, but instead makes it worse: you've both added complexity and lost transparency. It's like a kid saying yes when mother asks "did you clean your room", having shoved all the mess under the bed.

Re:Stop writing classes... by hackinthebochs on Saturday March 17, 2012 @10:58PM (#3718963)
I feel all this talk against OO is missing the fundamental idea being objects: You are in fact strictly reducing the solution complexity by the proper use of classes. They are a mechanism of data-hiding. I know data within a class cannot be accessed outside of my defined interface, thus my "interaction space" has been reduced. That is, there is data I can't access and code that cannot access my data. This is a marked reduction in solution complexity.

The same can be said about functional programming. But once you degenerate to passing a ton of parameters around in each function call, you're probably better off defining an explicit object anyway.

Measuring complexity by number of lines and saying defining a class is adding complexity is off the mark.

Re:Stop writing classes... by chousuke on Sunday March 18, 2012 @04:55AM (#3719394)
My intuition tells me that hiding data in objects does not really help as long as the data is still mutable. Immutability is the only way to guarantee true encapsulation for objects that don't actually represent something inherently stateful. (eg. file on disk)

Coupling data and operations is also a problem. It's non-extensible, both in that you can't add more data and use the same operations, and you can't add more operations that work on the added data. Inheritance works around some of this, but it doesn't solve the general problem. What if it makes sense to add the same piece of data to objects of classes from different parts of the hierarchy?

The thing about functions is that you can always write a new one that works with anything you want. You don't need to add it to a class or an interface (you can, if the language allows that), and if possible, with immutable data that essentially makes the function a unit of perfect encapsulation.

Re:Stop writing classes... by gruseom on Saturday March 17, 2012 @11:13PM (#3718989)
You're going to have to offer some evidence for this, because (as many threads on HN have discussed) all the evidence I've seen points to precisely the opposite of what you say: the best measure of complexity is simply the overall size of the program. If that's true, defining a class certainly does add complexity, and your argument is plausible but wrong.

Not content with repeating myself in this thread, I will repeat myself from threads of the past as well: it's astonishing that the evidence is so consistent on this, yet almost nobody takes it seriously. But I do! And I have a really interesting question, too: what it would it mean, not just for a programmer to organize their work around this principle, but for an entire company to do so?

Re:Stop writing classes... by hackinthebochs on Saturday March 17, 2012 @11:41PM (#3719027)
You're probably referring to the study that showed lines of code correlated with error rate. I completely believe it. But I think there's more to it than that.

We all know that lines of code is a poor measure of code complexity, but it does correlate with it. It is far more reasonable that error rate is proportional to code complexity, which is weakly measured by LOC.

Unfortunately I don't have any studies to back up my intuition here. But I would bet that my definition of complexity, aka "interaction space", would correlate much stronger to error rate than LOC does. Also, that decently good usage of classes would in fact reduce the complexity, and thus error rate.

Re:Stop writing classes... by jodrellblank on Sunday March 18, 2012 @02:09AM (#3719251)
Unfortunately I don't have any studies to back up my intuition here. But I would bet that my definition of complexity, aka "interaction space", would correlate much stronger to error rate than LOC does.

Intuition is often surprisingly wrong - lesswrong.com shows a lot of examples. That doesn't mean it's wrong in this case, but now you have code which is hidden so the interaction space is limited, so there could be:

1) Now you have to add complexity to get information into and out of this interaction space. Similar to how it's easier to walk onto a field than it is to walk into a castle - if the walls protect the contents, they also contort your path around them.

2) Leaky abstractions. It might be the case that your protected code is needed elsewhere. Now you have to duplicate it, or break around the protection/expose a new way through, all of which would not be necessary for a free function. At the very least you have overhead considering this. All of a sudden your neatly wrapped class is two classes, one in use in two places where you could again change code and have an effect far away if you're not careful.

3) In a language such as Python, you don't have your code inside a class protected by anything except convention. So it seems that you either must: a) accept that what protects groups of code is programmer attentive care, not the system of classes itself, and thus that any other programmer paying the right kind of attention could have the same benefits and less code, or b) declare languages like Python to be excluded from the benefits of classes by not implementing them properly. Do you agree?

Re:Stop writing classes... by gruseom on Sunday March 18, 2012 @12:30AM (#3719106)
First: not badgering you :)

We all know that lines of code is a poor measure of code complexity

We certainly don't! Program length is the only good measure we have. The best measure of program length is up for grabs, but LOC is probably as good as any (there was a big thread about this a few months ago).

But I would bet that my definition of complexity, aka "interaction space", would correlate much stronger to error rate than LOC does

But the best work on this points to so exactly the opposite of what you say, I would really recommend you take a look at it: http://www.neverworkintheory.org/?p=58 - and tell us what you think.

I'm going away now.

Re:Stop writing classes... by hackinthebochs on Sunday March 18, 2012 @05:21PM (#3721016)
Good link. The thing that stands out to me about the standard code metrics used in studies like this, is that they attempt to measure actual complexity, rather than perceived complexity. LOC perhaps is the only measure that directly measures perceived complexity. If I add 100 lines of code to my project, its possible that cyclomatic complexity stays constant (I didn't add any branches, just a straight fall through), but the perception of complexity no doubt increased.

If we can come up with more metrics that are based on our perception of a codebase's complexity, I think we would see interesting results.

Re:Stop writing classes... by pnathan on Sunday March 18, 2012 @01:04AM (#3719158)
> In what language do you find it easiest to make classes only when you feel like it?

Any language that isn't a fairly close C descendant. Haskell, Lisp, Python, Perl are languages I've done some work in with minimal OOness.

When I used Java a few years ago, it required classes. C++ winds up being very class-ish. C of course is limited.

I have come to be very pleased with not using classes unless the solution really demands it. It's sort of a "grow the solution" idea, instead of "waterfall the solution".

Re:Stop writing classes... by slowpoke on Sunday March 18, 2012 @03:15PM (#3720584)
>Any language that isn't a fairly close C descendant. Haskell, Lisp, Python, Perl are languages I've done some work in with minimal OOness.

At least in Python - which is the only one of those four I can speak for - all you are doing is basically OO (in fact, everything in Python is an object). The beautiful thing about Python is how it's abstracting a lot of this away by providing functions which implicitly call "magic methods" which are either generated by the interpreter or can be defined by the programmer (ie, __iter__(), __next__(), __init__()), and by virtue of Duck Typing, which means an object defines itself by what it can do, not its identity or origin.

You'd never even notice a lot of this unless you dip into the internals of Python a bit. And ultimately, I don't think this is actually possible without using OO or some close equivalent. So in the end, a lot of the "solutions" people have proposed in this thread ultimately depend on the very thing they want to "solve": Object Orientation.

Re:Stop writing classes... by tptacek on Saturday March 17, 2012 @10:57PM (#3718961)
I'm reminded of 100 horrible C APIs that take a "struct foo_opts" instead of just conceding that they need 7 or 8 silly arguments.

Or of "sockaddr_in".

Re:Stop writing classes... by barrkel on Saturday March 17, 2012 @11:49PM (#3719040)
The sockets API would be much more future proof if C better supported polymorphism. That's usually the reason for using structs instead of arguments; in Windows, most API structs start with the size of the struct, effectively indicating the version. Makes binary compatibility easier when you add arguments in version n+1.

sockaddr_in is the way it is because of sockaddr, sockaddr_in6 etc. Judicious polymorphism could have led to fewer headaches converting IPv4 apps to IPv6.

Re:Stop writing classes... by SkyMarshal on Saturday March 17, 2012 @09:28PM (#3718793)
"Classes get in the way between the programmer and the problem. ... Functions, for me, are the right level of abstraction to do this. They don't get in the way."

Couldn't agree more. I've long suspected that OO is a diversion or misdirection from actually solving the problem, rather than an inherent part of it. Discovering functional programming recently with Scheme and then Haskell has only reinforced that.

OO may be the appropriate abstraction for some things like GUI programming, which seems to be what it was originally created for, but not everything.

Re:Stop writing classes... by colomon on Sunday March 18, 2012 @08:48AM (#3719619)
I program 3D geometry and topology professionally. Let me tell you, the idea that my code would be simpler and clearer if I didn't have a Point3D class is purest insanity.

That doesn't mean everything needs to be a class -- that's crazy too. And except for special cases, my inheritance hierarchies never have more than two levels. (And I probably wouldn't allow Point3D, for instance, to be derived from.)

But classes are an incredibly powerful tool when they are needed.

Re:Stop writing classes... by sordina on Sunday March 18, 2012 @08:54AM (#3719630)
What advantage would a Point3D class have over, say, a Point3D data-structure here? (ernest question)

Is it the interface it provides, the types, the coupling of methods to data, or something else?

Re:Stop writing classes... by colomon on Sunday March 18, 2012 @10:51AM (#3719789)
I'd say the advantages are:

1) Naming it vastly clarifies further data structures and interfaces. (This is shared with having a Point3D data-structure, obviously.)

2) Providing functions and operators specific to the type.

At it's simplest (and possibly most compelling) it's the difference between needing to say

    p.x = p0.x + t * (p1.x - p0.x);
    p.y = p0.y + t * (p1.y - p0.y);
    p.z = p0.z + t * (p1.z - p0.z);
and

    p = p0 + t * (p1 - p0);
The latter is easier to type, easier to understand, and less error prone. It's a huge win, especially in more complicated expressions.

Now of course, your language may allow you to define data structure-specific functions and operators. But at that point, what you've got is essentially a class, even if you call it something else.

(PS Note that data hiding is completely unimportant here, and inheritance would be nothing but trouble.)

Re:Stop writing classes... by gruseom on Sunday March 18, 2012 @03:22PM (#3720606)
I agree with you that Point3D-type-thingies are a sweet spot, though your operator-overloaded line is not doable in most class-based languages, and indeed is generally controversial in OO, so I don't think it gets to count here.

That aside, you're quite right that when one has a common construct that permeates the entire program, one badly wants to give it first-class status in the language. What I've noticed, though, is that these constructs don't tend to get involved in complex object graphs (or if they do, they're leaf nodes). Rather, they tend to be atomic and universal (i.e. interoperable with anything) and simple. So I wonder if what one really wants here is the ability to add new primitives to the language. That's potentially quite different from classical classes. It's more related to the "build up a language that fits the problem, then code the solution in that language" idea.

Re:Stop writing classes... by colomon on Monday March 19, 2012 @06:55AM (#3723327)
You might guess from my example how little respect I have for the "don't overload operators" argument. All I can say is, all the OO languages I've spent any time programming do indeed let you do that, and I'm sorry for you if your experience is otherwise.

So clearly I agree that adding primitives is an extremely important ability. But it's already nearly if not completely there in all the OO languages I use, using classes.

I don't think primitives are enough, though. The interface / implementations of interfaces combination is also essential to my programming. Being able to say "Curve" and have it mean Straight or NURBS curve or Circle or Offset curve or Composite curve or... is another huge simplifying device. In fact, I've just looked at my code, and I have 15 distinct curve types, at least 5 of which I'd have missed if you asked me to list them, despite having written all of them over the years. That is exactly the power of simplifying abstraction.

Let me point out that given a sufficiently capable OO language, this doesn't need inheritance to implement. This is just the implementation of a role or interface. But it does need classes.

Re:Stop writing classes... by sixbrx on Sunday March 18, 2012 @11:53AM (#3719936)
I think there is no question that being able to define new types is important. I don't, however think it's clear that having to pack operations that operate on the types into the types themselves is a good idea in general. Your example is easily handled with a simple type class in Haskell e.g., and no there's it's not "essentially a class" in the OO sense, as new operations can be freely added without modifying the type itself.
Re:Stop writing classes... by colomon on Sunday March 18, 2012 @06:07PM (#3721162)
Er, I've never used a OO language that didn't allow you to add new operations freely without modifying a class. Not all of them allow you to add new methods, sure, but new functions and operators are par for the course.

And surely you're not arguing the defining feature of a class is that it's closed?

Re:Stop writing classes... by lukifer on Sunday March 18, 2012 @07:22AM (#3719518)
Hear, hear. I use classes when I actually need the functionality offered by classes, or when it's a good cognitive fit. Often, simple functions and data structures do the job.