Linked by John Collins on Wed 21st Apr 2004 06:42 UTC
General Development The purpose of this article is to give a novice programmer the basic idea of what OOP is, as implemented using PHP. Readers should have a basic knowledge of programming ie what variables are, variable types, basic methods of writing comments, and how to enter code into a text editor.
Order by: Score:
Public/private/protected
by Anonymous on Wed 21st Apr 2004 06:47 UTC

Does PHP 4 or 5 support classifying variables as private, or any other type of restriction to enforce encapsulation/abstraction?

php5 does private/public/protected
by shie erlich on Wed 21st Apr 2004 07:00 UTC

well, php5 ;-)

Re: Public/private/protected
by bsdrocks on Wed 21st Apr 2004 07:06 UTC

Yes and no.. PHP4 doesn't has them, but PHP5 has them. You should read the great article about PHP5 at http://www.sitepoint.com/article/coming-soon-webserver-near/ . In the five page, there have about public, private and protected.

Anyway, I usually like to do this:

$statement = "{$this->$Name} rides bus number {$busNumber}";

instead this:

$statement = $this->$Name . " rides bus number " . $busNumber;

RE: Re: Public/private/protected
by Anonymous on Wed 21st Apr 2004 07:25 UTC

Thanks. What is the significance of enclosing a variable with brackets?

Learn OO First
by Traal on Wed 21st Apr 2004 07:26 UTC

It might be an advantage to learn an OO programming language before any other, at least if your main interest is in writing applications (as opposed to libraries, where procedural languages hold the advantage). I know some good C programmers who can't quite get into the OO mentality, because they've already learned one way of doing things which is "good enough" for them.

A similar situation occurs in learning to type. If you started out with the "hunt and peck" method (like I did), it's really difficult to switch to touch typing. Especially if you can hunt and peck at a "good enough" speed. So inertia can be your enemy.

RE: Re: Public/private/protected
by Gusto on Wed 21st Apr 2004 08:00 UTC

"happy {$hippos}!" is the same as "happy " . $hippos . "!" in PHP.

