75 points · by AlSweigart · 11y ago · 85 comments
However, many feel that applying OOP to software that is not for physical simulation has led to a huge amount of wasted effort over the previous decades. The problem is with code reuse. The only real form of code reuse that OOP addresses is direct object inheritance. If you want to reuse a piece of code, the way to do it is to make an object that is a 'subclass' of an object that has the code that you want to use. The actual relationship of these objects is often not that simple, and people often create baroque inheritance trees to force their logic into the OOP pattern. Worse, is that OOP is built into many languages, which leaves you no choice.
An alternate pattern is functional programming, where a program is modeled as a series of data transformations, instead of a universe of interacting 'objects'. To write the code, one looks at what data will go into the software, and what data will need to come out. After all, if the right data is coming out of the program at the right times, it works.
Instead of breaking code into objects, you write functions that process the data correctly, and assemble them into larger structures, often resembling pipelines. The nice thing is that a lot of these functions are very reusable across projects and within a project. Avoiding the messy mixture of code and data allows you to identify the common patterns in your code, and refactor and reuse more easily.
EDIT: Here are a couple of libraries which have really facilitated functional programming for me in node.js
http://ocw.mit.edu/courses/electrical-engineering-and-comput...
Take your physical simulations, for example. You may have a game scene with hundreds or thousands of entities. It's natural to try to model these as objects. In every frame you will then call a method on each object that applies a translation to its position. Very intuitive and simple. But unfortunately extremely inefficient for a computer to execute. You will likely pay a number of cache misses while jumping to each of your objects. And once you get there, the rest of the cache line where your coordinates are is full irrelevant stuff and therefore wasted (the other fields of your object).
For performance, you would want to have all your entities' coordinates in continuous memory one after another, and then apply a function to translate them all at once. Pretty much the opposite design from where OOP naturally leads you.
I don't think the main problem with OOP is performance, either. The problem is that it's not always the right or the most natural design approach, regardless of any performance considerations.
No, it isn't true. But neither do we perceive all of reality as a collection entities that never change but are used to create new unchanging entities by a series of idempotent mappings from domains to codomains.
But both abstractions are useful as ways to organize your thoughts, or as languages we can use to describe processes in an organized manner. Which one is more useful is often case specific - with the case covering not only the problem space but also the individual psychology of the person doing the work.
Many find that neither is so useful that they would be comfortable using it to the exclusion of the other, which is why there are so many functional languages with object-oriented features such as Caml and why so many major object-oriented languages such as C++, C# and Java have been acquiring increasingly many functional features over the past decade.
The strict hierarchy thing is more a feature of the class-oriented programming of C++ and its close relatives (an artifact of what made sense when approximating OOP in something merged into the existing syntax and type system of C) than it is inherent to OOP.
Unfortunately, the popularity of C++ and Java means that its hard to tell when people are talking about "Object Oriented" if they mean it in the general sense that existed prior to those languages which they are one of many approaches to facilitating, or if it means it in the narrow, static-class-oriented sense which evolved out of the particular approaches of those languages and their close relatives, which is something different.
1. In OOP, one object is special.
Whether it’s the object that is receiving a message or the object that gets a special designation like `this` or `self`, something is always given a special emphasis in a purely OOP design.
However, many useful algorithms take multiple inputs where none needs to be singled out in that way. Where do such algorithms live?
Trivial example: A symmetric binary operator like +.
Grown-up example: You don’t really model funds transfers by sending a `debit` message to one instance of a `BankAccount` class and a `credit` message to another instance.
2. In OOP, one object is special.
This is a generalisation of the point that zmb_ made. Usually in programming we don’t work only with single, self-contained data points. Most interesting things happen when we manipulate structured data and consider relationships between data points.
In purely OOP designs, we often see classes representing single data points, and then further classes to represent containers of that type. However, if the implementation of each data point is locked up behind the interface to a particular class, and then we have to access the points in each container through the container’s own generic interface, we are constrained in the access patterns we can use. Emphasizing individual, self-contained data points is often the wrong level of granularity for promoting either code reuse or efficient designs.
Example 1: What if we want to implement a more efficient representation of a data set that supports a different access pattern, such as the kind of continuous memory case zmb_ mentioned?
Example 2: What if we want to enforce constraints on a whole set of data, or model relationships between structured data of different types?
In each case, it may be very difficult to reuse existing algorithms that are locked up in methods on existing single-data-point classes. We might want to store the underlying data in a different format, and converting between formats just to access functionality artificially tied to a specific variation is likely to be awkward and inefficient.
If we instead build our modules as a set of fundamental data types and a set of accompanying algorithms — which could be as simple as a library of C structs/enums and functions using them — then the artificial barrier doesn’t arise. We can still present a clean interface/implementation for each module as a whole, but we aren’t forcing the implementation details to be separated just because Everything Must Be A Class.
In #2, you again just illustrate a potential poor choice of objects. In both examples for this point, the answer to the "What if" is "you create an object that modes the data set, rather than the individual data points". This is not only consistent with OOP, its fairly routine.
OOP's problem with performance is that it doesn't play nice with modern CPU's L1/L2 cache since most typical OOP implementations don't allocate objects in contiguous memory. But only a very narrow set of problem niches such as high data volume high performance simulation require packing data tightly to take advantage of L1/L2 cache. The hundreds or thousands of entities using OOP in a game won't cause a sweat. The cache problem would have an impact when there are hundreds of thousands or millions of entities and you need to process them 60 times per second.
The L1/L2 cache performance hit can exist in functional program, too. The list and it cells in LISP are not allocated contiguously. Basically any non-array data structures would not play nice with cache.
That just means to use the right data structures for the right job. For high data volume and high performance processing, use array. Whether it's used in the context of OOP is irrelevant.
Just a minor nit.
Composition is far more useful and effective means of code reuse in OOP.
The Smalltalk/Ruby/arguably Erlang form of OO does not really treat composition and inheritance as things at odds -- the way the object you're talking to has achieved its composition (where inheritance is a specialized form of composition) is basically irrelevant to you as the caller does address this, and quite well imo.
I don't see how OOP is any more applicable to games than it is to other software. In a typical business or social CRUD app you can represent things in the same way you could in an OOP game. "Hero" becomes "User", "Monster" becomes "Friend", "Inventory" becomes "Account", etc.
Otherwise I strongly agree with you. I think all software should be written in a more functional or data-oriented style. The biggest reason I'd write OOP code now is that many game designers and programmers, and most popular game engines and frameworks, prefer OOP.
Not really, or at least, not with a well designed system. Give me a system with small, composable objects. I can reuse code by creating a new object for one of the components of the system, or by writing an object that knows how to talk to a previously existing objects. Sandi Metz' POODR [1] should be required reading for anyone who is writing object oriented code.
Functional programming is also worth learning as well, and Martin Odersky's Coursera [2] shows how Scala can be used for code that is both object oriented and functional.
[1]: http://www.poodr.com
OO is beneficial to the programmer.
Functional provides benefits in performance, footprint and memory utilization.
You can solve any problem with either approach. Microprocessors don't care. I've written genetic evolver code in machine language (don't ask) as well as C, C++, Python and objective C. The OO languages make it easy for the programmer, while the Functional approach requires more thought, planning and perhaps attention to detail.
I tend to prefer The functional approach, probably because I did tons of real work using this model before OO came into my world. However, I certainly appreciate how much easier some things can be in OO. What I object to is this idea that everything today has to be an object, this is wasteful and slow.
Of course, I am biased. When you learned programming starting with machine language, then Forth and then C before touching C++ your view of how to solve problems computationally is bound to be quite different than that of someone who started life with, say, Java.
Inheritance is a form of code reuse in OOP. Composition is another one which is often preferred since it does not have the issues you mention here.
Note that just a couple of days ago this was posted on HN: http://userpage.fu-berlin.de/~ram/pub/pub_jf47ht81Ht/doc_kay... It's the definition that basically the inventor of Object Oriented Programming gave of OOP itself. One of the nice things he says is that he left out inheritance on purpose because he "didn't like it" the way it was done and wanted to "understand it better".
Regardless, I think your advice of learning other programming paradigms is great.
This is not true.
COM, Smaltalk, Eiffel, BETA, SELF, CLOS offer different OOP models than the average Java and C# programmers are aware of.
You can have code reuse via composition, delegation, sub-typing, genericity, mixins.
OOP is nothing more than modules in steroids for those of us that started with languages like Modula-2 and Turbo Pascal, doing Abstract Data Types[1][2] programming.
[1] - http://cs.utexas.edu/~wcook/papers/OOPvsADT/CookOOPvsADT90.p...
[2] - http://www.amazon.com/Data-Structures-Abstract-Types-Modula-...
What if your program has no output? The applications I write seldom has. Instead they save down stuff or send it away here and there during the lifespan of the program. When they're done they just exit without any output. FP seems to be focused on one input going through transformations ending up in one output.
(I'm not a good programmer and barely know how to do OOP, much less FP.)
What is saved and what is sent are outputs.
> FP seems to be focused on one input going through transformations ending up in one output.
That's not entirely untrue, but that one can be a set of simpler values, a processes can be values, too.
Actually, OOP breaks down for this case (simulation) too.
I feel your statement above is a little naive. You should read some Martin Fowler. Be less reactive and more informed. Find balance.
Software systems, regardless of methodology, need good experienced designers There is no silver bullet.
The major functional languages all come from academic backgrounds, and it shows. They're very principled, and a lot of thought is put into designing languages that are clean and actively encourage you to write clean code.
The major object-oriented languages, by contrast, tend to come out of non-academic environments. Their design was often compromised by pragmatic concerns (C++, Java), or by their being hobby languages being designed by folks for whom Barbara Liskov maybe isn't a household name. I don't want to hate on these languages too much - C++ and Java and Python and Ruby make the world turn, after all, and I suspect that's partially because they let you get away with so much. But they are what they are.
That is incorrect and it's misinformation about OOP. The most important mechanism for code reuse is a function or method, and it's the essential part of OOP. You put code into a function/method that can be used repeatedly. Function exists in most languages and is not the exclusive domain of functional programming.
Game development today is moving quickly towards components, composition over inheritance, and Data Driven Design techniques. Check out the myriad of posts on Entity/Component systems that have sprung up over the past 10 years. It can be harder to grasp at first but has huge wins over the traditional OOP model.
That doesn't at all mean the game industry is moving away from OOP. Classes and methods still abound and work perfectly fine. Even if you go whole-hog towards ECS, the stuff you're passing around is usually still an instance of some class and not a bare public struct.
Encapsulating data and providing higher-level methods to operate on it works really well. Polymorphism is also powerful and useful in many places. Even subclassing is a good fit for some things. But just realizing that you need to dial back on subclassing doesn't imply that the first one or two things on my list are broken.
If you are talking about very very simple games, it would perhaps not be worth the effort, but at that level basically any architecture will work.
This is fairly different from the most popular/performant ways of implementing ECS's (there are no "Systems"), but keeps a lot of the benefits (much more flexible than traditional class hierarchies, easier to develop and design content for without writing new code, etc), while avoiding a lot of the complexity which makes component systems overkill for smaller games.
You lose a bit of performance (compared to other methods of implementing component systems), but in higher level languages this will likely be faster than trying to imitate C++ patterns (I could say more about this, as I've seen some travesties, but I won't).
In some parts--like rendering--OOP is pretty terrible. Outside of that, though, it's not inherently bad.
That being said, OOP is also about managing interfaces between the different parts of your code. Adding a little more type info to your variables doesn't help you if you need to drastically change how a variable is accessed and mutated (memoized, retrieved from a service, persistence layer, etc.) while avoiding a running a giant find/replace across your entire project.
I feel like if you have a generic "context"-like notion then you can have a lot of this pass directly through. E.g. I recently changed where a Scala report gets most of its data, making it use an (async) web service rather than a database call, and I only really had to change the "top and bottom" - all the intermediate code handles any kind of context as a generic "F[_]", sometimes requiring particular typeclasses (Applicative, Comonad) depending on what it does with it.
Object oriented programming enshrines mutation.
Mutation is a good optimization when memory is expensive and fast relative to computation. Memory is now cheap and slow relative to computation. You can execute 100's to 1000's of operations in the time it takes to chase a pointer that is not cached.
However, if you're being snide, let me retort "So why does everybody in Java immediately recommend that you use the StringBuilder class instead of String?"
The same goes for the classical Car and Animal OOP examples. Yeah, that makes sense but how often do you have such entities in a real code base?
I think I've grown so much as a programmer since I started thinking more about states and less about objects.
He made a lot of good points that with game development OO makes a ton of sense. I kind of agree. OO works amazingly with game development but with application development I'm really finding the functional paradigm so much more logical.
var isMultilanguage = function(field) {
return field.multilanguage === true;
};var isNotMultilanguage = function(field) {
return field.multilanguage !== true;
};var getMultilanguageFields = function (fields) {
return _.filter(fields, isMultilanguage);
};var getNonMultilanguageFields = function (fields) {
return _.filter(fields, isNotMultilanguage);
};into this
var isMultilanguage = R.where({multilanguage: true});
var isNotMultilanguage = R.not(isMultilanguage);
var getMultilanguageFields = R.filter(isMultilanguage);
var getNonMultilanguageFields = R.filter(isNotMultilanguage);
var where = _.curry(_.rearg(_.where,1,0));
var isMultilang = where({multilanguage: true});_.filter(fields, {multilanguage: true}) _.where(fields, {multilanguage: false})
Reason being that I save these articles for later to show people who I try to teach programming and my attempts to save this page were unsuccessful.
Translation for non-D&Ders - I was so nerdy I made my own characters for my own games I was DM for with completely invented characteristics rather than rolling dice for traits like the rules say
Also, for some reason, on safari the code is in one line, while on chrome it's in multiple lines, like it should be.