Intros to object-oriented programming?
November 8, 2005 9:22 AM   Subscribe

Looking to understand object-oriented programming. Have tried & tried & tried to understand...

I've only ever done procedural programming (PHP, mainly), but to stay competitive in today's job market, it's more or less a requirement to understand OO programming, at the very least. Every book I have on PHP (some O'reilly, some from other publishers) all kinda dabble in OO programming, with most copping out with a "OO is too big for us to explain in this book, kthxbye" remark. Those that DO delve into it just leave me baffled and with a big "WTF?"-look on my face.

Am I too dumb to understand object-oriented programming?
posted by slater to Computers & Internet (35 answers total) 2 users marked this as a favorite
For me it was a process: reading a lot of books, reading a lot of code, copying a lot of code, writing very basic classes and then one day it just went click.

That's generally how I work, though. Flailing about and hoping it goes click. Sometimes it does!
posted by xmutex at 9:32 AM on November 8, 2005

You're trying to learn OOP in PHP? That won't work. Get a book on python or C++.
posted by cmonkey at 9:34 AM on November 8, 2005

It's really pretty simple. OO just attaches procedures/functions to the data types they operate on. So instead of saying, for example, UpperCase(name) (where UpperCase is a global function that works on strings) it becomes name.UpperCase() (where UpperCase is a method that is attached to Strings, and the language picks the right one because it knows name is a String). You can define your own data objects too (with their own attached methods) but that's basically the same as structs or records in other languages, except for the fact that one object can be based on another already existing one (inheritance). Those are the basic concepts -- a few other things are added on top, such as operator overloading and polymorphism, but once you know the basics you will be able to learn those pretty easily. OO is not hard, it's just a different way of organizing and modularizing code.

I'd suggest learning some Java. Bruce Eckel's well-regarded Thinking In Java book is available online for free.
posted by kindall at 9:35 AM on November 8, 2005

You might be beyond it already, but I think this Processing tutorial is a great, simple explaination at the benefits of using OOP. It shows a OOP program side by side with a procedural program and goes through step by step.
posted by miniape at 9:36 AM on November 8, 2005
posted by mhuckaba at 9:37 AM on November 8, 2005

PHP is not a good language to learn OOP in.

Python is a wonderful one to.

Heck, my first exposure to OOP was via Eiffel which was completely incomprehensible to me at the time. I feel your pain.
posted by unixrat at 9:38 AM on November 8, 2005

You probably aren't too dumb, but it is very difficult to find intros to OOP that are more extensive than:

class Square extends Rectangle
  function Square( $width )
    return Rectangle($width,$width);

The fact that PHP is your language of choice only hurts. I use PHP 4 daily in my work, and OO development can be a real pain. PHP doesn't even get procedural programming right much of the time.

Some people really love Ruby for its object model. It is certainly much more powerful than PHP because you can easily modify the interface of any class or object at runtime.

The concept you must understand is that OOP means more than subclassing—the real power of OOP comes from composition of objects. The Gang of Four book is tough, but very rewarding.
posted by ijoshua at 9:40 AM on November 8, 2005

i taught myself the basics of c++ in a couple weeks using c++ for dummies. it's actually pretty good and gives you a good feel for the basics of OO. after you have some experience i recomend Effective C++ by Scott Meyers to really nail down some good habits.

that's if you decide to go c++ that is. I can't speak for other languanges, but it's probably essential that you find a good OO language to learn rather than just trying to figure out the "concepts" of OO programming seperate from a specific language.
posted by jacobsee at 9:55 AM on November 8, 2005

I struggled with this as well and as someone who started in PHP, I'll echo the suggestion that PHP is not the easiest language to learn OOP in. Maybe PHP5 is different, but learning a "more" OOP language would probably help. It really does just "click" one day (or it did for me anyway).

The one concept that helped me was thinking of an object as an abstract data type-- that I could create my own objects in a language that would work just like the native string, int, array, etc objects and could contain all the methods and properties the thing ought to have.
posted by yerfatma at 9:58 AM on November 8, 2005

Response by poster: kindall: Everything following "It's really pretty simple." kinda made my eyes glaze over :-/