Also, variables "should always" (at least it's a standard) be written in lowercase, such as $name and $genderLevel instead of $Name and $GenderLevel.

Object Overloading
by Daniel van Eeden on Wed 21st Apr 2004 08:05 UTC

OOP programming with PHP is nice...but PHP isn't fully OOP. Some OOP features like Object Overloading are missing. (altrough some dirty hacks exist). Using OOP can improve security (especially with PHP5) if it's done the right way.

PHP4 Object orientation
by Bryan Feeney on Wed 21st Apr 2004 10:08 UTC

It's also important to realise that PHP4 uses value-semantics (as opposed to the more usual reference semantics) for objects. Thus if you say

$bill = new Student("Bill", "Male");
$william = $bill;

three objects will be created. The new command creates an object, and then a copy of this is placed in the variable $bill. On the second line another object is created (a copy of the one in $bill) and is placed in $william.

Thus for the following

$bill = new Student("Bill", "Male");
$william = $bill;
$bill->name = "Bill Gates";
echo $bill->name . "n";
echo $william->name . "n";

You would get


Bill Gates
Bill


This becomes even more of an issue in functions. As a result most PHP programmers explicity pass by reference.

The following code passes by reference

$bill =& new Student("Bill", "Male");
$william =& $bill;
$bill->name = "Bill Gates";
echo $bill->name . "n";
echo $william->name . "n";


and the output is

Bill Gates
Bill Gates


In PHP5 objects will use reference semantics only, and there will be no need for hundreds of & symbols in your code.

oop
by Anonymous on Wed 21st Apr 2004 10:19 UTC

One of the main featurs in OOP, is the concept of a class as a blackbox. One should not know what is inside the class, or how it is implemented. Thus instead of accessing the data directly trough $person->name it would be much cleaner to have getter/setter for that variable, fe: getName() { return this->name; } and setName($name) { if isValid($name) this->name = $name; else raiseError("invalid name"); }

v RE: oop
by Horse on Wed 21st Apr 2004 11:15 UTC
for an introduction to OOP, PHP is not the best option
by tech_user on Wed 21st Apr 2004 11:39 UTC


for an introduction to OOP, PHP is not the best option. a beginner (like myself) is confused by the web-related side of it.

what has <? got to do with OOP?

pyhton would be a much better introction to OOP, or even programming in general.

RE: @horse
by nick on Wed 21st Apr 2004 11:54 UTC

So your saying that just because Java does it this its bad and you should flame the person? Even if this practice JUST MAY be a better way to do it?

Maybe you don't need explicit get/set methods but the original post was right. When programming to a class you shouldn't need to know/care about how that class does it stuff.

By the way you shot back at him I'm guessing you leave all your variables as public globals so anyone get at them?

Also, why would "Java mentors" think multiple inheritance is evil? Care to explain?

PHP is not a good choice
by Bob on Wed 21st Apr 2004 12:23 UTC

I agree that introducing the web aspects on top of learning OO is a bad idea. You need to learn a more general scripting language like Python or Ruby that you can install and learn right away.

RE: PHP is not a good choice
by Tarmo hyvärinen on Wed 21st Apr 2004 12:48 UTC

PHP is a good choice, it's easy to learn with clear syntax.

You really don't need to create web-based application with PHP, you can do console, even GUI applications. I've written several phpgtk apps with php/gtk and especially looking forwards php5+gtk 2.0 support.

Developing Script languages is much faster than compiling c++ for example, which makes it especially good for learning.

I write PHP as my work and I can tell you, PHP has really nice OO features and makes possible to develop OO code very fast. Of course, lots to improve, but PHP5 with Zend engine 2.0 brings really good OO capabilities.

You're referring to Python. Do you even know Python syntax or have even coded in python? Python syntax, in my opinion, is very ugly. Horrible ugly. PHP syntax is quite near C++ and Java, which makes learning them easy in the future.

Just my opinion.

Re: oop
by rycamor on Wed 21st Apr 2004 12:57 UTC

The whole "getter" and "setter" thing is not necessarily the only way to go. For example, C# has the concept of Accessors, which makes it "seem" like you are accessing properties directly, but in fact every request of a property gets passed through the method(s) of your choice anyway.

Think of it like having triggers and constraints in an SQL database. Even though the query is simply getting or setting a database value, the system intercepts that query and performs additional or substitutional logic.

Fortunately, PHP allows for this with the Overload extension (http://php.net/overload), which is available in PHP4 and PHP5.

Great article for people like me
by Big Al on Wed 21st Apr 2004 13:06 UTC

I want to commend the author for this article. I've done lots of work with PHP but never using object-oriented methods. I've been learning C++ but the concept is sometimes overwhelming until you're used to it.

This tutorial offers a good way to start using objects in something I'm already comfortable in, namely PHP. True, PHP might not be 100% OO but it makes a great stepping stone to learning to do it in other languages.

Thanks for a great article, John!

@ bsdrocks, Gusto
by Anonymous on Wed 21st Apr 2004 13:14 UTC

When using variable interpolation in PHP (which occurs automatically with double quoted strings but not with single), the braces act to disambiguate variables from the surrounding text.

Example:
$foo = 'spam'
$bar = '$foo to you'
$wrongbaz = "$foos to you"
$baz = "{$foo}s to you"
echo $foo, $bar, $wrongbaz, $baz

Should print:
spam
$foo to you
$foos to you
spams to you

Notice that it's impossible to tell whether you mean to look up the variable $foos or whether you're trying to add an 's' onto variable $foo, hence the need for braces.

@tarmo
by Anonymous on Wed 21st Apr 2004 13:31 UTC

You're referring to Python. Do you even know Python syntax or have even coded in python? Python syntax, in my opinion, is very ugly. Horrible ugly. PHP syntax is quite near C++ and Java, which makes learning them easy in the future.

Just my opinion.


I code in Python as my primary language. Having coded in all the languages you list (PHP, C++, Java), I find Python's syntax to be the best. The lack of extra control characters like braces, semicolons, and dollar signs make the code easier to type and read. I can skim other people's code without getting worked up about brace placement and whatnot since the compiler-enforces one coding style.

I find PHP, along with perl, to be one of the uglier languages, the $variable convention irks me for some reason. It does allow you to get a lot of web programming done, though, and that's why I use it.

Just a counter opinion. ;]

Re: @tarmo
by rycamor on Wed 21st Apr 2004 13:57 UTC

I don't have any particular antipathy towards Python, but I have to say, I personally really like the '$' prepended on variable names, and I think PHP's nice simple way of dealing with that is much nicer than Perl, Bash, or TCL, for example, where there are ungainly additional rules as to what prepends a variable. It makes it easy to tell at a glance what is a variable in your code.

That, combined with 1) the ease of variable interpolation in strings via {$varname_or_expression}, 2) the concept of variable variable names, as in $$varname, and 3) even the concept of variable (conditional) function execution via $function_name() all combine to create some powerful scripting features.

python's syntax is one of its main design goals
by tech_user on Wed 21st Apr 2004 14:04 UTC

