369 points · by andybak · 14y ago · 197 comments
3DPoint = collections.namedtuple('3DPoint', ['x', 'y', 'z'])
p1 = 3DPoint(3, 2, 4)
p2 = 3DPoint(10, 1, 10)
dist = math.sqrt((p2.x - p1.x)**2 +
(p2.y - p1.y)**2 +
(p2.z - p1.z)**2)
I don't mean to say that classes aren't useful in Python, just that I've gotten a lot done in the language just depending on hashes, lists, tuples, named tuples, functions, comprehensions and generators. I've never felt the need to define a a class - the closest I came, I realized I wanted a named tuple. It certainly would make sense in the above example to define "dist" as a member function of a 3DPoint class, but it's just not how I write code in Python.Contrast this with C++, where I define classes all the time. I think the reason for this discrepancy is that if you want to do anything interesting in C++, you almost have to define a struct or a class; that's where most of the abstractions happen. In fact, if I want functional style code in C++, I have to define my functions as classes. I think that Python's native tuple types, first-class functions and comprehensions make the difference.
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.
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.
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 :)
Maybe a reasonable conclusion is that there is no silver bullet for managing complexity and making things easier to reason about.
> 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.
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.
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! 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. (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.
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.
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.
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.
Is it the interface it provides, the types, the coupling of methods to data, or something else?
And in cases where you really do need class-like behaviour, it's easy to extend it with additional methods or operators, while still getting all the other convenience stuff for free:
class Point3D(namedtuple('Point3D', "x y z")):
def __add__(self, other):
if other.__class__ != self.__class__:
raise TypeError
return self.__class__(*[a+b for a,b in zip(self, other)])
print Point3D(1, 2, 3) + Point3D(5, 4, 2)Much of the benefit of C++11 and Boost is in not having to write functor classes.
Twice now, I've been faced with a metric crap-ton of Java source files for reading / writing to a device.
Anything you could possibly imagine, gets defined as a class. There's dozens of classes, and more SLOC than I can count.. Meanwhile, an equivalent C program comes in at 2k SLOC, and 4 files.
You().Can('not').Do(any(thing)).Concise().In(java())!
When I was primarily doing C++, I gradually switched to generic programming once visual studio supported STL... And then when I started using Perl I found I didn't need to write classes at all.
Reminds me of this Paul Graham quote: "This practice is not only common, but institutionalized. For example, in the OO world you hear a good deal about "patterns". I wonder if these patterns are not sometimes evidence of case (c), the human compiler, at work. When I see patterns in my programs, I consider it a sign of trouble. The shape of a program should reflect only the problem it needs to solve. Any other regularity in the code is a sign, to me at least, that I'm using abstractions that aren't powerful enough-- often that I'm generating by hand the expansions of some macro that I need to write."
This is just so wrong. The shape of your program should reflect your understanding of the problem, and the clearest way to communicate that to other humans. Patterns will be a part of this, as it reduces the amount of mental effort required to understand the solution.
It is true that writing too much boilerplate to create a pattern is a sign that your language is lacking necessary abstractions. But patterns themselves will always be a part of good software.
I swear this entire thread is just trying to rationalize bad programming practices.
In the neighboring programming-language kingdoms, taking out the trash is a straightforward affair, very similar to the way we described it in English up above. As is the case in Java, data objects are nouns, and functions are verbs. But unlike in Javaland, citizens of other kingdoms may mix and match nouns and verbs however they please, in whatever way makes sense for conducting their business.
For instance, in the neighboring realms of C-land, JavaScript-land, Perl-land and Ruby-land, someone might model taking out the garbage as a series of actions — that is to say, verbs, or functions. Then if they apply the actions to the appropriate objects, in the appropriate order (get the trash, carry it outside, dump it in the can, etc.), the garbage-disposal task will complete successfully, with no superfluous escorts or chaperones required for any of the steps.
There's rarely any need in these kingdoms to create wrapper nouns to swaddle the verbs. They don't have GarbageDisposalStrategy nouns, nor GarbageDisposalDestinationLocator nouns for finding your way to the garage, nor PostGarbageActionCallback nouns for putting you back on your couch. They just write the verbs to operate on the nouns lying around, and then have a master verb, take_out_garbage(), that springs the subtasks to action in just the right order.
Dictionaries and lists of things don't relieve you from the job of naming and encapsulating the data you're dealing with. But full on classes are usually only needed when behaviour needs dispatching from polymorphic locations, and that isn't too often.
It's the OO and design pattern culture that results in much of the Java code you describe as over-engineered. But you can write bad code in any language.
Taking software engineering advice from algorithm geeks is a mistake we've been making for decades over and over again.
In my professional life, I've not had a need to engineer a single algorithm. I have had to make plenty fault-tolerant, maintainable and understandable control software, though.
The same holds for most, if not all, of my colleagues. Common professional software engineering has nothing to do with sitting in a room on your own figuring out how to best store a dictionary in memory such that it is fast under insertions, removals and lookups.
Or is it that classes in Python specifically aren't that much of a win over the language's implementation of other paradigms? I sure haven't hit into any problems using classes or objects in Ruby, even when sometimes the use feels a little contrived to begin with, but.. I also have no choice :-) (maybe Rubyists have a Stockholm Syndrome with OO ;-))
In Python, it's reasonable to have a package with just functions in it, whereas in Ruby, writing a top-level method means polluting every object in the system. You can write modules that have singleton methods on them, but you still don't have anything as flexible as Python's "from pkg import foo, bar"—the caller needs to either write "ModuleName.my_function" at every call site, or use "include" and end up with the module's methods as part of the consuming class's interface.
After working with Perl (which has a similar namespacing), I must it's something I really miss when I come back to Ruby.
Python - take your __init__+1 method class and just make it a function
Ruby - take your initalize+1 method class and just make it a static method (and maybe make that class a module instead)
It's more that Python programmers prefer not to proliferate excess complexity or layering. They hate ravioli code.
This isn't to say his underlying message is wrong (I 100% agree with Jack's message, too much classes create unnecessary complexity in your library/app), but I don't want people destroying their classes without fully understanding the consequences.
In plain C, your main "method" can be a simple external function, and the "helpers" can be static functions. Python offers similar functionality.
Making a class is a step backward because the internal helpers have to exposed to users, even if they're intended not to be used.
My experience confirms this.
EDIT: Can't reply to Tommabeeng's comment (probably too deep). Yup, and I agree with the presenter's main point - that classes are not necessary in many situations, even for decoupling.
That's wrong. I like the key to his talk but the plague of large complicated systems is exactly coupling and incoherence. Classes are NOT necessarily the way to achieve these.
It's easy for people who are very smart and experienced to dismiss the rules - that applies for all things, not just programming. But if you never learn the basics then you'll stumble over silly things that have be solved by much smarter people.
var o = {
name: 'David',
greet: function () {
console.log('Hi, I am ' + this.name);
}
};What can you possibly believe a class is other than exactly that?
Very often when writing Python (or whatever) you'll create a class which is only ever instantiated once and the instantiation is done simply for the benefit of calling one method.
In such cases I find classes to be overkill. What I really want is the object. I don't need to factor the object's behavior out into a class.
Many of my sympathies are expressed much more thoroughly and eloquently in the many papers you can find online by Walter Smith outlining the motivations behind NewtonScript.
function greet(name) {
console.log('Hi, I am ' + name);
}
var o = function() { greet('David'); };I suppose that "true" objects are Erlang processes. (I'm only partly joking)
OOP gone wrong when it became structs with methods.
Edit: here you go:
http://news.ycombinator.com/item?id=2855500
http://news.ycombinator.com/item?id=2928672
http://news.ycombinator.com/item?id=2856567
http://news.ycombinator.com/item?id=2855508
The first two are teaser comments. The second two are the important pieces. Also the paper Kay praises at the start of the talk is short and very worth reading.
Unfortunately, this is the only way to perform this activity in Java. Also, I adore Go's style of pseudo-OO programming.
.. or, from reading the HN threads, is that decoupling?
If so, I'm using decoupling right now!
Alternatively, if you are working with things that you expect to follow a certain interface, Python does not really require a formal definition. Duck typing should suffice.
I agree on some of the presenters philosophical ideas, mainly that adding complexities into the codebase before they're needed is almost always a terrible idea, but saying that classes lead to complex code is simply not true, at least in my experience.
I think the distinction between 'end-users' and people who make libraries is an important one and one that Jack seemed to overlook.
That's a platitude which everybody can and does say about everything.
But I think one can make a case that there is something wrong with OO in general. The original arguments for OO were: it's better for managing complexity, and it creates programs that are easier to change. Both of these turned out not to be true in general. So we need to ask, when is OO a win? But for simpler problems it doesn't matter, because anything would work. So we need to ask: what are the hard problems that OO makes significantly easier? I don't think anyone has answered that.
I suspect it's that OO is good when the problem involves some well-defined system that exists objectively outside the program - for example, a physical system. One can look at that outside thing and ask, "what are its components?" and represent each with a class. The objective reality takes care of the hardest part of OO, which is knowing what the classes should be. (Whereas most of the time that just takes our first hard problem - what should the system do? - and makes it even harder.) As you make mistakes and have to change your classes, you can interrogate the outside system to find out what the mistakes are, and the new classes are likely to be refinements of the old ones rather than wholly incompatible.
This answer boils down to saying that OO's sweet spot is right where it originated: simulation. But that's something of a niche, not the general-purpose complexity-tackling paradigm it was sold as. (There's an interview on Youtube of Steve Jobs in 1995 or so saying that OO means programmers can build software out of pre-existing components and that this makes for at least one order of magnitude more productivity - that "at least" being a marvelous Jobsian touch.)
The reason OO endures as a general-purpose paradigm is inertia. Several generations of programmers have been taught it as the way to program -- which it is not, except that thinking makes it so. How did it get to become so standard? Story of the software industry to date: software is hard, so we come up with a theory of how we would like it to work, do that, and filter out the conflicting evidence.
Wrong. Even the worst Enterprisey mess of Java classes and interfaces that you can find today, is probably better than most of the spaghetti, global state ridden, wild west that existed in the golden days of "procedural" programming.
If you consider that software is composed of Code and Data, then OOP was the first programming model that offered a solid, practical and efficient approach to the organization of data, code and the relationship between the two. That resulted in programs that, given their size and amount of features, were generally easier to understand and change.
That doesn't mean OOP was perfect, or that it couldn't be misused; it was never a silver bullet. With the last generation of software developers trained from the ground up with at least some idea that code and data and need to be organized and structured properly, it's time to leave many of the practices and patterns of "pure" OOP and evolve into something better. In particular, Functional has finally become practical in the mainstream, with most languages offering efficient methods for developing with functional patterns.
Part of the allure of Java: it gives the illusion that more progress was made before you entered that region.
We've all heard that you can shoot yourself in the foot with any language, but I think the implications haven't fully sunk in: There are no bad paradigms, only bad codebases.
How so? I find OOP code to be much easier to understand and change.
There were also some revelations - like printer().getSingleton() (or instead of printer, put keyboard, mouse, memory, etc.) - at some point some of these "singletons" might be become "multi-tons" - for example gamepad().getSingleton() already is a trouble...
"The singleton pattern combines all the perf benefits of a global variable with all of the code maintenance benefits of a global variable."
1) Do not use a class if it doesnt have state
Agreed
2) Keep it simple and do not think about the future, fix it later if needed
He probably never wrote API code in libraries needed for other people. Once you choose something you are bound to it. In this case classes and interfaces are very helpfull. For example the API class example in the beginning (no state) is a good example. In the future the api might be extended with more functionality. The last thing you want is have 3rd parties rewrite their code cause you changed the API. So a class is good to provide a Facade (yes Facade Pattern).
3) package names are not for taxonomy but for preventing nameclashes
True. However in Java the editor is so powerfull that you never ever have to lookup package names. This goes automatically (IDE parses the code on the fly). Java package names also use URI patterns like: com.google.android.hardware.vibrator. Which can only be used by somebody who has the google.com domain name. This prevents name clashes ALL the time. In python you sometimes have to rename a whole project. And the taxonomy gives you an indication what the code actually does.
4) Dont overuse exceptions and keep shorts names.
Agreed. However i am not sure what the best granularity is. In a public Library API, i would be very carefull about this.
Otherwise I agree with him.
Classes are fine. Over-engineering classes, like over-engineering anything is bad, m'kay?
The benefits of Classes are still related to data abstraction. But it is pointless if you are still accessing the data directly anyway (getters and setters be damned). So, I would only legitimately prescribe a class only when you are building a data structure.
Nowadays, my classes are either - composition of primitive data (as I don't have tuples(python)/structs or dynamic objects (javascript)) - or function groups (like a business logic layer of some sort, which could have just as easily have been just bags of functions in modules).
I'm going to be teaching my students Classes in a couple of weeks... food for thought before then.
Facepalm.
eg complaint about nested packages. (not that I agree that this is a necessary class): instead of MuffinMail.MuffinHash.MuffinHash, type MuffinHash and have your editor add: from MuffinMail.MuffinHash import MuffinHash.
No
Ooooh, you wanted to make a case for not using classes in certain situations? Then enough with the linkbait title.
class foo:
pass
f = foo()
f.bar = "yes"
which is easier to type and more readable than: f = {}
f['bar'] = "yes"
(credit where due: learned this trick from TB) >>> x = type('Foo', (object,), {})
>>> x.bar = 1
>>> x.bar
1