And from what I read here is that PHP might NOT be the best choice of language... thanks for the answers so far. I suppose Ruby, apart from being the de rigeur language, would seem a better choice...
posted by slater at 10:02 AM on November 8, 2005

Read a lot of actual OOP-based code until it sinks in. Many of the theoretical explanations of OOP out there are pretty lame. I do second the recommendation for Eckel's Thinking in Java, but be aware that you may need to take your time and read it slowly, giving yourself the time to understand each section.

One thing that helped me was the experience of playing with Visual Basic. Even though VB 6 was not a true OO language in itself, there was OO stuff that went into its creation. When you realize that each of the widgets (button, textfield, etc) that you can use is a pre-built object, with properties and methods, then you get some idea of how you might want to build your own objects.
posted by tdismukes at 10:06 AM on November 8, 2005

PHP5 + Schlossnagle's Advanced PHP Programming will get you OO in PHP.

Python, Ruby, C++ would probably be better choices, but if you're familiar with PHP...
posted by togdon at 10:11 AM on November 8, 2005

Here's the total beginner's primer to objects:
  • Objects are a collection of data, and functions to act upon that collection of data.
  • An object's data are called attributes or properties.
  • An object's functions are called methods.
  • By keeping the attributes and methods together in a single place, we have "encapsulated" them. Everything you need will be in one single package.
  • Objects are created and initialized (you'll hear the 25 cent word "instantiated") from a template. In PHP, these templates are called Classes.
  • Templates can incorporate other templates in their design. This idea is called inheritance and it allows programmers to build upon existing code, saving time typing and debugging.
Different programming languages will implement variations on these themes, but these are the core ideas: Attributes, methods, encapsulation, instantiation and inheritance.
And I'll echo the suggestion that PHP is not the gentlest introduction to OOP either.
posted by boo_radley at 10:16 AM on November 8, 2005

You are certainly not too stupid to learn it. PARC concieved of it to teach to children!

If you're working in PHP to any extent I'd suggest you use Rails as a way to learn OOP. Ruby supports it (and in a not-stupid and consistent way, unlike Java with its non-object integer type foolishness) and Rails is fun.

Additionally you'll probably take away from it some appreciation of worthwhile but underused techniques like templates that will work in PHP as well.
posted by phearlez at 10:16 AM on November 8, 2005

> Objects are a collection of data, and functions to act upon that collection of data.

That's close, but I think it's better to say somthing like, objects are composed of other objects. Some objects simply encapsulate data, but the purpose of OOP goes far beyond that.

Look at the arguments of your object's methods. If most of the arguments are references to objects, rather than simple scalar values (e.g. integers or strings,) then you are composing object interactions. Otherwise, you're simply building a hierarchy of classes.
posted by ijoshua at 10:25 AM on November 8, 2005

Simple example:

MyName.text = "lordsludge"
MyName.length = 9
MyName.uppercase = "LORDSLUDGE"

MyName is an object. It has 3 properties: text, length, and uppercase.

Once you "get" this, go back and read the other replies, as they will make sense now
posted by LordSludge at 10:27 AM on November 8, 2005

My first exposure to objects was in Perl. I didn't get it. Then I learned Java and it all made sense, and I've had no problems understanding OO principles in languages like Python and Ruby too.

I still don't get OO in Perl. I imagine PHP has many of the same issues.
posted by nev at 10:34 AM on November 8, 2005

I'm glad slater asked this question, and am hoping to tag along:

As someone who'd really like to learn more about programming (I'm a designer, not a programmer) what's the best way to start out? Is Ruby a good place to begin?

See, the problem I face is that nearly every programming book I've picked up assumes a familiarity with some *other* programming language. How does one start from scratch?

More importantly, how does one with a penchant for doing interesting things on the web start form scratch on a Mac running OS X?
posted by aladfar at 10:50 AM on November 8, 2005

If you want to start from scratch, or even if you want an entertaining read, Why's (Poignant) Guide to Ruby is very good.
posted by ijoshua at 11:40 AM on November 8, 2005

Best answer: A few people in this thread have said that understanding OOP is easy. I disagree. I think it's hard.

Oh sure, picking up some new terminology ('classes', 'objects') and some new syntax ( ) is pretty straightforward. But if that's all that you do, I guarantee that you'll be left saying, "So what?"