python' syntax is agonised over.. it is one of its best design goals. and python's inheritence (if you'll excuse the pun) is in languages designed to teaching to younger minds...

A Poor choice
by Sphinx on Wed 21st Apr 2004 14:24 UTC

About the only thing OOP and PHP share is the letter P. Ruby would have been a far better choice to learn OOP from.

Don't start with PHP
by Anonymous on Wed 21st Apr 2004 14:37 UTC

I agree with everyone else's assertion that PHP isn't a good place to start learning OOP. I learned OOP at the university level and they started us off with Java. I still think that is the best place to start because it is syntactically very similar to C. Ruby and Python are good examples of OOP languages, but they both have non-traditional syntax.

Unless you yourself sit down and right an equivalent, easily read, easy to comprehend little tutorial in language X. If Ruby, Java, Python, D, whatever, is better for doing what the author attempted to do- go ahead and contribute.

If you wish to discuss the pro's and con's of the various languages and their differences- please do so by all means, particularly if your post actually provides insight into non-obvious things for those who don't already know the language in question-otherwise you are just playing ego-games....



(kudos @ rycamor and @Anonymous (IP: ---.res.gatech.edu) and @ Bryan Feeney )


Errors in Article
by Xavier on Wed 21st Apr 2004 14:58 UTC

If you declare a property in your class such as var $Gender; then you must access it through $this->Gender or $object->Gender, not $this->$Gender or $object->$Gender
If $Gender is a local variable and has a value, (say, "name"), accessing $this->$Gender will effectively access $this->name.

Say for example I do this:

class Student {
var $gender;
var $name;

function blah() {
$Gender = "name";
$this->$Gender = "Male";
echo "Gender: " . $this->$Gender; // Will print "Male" indeed.
}

}

$s =& new Student;
$s->blah(); // will print "Male"
echo $s->gender; // Will not print anything
echo $s->$Gender; // Will not print anything
echo $s->Name; // Will print "Male";

The lesson here is that you should never use the dollar sign to refer to an object's property. Whether it is to set it, or to retrieve it.

The article uses them for every single property and this is not the proper way to refer to instance variables at all.

The proper way would be as follow:

class Student {
var $gender;
var $name;

function blah() {The article
$this->name = "Blah!";
$this->gender = "Male";
echo "Gender: " . $this->gender; // Will print "Male"
}
}

$s =& new Student;
$s->blah(); // Will print "Gender: Male";
echo $s->gender; // Will print "Male";
echo $s->name; // Will print "Blah!";

This process is also highlighted all over the place in the php documentation.

I think an errata is required here.

v Please start proof-reading articles.
by feti on Wed 21st Apr 2004 15:05 UTC
re: Don't start with PHP
by PainKilleR on Wed 21st Apr 2004 15:08 UTC

I learned OOP at the university level and they started us off with Java. I still think that is the best place to start because it is syntactically very similar to C. Ruby and Python are good examples of OOP languages, but they both have non-traditional syntax.

If your primary reason is syntactic similarity to C, then you should be telling people to start learning OOP with C++, considering that it began as a superset of C, and that C programming is still completely possible with many C++ compilers.

The problem many people have when moving from C to Java or C++ is breaking the mindset that programming in C often brings with it. This is why learning OOP is often better done in a language with a non-C-like syntax to get the ideas firmly rooted in the mind of the programmer, and then let them learn the OOP syntax of C++ or Java, where they can return to familiar coding styles with the OOP ideas fresh in their minds.

Sticking with one familiar syntax for every piece of code you ever write doesn't really help you in the long term. Over the last 5 years I've had to learn 4 programming languages, 2 of which had C-like syntax, and 1 of which was similar enough to a C-like syntax to get by. In the end, I found the 1 language that did not use C-like syntax was what got the job done for 3 of those 5 years, and in the last 2 years I've had to use a blend of C, C++, and C# to get what I needed. I certainly prefer these languages, probably because C was the first language I learned (8 years ago), but I often find myself looking to other languages to learn new concepts, even if they're available in one of these C-based languages, simply because it's easier for me to pick things up at the conceptual level when I'm not trying to use familiar syntactic elements in new ways.

i use it
by wayne on Wed 21st Apr 2004 15:56 UTC

I have written a few classes in php, and for me they've been a useful way to have a collection of related functions share variables between each other. But, I don't know enough about OOP to fully grasp all the objections that I always hear raised when php & OOP are mentioned together.

looks good to me
by chris on Wed 21st Apr 2004 16:09 UTC

I think we could spend all day arguing about what language would be best to teach OOP, but then we'd be missing the author's intent. I was taught OOP @ University using Java as well, but never could quite grasp the general model of OOP. I think this article does a pretty good job of demonstrating OOP basics, even if some mistakes were made in the exact implmentation/demonstration of it.

A java tutorial might have been best, at least then visibility modifiers would have been included for variables, but as a PHP developer as well, I can certainly see the "Simplicity" benefits of using PHP.

Python, OOP and Syntax vs. Semantics
by Luke McCarthy on Wed 21st Apr 2004 16:10 UTC

Python, one of the saner languages I have come across. I find I can do a lot of work in Python very quickly, although the efficiency of such results means the quality can only ever be prototype-level. For brainstorming, scripting and testing ideas, Python is unmatched. I hope that bringing Python to the .NET CLR will make it more efficient (compiled to native code at load/run time) and therefore more useful. Python has the potential for fully-blown web and GUI applications.

Personally, I hate syntax, it is a foolish distraction that brings intelligent people to a level of religious blindness. The truth is, semantics is all that is important in a language. Python takes a decent compromise of cut-down syntax, but enough to make code easier to comprehend.

OOP sucks but Python does it well ;-) It should be great for teaching OOP, I imagine.