So you go and try designing some classes of your own. You write some dummy programs that have objects. You use some of that funky dot notation. Great! You're an OO programmer!

No, you're not. And I bet deep down you're still thinking, "So what?", aren't you?

Here's the thing. Becoming an OO programmer isn't just about learning some new syntax, and it's not just about shoehorning your subroutines into objects. It's about learning to think in objects.

This is a big thing. Seriously. If anyone tells you it's easy to go from being a good procedural programmer to being a good OO programmer, then I'm sorry, but they don't really understand OO themselves.

I'm kind of ashamed to admit it, but my original 'a-ha' moments came when I had to write a bunch of code in Excel using Visual Basic for Applications. It's not a fantastic environment by any means, but the Basic syntax is familiar enough not to be a stumbling block, and you have a big collection of objects to play with (Ranges, Fonts, Charts, etc.) that are actually reasonably well documented.

I believe that the best way to start is by using some objects that other people have written.

Once you've been thrown into a rich, well-designed object hierarchy, and forced to use it, you'll have a whole bunch of 'a-ha' and 'that's neat' moments. More importantly, you'll pick up some of the patterns of how objects are used in the real world.

You really need to experience it to see the benefit of it -- I don't know why, but written explanations of OO always make the whole thing seem completely underwhelming and pointless.

Writing your own little dummy classes and programs is fine for learning the syntax, but you won't learn good OOP. Again, you'll probably just get a lot of "What's the point?" thoughts.

I know it's not as trendy as Python or Ruby, and I'm probably going to get laughed out of the room for suggesting this, but I think you could do worse things than doodle around in Excel VBA for a bit. Just to see some objects in action. That might be the experience you need to get your head around this.
posted by chrismear at 12:16 PM on November 8, 2005 [1 favorite]

Best answer: Most OO tutorials show you how you make and use objects in a given language and continue to leave you baffled as to why. Not getting it isn't surprising.

OO is a different paradigm. Thinking in OO is different from thinking in a procedural language ( different from thinking in a functional language, etc.)

In a procedural language, you have pieces of code that pass data structures to each other to get things done. In OO, you have objects pass messages to each other to get things done.

It sounds like a meaningless semantic difference given that objects are just encapsulated data structures with some associated code, and the messages they send are themselves objects (or data in less than fully OO languages like Perl, PHP, or, yes, Java.) But getting that there really was a difference was at the heart of my finally getting OO.

You'll have a harder time getting this in PHP (or Perl) than Python or Ruby. I never got this in Perl, which doesn't support OO so much as offer a means to roll your own OO system (which'll never work as smoothly as true OO languages'.) (I say all this as someone who loves Perl.) I finally got it working with Python. (I say all this as someone who finds Python annoying.)

But if you're a designer who wants to learn how to program, don't worry about getting OO down as your first task. Start with the basics. (And if you don't start with the basics, make sure you fill them in at some point -- you'll need them.) Python's a decent choice to learn with. I only just started playing with Ruby and I'm lovin' it, but it still has too much new-car-smell for me to be objective about it, and, certainly, more tutorials have been written about Python.

For Python, check these links. Read How to Think Like a Computer Scientist, a programming tutorial for Python.

If you pick Ruby, check these links, and see if Why's (poignant) Guide to Ruby is your style.

Either way, read A Little Ruby, a Lot of Objects -- it's the best beginner-level tutorial on actually thinking in OO I know (and though it uses Ruby for its examples, it's more about OO than Ruby.)

But if you really want to learn programming rather than how to cobble together a script, don't stop with one language or one paradigm. Keep learning.
posted by Zed_Lopez at 12:22 PM on November 8, 2005

Response by poster: thank you chrismear, that's PRECISELY what i've been thinking ("so what?"). Except I don't Excel available, I fully agree with what you said.

Zed: Thanks for those links. For some reason, Java just rubs me the wrong way, so I'll check out the Ruby links first.
posted by slater at 12:27 PM on November 8, 2005

It absolutely just clicks one day, after intense study and frustration. As a freshman in CS15, I went from C to A overnight. (This was 10 years ago, and we were using Pascal, so YMMV.)
posted by Saucy Intruder at 12:42 PM on November 8, 2005

Best answer: You didn't mention having any experience in the C programming language, so this probably won't be directly applicable to you, but I'm gonna post it anyway because it might help someone else later on.

If you have access to a Mac running Mac OS X, the Cocoa frameworks are amazingly elegant and the development tools to work with them come free with every copy of Mac OS X. Even if you don't have a Mac, Objective-C, the language underneath Cocoa, is supported by GCC (the GNU Compiler Collection) which comes with pretty much any Linux distribution and is fairly easily gotten for Windows.

To me, Objective-C is one of the nicest languages to learn OO in because it's just so small and simple, so you're left just focusing on what's really going on: objects sending messages to other objects, with the receiving objects doing something as a result of receiving that message.

Apple has a free online book, The Objective-C Programming Language (PDF), that covers the basic ideas of OO and associated concepts like the Model-View-Controller (MVC) pattern in a professional and fairly jargon-free way.
posted by BaxterG4 at 12:51 PM on November 8, 2005

Response by poster: Thanx BaxterG4, i'm mac-based so that's certainly interesting.
posted by slater at 1:55 PM on November 8, 2005

I'm going to echo a few other sentiments here, that if you are a designer, working with a very slick IDE creating GUIs that DO stuff might be your best bet. That is, click a button, something happens. Change what happens.

I hear they are giving away Visual Studio for free now.

That's for understanding programming in general, and OO in a small way.