what about...
by V. Jenks on Wed 21st Apr 2004 16:26 UTC

PHP is nearly worthless as an OO language as it really isn't OO, it pretends to be by offering a class structure with very simple inheritence.

PHP is not strongly typed and it is interpereted, therefore it is probably one of the worst choices to explain OOP.

What about design patterns? What about building real-world business objects and mechanisms to deliver them to your presentation layer (i.e. facades, visitors, etc.)

PHP teaches you poor OOP practices by munging your programming logic into your presentation layer, otherwise known as spaghetti code.

For *real* OOP learning, turn to ASP.NET or Java, where you have strongly typed languages, interfaces, full inheritance, and tons of other constructs (class libraries, stateful objects, etc.) in order to learn OOP to its fullest.

RE: what about...
by chris on Wed 21st Apr 2004 16:45 UTC

I concur whole-heartedly, that another language could have been used. I think for the purposes of introducing OOP to a beginner however, PHP's basic OOP implementations are more than sufficient. PHP's OOP model is loosely based off of Java (I think, certainly looks that way).

I've read countless articles saying "You should learn in <insert language>." To reiterate, the spirit of the article is to teach basic concepts, not to teach a language. In that regard at least, the author did a decent job, I think.

Re: what about
by rycamor on Wed 21st Apr 2004 16:48 UTC

Bah... whether a language is strongly typed or interpreted has nothing to do with whether it is OO. That is like complaining that Perl isn't compiled, so it is not procedural like C. In fact, there is no clear formal set of rules as to what exactly defines an OO language. This even goes down to such things as prototypes vs. classes, function nesting, etc...