(Also keep in mind that I can't write a regex properly, so, YMMV)
posted by eurasian at 2:06 PM on November 8, 2005

I think the "so what" factor about OO is particularly significant for people who are just writing scripts on their own, which are stand-alone scripts.

Perhaps it's axiomatic that if your code doesn't get used more than once, and you code all by yourself, you don't really need it?

But the moment you start working with other people, and the moment you need to re-use code, it starts to make sense.

I use OO programming all the time, in Perl (no comment, Zed_Lopez) but I don't even think of it as OO most of the time, because I'm using other people's code, in modules which just happen to have OO interfaces.

I write

use HTML::Template;
my $template=HTML::Template->new(filename=>'foo.tmpl');
$template->param(list => \$list);
print $template->output();

and I'm not thinking "wow, I've instantiated an object", I'm thinking "how cool is the guy who wrote HTML::Template and what would I do without it?"!

HTML::Template is grabbing my $list, merging it with the layout in 'foo.tmpl', and outputting a web page for me. I don't have to know how it works. I just use it.

And if the author comes across a newer, smarter, faster way to do what it does, he can release the new code, which will work exactly the same as far as I'm concerned, but faster. I still don't need to know how it works.

Here's another object using some external code:

use DBI;
my $KEY = 'foobarbaz';
my $dbh =
DBI->connect( "dbi:Google:", $KEY, undef, { debug => 0 } )
|| die "$dbh->errstr";
my $sth = $dbh->prepare(
SELECT url,title,summary FROM google WHERE q = "askmefi"
LIMIT 0,100

$sth->execute() || die "$dbh->errstr";
while ( my $r = $sth->fetchrow_hashref ) {
print "$r->{'title'}\n$r->{'url'}\n$r->{'summary'}\n\n";

That's searching Google, as if it were an SQL database. How does the DBI::Google module work? I don't know. How does Google work? I'm not allowed to know, it's a trade secret. But who cares, I've got an object which talks to Google. Sweet.
posted by AmbroseChapel at 2:35 PM on November 8, 2005

Read a little book called "The Object Oriented Thought Process." Bruce Eckel's Thinking in Java book is good too, and I believe available for free on the web.
posted by matildaben at 3:13 PM on November 8, 2005

Is it really more or less a requirement to understand OO programming to stay competitive in today's job market?
posted by jasondigitized at 3:30 PM on November 8, 2005

Oh, my, yes.
posted by kindall at 3:48 PM on November 8, 2005

This confusion you're feeling about object-oriented programming? It's because they don't give away HyperCard with Macs anymore. :(
posted by kindall at 3:48 PM on November 8, 2005

We have Automator!

posted by chrismear at 4:39 PM on November 8, 2005

I used OO programming in Perl all the time through other people's modules, too, AmbroseChapel. Didn't help me understand how to design an OOP system.

I'm not saying you can't do good OO programming in Perl. I'm saying that Perl's native support is lame. If you try doing OOP in Perl in the obvious, naive way that's recommended in multiple naive tutorials, you get objects that can't be subclassed safely. You can work around this, or use one of the solutions to the problem on the CPAN, but all that requires thought and effort you don't have to go to in other languages. And you'll still never get some of the OOP benefits Python and Ruby (for two) offer through having everything be an object. As such, I don't think it's a language to seek out if your goal is to understand OOP. (If one were already well-versed in Perl and wanted to learn OOP, my advice would be different.)

I ♥ Perl, but I'm not blind to its flaws.
posted by Zed_Lopez at 5:25 PM on November 8, 2005

chrismear is exactly correct that *designing* proper class structures and inheritance is really hard. When you are starting out you tend to make a ton of mistakes.

It's interesting that ijoshua chose the square-rectangle example. That is one that looks trivial at first and appears to be straightforward but really isn't. The key point to grok is that when a "bar" is derived from a "foo", what this means is that a "bar" is a "foo" of a particular kind. You should be able to correctly refer to both of them as "foo"s.

In the case of saying that a square is derived from a rectangle, then what you really are saying is that a sqaure is a rectangle of a certain kind. In the mathematical sense this is precisely true. However, when designing a class it is not always true. Suppose you have a rectangle class, and one of its methods is "setsize(w, h)" which takes a width and a height. Since this is a rectangle we need to be able to specify both of these dimensions.

So then we derive class "square" from class "rectangle". Again this means that we should be able to treat any "square" as a "rectangle" of a particular kind. In concrete terms this means that any object of this new class "square" must inherit all the interfaces from "rectangle." If it did not, then we could not refer to it as a rectangle, because it can no longer be used interchangably in any situation where a rectangle object would be used.

And here lies the problem. This means that our new "square" class has to have this "setsize(w, h)" method. But for a square, this makes no sense because you cannot set both the width and the height of a square to different values. But the square class HAS to implement this method, because all squares are rectangles, and rectangles have an interface "setsize(w, h)". So you either have to make up some hackish rule like, "w is used for the size of the square and h is ignored" or you check that w always equals h and abort if they are not the same. But from the standpoint of the user of this class, that is awful. It means that now I have to code something like "Square blah; blah.setsize(10, 10);". Not only is this tedious to have to repeat the parameter twice, it looks funny, it's confusing, and it's just bad OO design. You really should not derive "class square" from "class rectangle" if you intend to have a "setsize(x,y)" method.

Why did I mention all this? Because the "square derives from rectangle" textbook example looks tantalizingly logical, and it is on a mathematical level in that a square really is a special case of a rectangle. But in terms of OO design, it doesn't work -- and this is why it takes a long time to really learn how to design classes and inheritance structure that works well.

(You can read a much more expanded version of this in section 21 of the most excellent c++ faq lite.)
posted by Rhomboid at 5:37 PM on November 8, 2005 [1 favorite]

While I agree with Zed that Perl's OOP structure isn't necessarily the most rigidly structured, it does very much offer a really simple glimpse at what happens under the hood in object programming:

my ($self) = bless {}, $class;

In looking at $self, you'll see that it has the class bolted on to the reference, which is pretty much what you'd expect from the constructor. Its some storage and a knowledge of where calls made to the functions go. Functional OOP in a sentence.

Further, calls from the object into the class are similarly rudimentary to deconstruct:

my $foo = Bar->new;

package Bar;
sub this {
 my($self) = @_;
So you mean all this object nonsense is just me schlepping around someone else's data for them? Sort of, yes.

At least half of my conceptual problems with learning OOP was not so much in reusable design but with how and why the damned thing worked in the first point.

Good OOP design, inheritance and so forth is somewhat more difficult than in normal design, but thinking re-use anywhere doesn't exactly come freely.
posted by Ogre Lawless at 10:50 AM on November 10, 2005

« Older Gen Y and new narratives   |   Studio Ghilbi Newer »
This thread is closed to new comments.