Of course, no one in his/her right mind would argue that PHP4 is a very complete OO language, but PHP5 actually offer almost all of the things you refer to, including the ability to restrict automatic type conversion. (http://zend.com/php5/articles/engine2-php5-changes.php)

What you are really talking about is not OO, but general language design goals. PHP is designed as a scripting language. Scripting languages in general are weakly typed, and allow for such interesting things as dynamic evaluation, etc... In fact, there are some very logical arguments FOR weak typing in scripting languages, as argued by the creator of TCL. PHP is not meant to be the language for serious "business objects" (Personally, I'll keep my business logic in the database, for the most part, but PHP can easily interact with many "heavier" systems where an enterprise might keep its core business logic)

PHP doesn't "teach" you to combine logic and presentation. It leaves the choice up to you. With PHP, I haven't munged business and presentation together in years.

Sorry for the rant, but I'm tired of hearing all the same tired old arguments.

Constructive Criticism
by Anonymous on Wed 21st Apr 2004 16:53 UTC

Unless you yourself sit down and right an equivalent, easily read, easy to comprehend little tutorial in language X. If Ruby, Java, Python, D, whatever, is better for doing what the author attempted to do- go ahead and contribute.

Whoa! Take a deep breath and calm yourself. It's just a sharing of ideas. It's good to write a beginner tutorial about OOP, but the criticism of using PHP as an example is certainly valid. It does lack many of the structures that are fundamental parts of OOP. Furthermore, it's a web-based scripting language.

But on a different note, I must say that I love the fact that PHP is object-oriented. Especially the new features that are being implemented in PHP 5. With web-apps becoming more complex, it is a major advancement to offer a server-side scripting language that bears a greater resemblance to true OOP languages.

Re: Constructive Criticism
by rycamor on Wed 21st Apr 2004 17:08 UTC

While its true that PHP was originally created with the sole purpose of being a web-based scripting language, I would argue that over the past 2 years it has pretty much graduated to general scripting language. Especially for Unix systems, it includes all kinds of capabilities for systems-level interaction: sockets, streams, process control, expect, readline, FAM, direct I/O, shell redirection, and a long list of other shiny toys ;-).

For example, I have just finished a project on FreeBSD using PHP in daemon mode, as a socket server for messaging, and it has been rock-stable. Nothing at all web-based about this project.

And, all of these abilities will be even better integrated in PHP5. I am really looking forward to it.

Maybe I'm clueless...
by Adam Scheinberg on Wed 21st Apr 2004 17:14 UTC

but 99% of the time, I don't get why OOP is better than plain old procedural functions in PHP.

How is this any easier? Is anything "more reuseable?" It seems like classes are just way more typing than regular non-OOP functions.

The title of the article should be:
by Brian Zhou on Wed 21st Apr 2004 17:39 UTC

"A PHP Beginner's Crash Course into Object Oriented Programming, part 1 of n"

There isn't a concensus on what OOP is about, but generally encapsulation is only the tip of it. IMHO polymorphism is the key to OOP, without which OOP does not have significant advantage over procedural programming.

And Python is a much better first OOP language to learn. Depends on your background or interest, you can also learn Squeak Smalltalk or Objective-C.

RE: Maybe I'm Clueless
by Lumbergh on Wed 21st Apr 2004 17:49 UTC

You're not clueless. I've never done PHP, but I've done a lot of C++ and quite a bit of C#....a little Java. OOP has it's uses but it's been oversold - especially it's reusability in comparison to procedural code.

In reality not everything has to be in a class, but could just as easily be a standalone function in a particular namespace to avoid namespace collisions. I like how c# v2.0 will introduce static classes so you don't have to prefix all your variables and functions with static in the class, but I still don't see why you can't have a standalone function in a particular namespace. Maybe it's a compiler issue. I don't know

Re: RE: Maybe I'm Clueless
by rycamor on Wed 21st Apr 2004 18:40 UTC

I tend to agree that OOP has been oversold, especially for the past decade. However, the pragmatic in me finds many uses for it. In fact, I would argue directly in opposition to Traal's post at the beginning of the thread. I think libraries are the most natural place to use OOP. (of course, we might mean different things by the term 'library')

For example, in PHP, HTML templates fill a very useful problem space. They don't solve all problems of logic/presentation interaction, but they are quite useful. Keeping your template logic inside a class makes it easier for templates to be widely deployed, even by people who have no idea what is going on inside the template code:
---------

require_once(templateClass.php);

$mypage &= new templateClass('/path/to/template.html');

//.. whatever complex logic I use to arrive at a value for $variable

$mypage->assignVar('MARKER', $variable);

$mypage->render();

---------

Now, if I had to do the same thing without OO, it would have to look like:

---------
require_once(templateFunctions.php);

$mypage = startTemplate('/path/to/template.html');

//other app logic...

assignTemplateVariable($mypage, 'MARKER', $variable);

//oops, now you have to pass $mypage by reference inside the
//function, so you modify the main $mypage variable and not a copy
//or, you have to constantly return the modified variable in full,
//as in $mypage = assignTemplateVariable($mypage, 'MARKER', $variable);
//which can be dangerous and counter-intuitive
//and you have to do more namespace-collision checking

---------

So you see how sometimes procedural methods can introduce unnecessary distractions in your main app flow. Even if your main application flow is procedural (which has its advantages in clarity and readibility), "side" issues like your database access and presentation concerns can be handled by classes. Basically, anything that you would like to swat aside like a fly, because it annoys you in your code could benefit from being encapsulated in a class somewhere.

Some of my criteris for the kinds of things to hide in classes tend to be:

1. if I am dealing with something annoying that distracts from my app flow, such as dealing with HTML, or configuration settings, etc...

2. if I want to maintain or protect the state of something I am dealing with -- for example, I have a class to access windows networks from Unix with by calling 'smbclient'. Now, that gets really messy, because each call to smbclient leaves you back at the root directory, so it is hard to navigate directory hierarchies in code. But, I maintain that state inside the class, using extra methods to put me where I should be each time, so the rest of my PHP code can interact with a Windows LAN just as naturally as with a local directory tree.

3. As a way to wrap up and render harmless some particularly messy piece of code inherited from a previous developer ;-). Haven't we all been there...?

4. When I want to think of a certain collection of data as sort of a 'complex' data type, which can be wrapped up and passed anywhere. Try that with only functions and you will get a headache fast (although it can be done).

Don't let anyone sell you OO purity as some sort of magic, but by the same token, don't be so quick to dispense with it. There are all kinds of reasons to use either one of procedural, functional (and yes, PHP has some functional abilities), and OOP. Really, I think each of us has certain mental predispositions to one or the other, but it is a good idea to learn a range of possibilities, so you can make an informed decision about which to use where.

Re: Maybe I'm clueless...
by Luke McCarthy on Wed 21st Apr 2004 18:42 UTC

I, quite franky, agree. OOP has niches where it is appropriate. But you are better off with procedural programming for the web. From what I can gather, PHP is often teamed up with MySQL, so there is no need to carry state inside objects when you have a database right next to you!

With a class you have reduced the reusability of all the functions ("methods") by locking them to a certain type of data structure. This may, in the short term, make them easier to use; but the lock-in nature dooms them to obscurity.

Combined with the fact that there are so many different OOP ABIs, and so many different opinions on whether feature X or feature Y are considered "OO", code re-usability is simply unfeasible (at least across language boundaries). Procedural code, with handles for state tracking when (and only when) it is required, is more often than not sufficient for almost anything. This is one reason for the persistence of the C language, despite all its failings!

Re: Maybe I'm clueless...
by Miron Brezuleanu on Wed 21st Apr 2004 18:49 UTC

Well, I had the same question. It seems there are some applications that could use a little polimorphism (nothing vital, however).

For instance you could define a "html rendering engine" of some pages as an "abstract class". Then write code having this "interface" in mind. Then write some implementation (actually generating the html, implementing the interface).

Nothing fancy yet.

But suppose you want to change the look of the site. You only need to write another implementation and create an instance of the new one instead of the old when needing a renderer (hopefully the renderer is created only once, in one place). This separates look&feel code from the rest of the app: the rest is written (hopefully) with the renderer interface in mind, so changing implementations doesn't matter.

Switching site looks becomes easier. Well, if you need that sort of change ;)

I'm sure similar stuff can be imagined. OOP is useful, sometimes .. ;)

In defense of OOP
by V. Jenks on Wed 21st Apr 2004 20:25 UTC

Personally, in defense of object oriented programming, I have to say that it's made my life eaiser, in most cases (where it is appropriate to use).

It doesn't solve every problem every time one is presented, but such is any programming language or technology and...such is life.

It wouldn't be practical to sit down and say "I only know or like C++, so I want to write a web site in C++" and then continue to sit down and write a simple web site by using C++ (I know the example is farfetched but it's also a possibility). In this particular situation, you would use HTML and perhaps combine that with other web-centric technologies such as CSS, JavaScript, or on the server side Java, C#, and perhaps even some C++-based web services.

A few years ago I wrote quite a bit of code in ASP/COM and other web-centric Microsoft technologies.

In procedural ASP (using say, VBScript), I would tend to write a TON of the same type of code repeatedly and it grew quite difficult to maintain in larger projects. Even writing VB COM components posed a lot of problems with maintainence issues.

Now, for example, using ASP.NET and .NET assemblies to contain highly OO code, I've found my projects easier to envision, plan, test, build, and maintain.

Rather than grabbing a Recordset and repeatedly looping through it over and over and over to display data (spaghetti-coding it together with HTML) I can now create a clean, simple business object to represent my data, populate it with data using the appropriate design pattern, and display it on the client very easily with data-binding.

Should I want to do something particular to each record after it's bound, I can simply extract it with an event-handler

Product product = (Product)e.Item.DataItem;

product.Name
product.Price
...

...and then do whatever I like with it's methods and properties.

It's a beautiful thing, I'm a big OO proponent for most programming tasks!

However, it does not solve every problem and for small web sites, applications, etc. - procedural works just fine and in that sense, will never go away or be considered obsolete.

Just my $0.02!

@Luke McCarthy
by Lumbergh on Wed 21st Apr 2004 20:39 UTC

With a class you have reduced the reusability of all the functions ("methods") by locking them to a certain type of data structure. This may, in the short term, make them easier to use; but the lock-in nature dooms them to obscurity.


Right on, and this is not discussed enough. I know this is not really a problem with OOP - per se, and can be mitigated with refactoring, but this is a problem with re-use. Software artifacts should be loosely coupled with tight cohesion. When you throw everything in a class you end up with tight coupling a lot of the time.

built for purpose
by valraven on Wed 21st Apr 2004 20:58 UTC

>With a class you have reduced the reusability of all the >functions ("methods") by locking them to a certain type of >data structure. This may, in the short term, make them easier >to use; but the lock-in nature dooms them to obscurity.

Isn't this like saying that it sucks that my
ford passenger door can't be used on my toyota?
You really think they should be reusable across
products?

The issues are the same in OO. At some scales in some
contexts reuse makes sense. It many others it does not.
This is not doom. This is the reality of things designed
for a purpose.

Re: built for purpose
by Luke McCarthy on Wed 21st Apr 2004 21:12 UTC

I guess you have a point there. There probably is no point in making public functions that muck about with internal state. In that case a class is a convenient way to hide it away. And I also guess that genericness of a function is not always desirable (because it may be a lot less efficient).

This really depends on the kind of code you are writing. It is probably inconsiderate for a library designer to dictate which structures you should use. Calculating a person's age from a date of birth and the time() doesn't need a Person object! (bad example, can't think of a good one at the moment)

Re: build for a purpose
by rycamor on Wed 21st Apr 2004 21:26 UTC

One interesting area in all of this might be the concepts of Aspect-Oriented programming (AOP). It seems to me the point of AOP is to resolve precisely those method lock-in issues of traditional OOP. It takes into account the idea that some concerns are "crosscutting" to others, and thus should be employable across classes instead of encapsulated in them. Anyone with experience at AOP care to comment?

It's usually at about this point in a discussion where I bring up my favorite logical model: the relational model. By that I mean the "true" relational model, not the standard hack called SQL.

Now I understand the relational model is not a programming model, but a data management model. However, most of the problems of programming ARE data management problems. To me, the interesting point about the relational model is precisely that it handles problems such crosscutting concerns simply and elegantly, allowing for declarative constraints over any and all parts of the system, allowing for user-defined operators, operator overloading, etc... Also, the relational model theoretically can allow for datatypes of arbitrary complexity, even inheriting attributes from other datatypes. It seems to me almost that by the time we have come full-circle with some magical combination of OOP, functional/declarative, AOP, etc... we might finally have what the relational model has had all along (only no one has bothered to implement it). And, yes... I will now bring up the website some programmers love to hate: www.thethirdmanifesto.com ;-).

I also have had good luck with OOP
by Anonymous on Wed 21st Apr 2004 21:27 UTC

By writing my common utility functions in nice, well contained classes, I have found that it makes it much easier to work on a project. For example, I wrote a class that interacted with MSN Messenger, and I abstracted away all of the socket stuff into it's own wrapper class. When I was assigned to write a project that monitors an IMAP mailbox, a nice sized chunk of this project was already done! I can just write a new class called IMAPMailNotifier or whatever, and use include SocketWrapper as a member, and now I have instant socket functionality. If I ever need to do MD5, url-encoding, I also have those classes available now. A week later, I was asked to write a project that parsed the Spam folder of an IMAP account, and parsed a header (X-Spam-Header- spamassassin score) and gave an average score for all of the message. It only took me 30 minutes because I had a reusable IMAP class.

Yes, this does mean the original project took longer to do, because I had to spend some time organizing the classes, seeing how they would interact with each other, deciding what members should be private, if anything should inherit anything from anything else, but it pays off. I have easily reusable code. My employer certainly was impressed at how quickly I finished my projects, and it also means that I have to spend less time debugging my project, because I am using code I have already tested. ;)

Just my thoughts!

AOP
by valraven on Wed 21st Apr 2004 21:48 UTC

>One interesting area in all of this might be the concepts
> of Aspect-Oriented programming (AOP). It seems to me the >point of AOP is to resolve precisely those method lock-in
> issues of traditional OOP.

I think the logical conclusion of AOP is that methods
and classes do not exist. Otherwise what does my method
or class mean anymore if anyone can change it to do
anything and i can't even tell that it happened?

new to OO
by adam on Wed 21st Apr 2004 23:32 UTC

as someone new to oop, why would you use class Student, then turn around and make a function Student.. i have no idea what you are talking about when you refer to $a_student = new Student(fdsa,fdsaf); ....

OOP with Fortran, any interest?
by OoSync on Wed 21st Apr 2004 23:35 UTC

Would anyone be interested in seeing a similar tutorial done in modern Fortran?

In all seriousness, I'd be quite interested in doing so, as that's a language that's not oft-mentioned in these circles. A little breadth-of-experience could be interesting for many readers here.

re: AOP
by mabhatter on Thu 22nd Apr 2004 02:40 UTC

from what I understand AOP allows you to define actions based on aspect rather than class. most of the examples I see involve things like data input or record handleing and verification. AOP allows you to define something accross all classes of a type you define. The examples I always see are error & bounds checking...AOP allows you for example to define bounds checking for ALL input fields...preasent and FUTURE...so you can't forget to add it later! It's just there in the background doing it's thing.

The poster above was right about the relational thing, everything is data & scripting is just stored procedures on the data...we're working both ends against the middle here. There are rules-based database applications that take general rules and apply them to make applications...but programming languages haven't quite bridged the gap to make it have a human's intuition...simple things users might want such as "all screen will input employee clock number" are still a bear to implement in most programming languages. especially AFTER the programs are already running!!!

RE: new to OO
by Anonymous on Thu 22nd Apr 2004 05:44 UTC

as someone new to oop, why would you use class Student, then turn around and make a function Student..

When you make a function with the same name as the class name within the class, this is a special function called a constructor. This function is called when an object of the class is created. Remember that the class is a guideline for making objects. This is explained in the article...

i have no idea what you are talking about when you refer to $a_student = new Student(fdsa,fdsaf); ...

$a_student is an an object of class Student (if you want to be more fancy, $a_student is an an instantiation of class Student). We designed a class called Student, and now we are actually creating a Student by using new. The fdsa,fdsaf are values that are passed to the constructor.

re: new to OO
by adam on Thu 22nd Apr 2004 11:19 UTC

well after doing some reading, he should have mentioned that the reason he named the first function Student is because that is what is looked for first considering the class is named student, at least that is what i could get out it from other readings.

RE: ADAM
by Anonymous on Thu 22nd Apr 2004 11:30 UTC

Also, if you have a function called the same thing as the class name ("Student"), then when you create an "instance" of the object in your code (ie, you create a student in your application), then that function is called automatically, as soon as you create the instance of the object. This function has a special name, called a "constructor"

It is in the article.

RE: OOP with Fortran, any interest?
by Christophe Grandsire on Thu 22nd Apr 2004 13:05 UTC

Would anyone be interested in seeing a similar tutorial done in modern Fortran?

What do you mean by "modern Fortran"? The currently used standard, Fortran 95, is no OO. OO programming can be approximated (I personally did it, developing a whole library in Fortran 95 using an OO-like structure with private types put in modules and getter/setter functions to access these types), but it's very much like Perl 5's OO: a hack to simulate OO programming in a procedural language, and it's not easy to maintain.

Fortran 200X will be completely OO, but the standard is not ready yet and no implementation exists of it.

In all seriousness, I'd be quite interested in doing so, as that's a language that's not oft-mentioned in these circles. A little breadth-of-experience could be interesting for many readers here.

I agree. Fortran *is* a nice language, which has evolved a lot since the days of Fortran 77 and fixed-form lines. Fortran 95 is a very modern programming language, with an interesting syntax (although it sometimes annoys me to no end ;) ) ). For heavy array calculations, Fortran stays the best language out there (which is why one of the best fluid mechanics simulation package out there, Fluent, is written entirely in Fortran) and with the right libraries, it can do many other things (I personally write programs with full GUI entirely in Fortran, thanks to the Winteracter library). Fortran 200X will have complete access to the C libraries, thus providing tons of useful features without need for rewriting.

In my hierarchy of favourite programming languages, Ruby is the uncontested winner (being the first language I saw that seems to *guess* my needs before I even articulate them ;) ) ), but Fortran is a good runner-up, probably because it took me only three weeks to learn enough Fortran 95 to be productive (without formal course). Only Ruby has a better score here (I've had formal classes of C and Pascal, and tried to teach myself Java and Python, but never managed to get productive in those). And note that I am *not* a programmer by education, but a engineer ;) (in my current job, I am slowly becoming a programmer, though, which is why I had to learn Fortran ;) ).

Anyway, I agree that an introduction to Fortran 95 would be a good idea (if only to dispel the myth that Fortran is outdated ;) ). I could help if needed.

RE: OOP with Fortran, any interest?
by rycamor on Thu 22nd Apr 2004 14:29 UTC

Sure, I would be interested in a Fortran tutorial. Funny... the last time I dealt with Fortran was my first year of college (1983... yeesh), and I as 17-year old engineering student took an intro to Fortran course. Back then, the Freshmen didn't even get to work with CRTs, so we had the experience of typing our code on punch cards... lol. My main project had a bug that neither I nor my professor could figure out. She finally gave me a good grade, because as far as she could see, my code was right, but the mainframe just refused to run the program. That experience soured me on programming for quite a while, unfortunately.

RE: OOP with Fortran, any interest?
by OoSync on Thu 22nd Apr 2004 15:40 UTC

My main thought, to which I'm sure you'll agree, is that everything object-oriented presented in this tutorial is also available in modern Fortran. And yes, I do mean Fortran 90/95 when I say modern.

As far as if F95 is and OOP language, well, more or less it is. There are some excellent tutorials on this and even the book _Object-oriented Programming with Fortran 95_, which is pretty decent. What Fortran 95 cannot do is dynamic dispatch (i.e., part of what templates allow in C++) and inheritance. Both of these can be emulated to a degree if they are absolutely necessary. Of course, as you mention, the Fortran 2003 (official name) revision updates the language to a fully OOP language. If you wish to play with these things, the current Lahey compiler (version 9?, I'm not sure), already impliments many of the new features, including OOP features.

Hmm, on second thought, it may be pretty cool to write a pretty simple intro to OOP and F95, and then play with the Lahey compiler to flesh out an intro to OOP in F2003. That could be really fun.

Nicley Done
by NixerX on Thu 22nd Apr 2004 16:17 UTC

This was probably one of the most easy to understand OOP breakdowns I've ever read.
Great Work. Maybe Oreilly should give you a book deal!
-Nx


RE: Nicely Done
by John Collins on Thu 22nd Apr 2004 20:18 UTC

Thanks!

Thanks!
by Andy Crofts on Fri 23rd Apr 2004 05:22 UTC

Excellent artcle.
I've struggled with 'theoretical' OOP concepts for ages, and never got it. Books written by people who assume the reader already understands the idea.
This article had a simple (academic!!) example that I could follow at last.
Got it, easily. More like this, please!
-Andy
-Oulu, Finland