Page 1 of 6

When should a class be used?

Posted: Sat Feb 19, 2005 10:35 pm
by Stryks
Hi all,

I've been coding for a while and am currently working on the biggest project I have ever worked on. As I go on, it occurs to me that there must be some reason all the big packages that I see use classes in one way or another.

It also dawns on me that perhaps this reason is to ease the knots that I seem to get myself tied into. Especially in regards to database access and user authentication.

Thing is, I have never used classes, and while I learned PHP pretty much from looking at things and changing them until they did what I wanted, I just cannot seem to learn classes in the same way.

Anyhow, I'm doing a tutorial and reading up as much as I can (though I dont seem to get it fully most of the time) and I am finding myself without answers for a few fundamental things ....

For example, what would I use a class for? I mean ... I'm assuming classes are best used for repetitive things, as opposed for things that are just used once.

So ... a class is your man if you want to access the database and return results, but not your man if you want to return a specific results set (unless it applied specifically to another task).

Will it make code run faster or better? Will it make my body of code easier to manage?

Sorry if these are dumb questions.

Cheers. :)

Posted: Sat Feb 19, 2005 10:59 pm
by feyd
classes are very useful when you have a data set that needs to be operated on by more than one specialized function. They are useful for creating a simple way of interacting with data sets, grouping similar functions together, building generic interfaces so that the internals can be changed without affecting what a user sees. There's a lot..

Classes can make code run faster, but often it's better for migration, resuse and maintenance. It can take some time to set up a good OOP base, but once built, it is a lot easier to maintain across multiple uses.

Posted: Sat Feb 19, 2005 11:30 pm
by smpdawg
Having written procedural code for over 20 years and OOP for the last 15 years I can honestly say that in most cases it comes down to personal preference. I am sure that purists will lean one way or the other and likely say that I am wrong but the fact is that you can do most of your your work using one, the other or both. For example, I am writing an OOP framework in PHP5 and yet my day to day work leans more toward procedural development.

For me it seems that the right time to use objects is largely to use and abuse inheritance and encapsulation - yes I know there are other uses for objects but those are the ones that are the most obvious and useful to me.

I like that I can put commonly used functions into containers for the express purpose of keeping tasks grouped. However you can do the same thing using files that contain related functions and not use objects at all.

I am particularly fond of implementing base functionality into an object and then creating specialized derivatives of that object. Life can be so much easier when you know that the underlying code has been tested and works well and you are simply extending it.

And while I like objects a lot, I don't care for class methods. Don't get me started.

I like using objects in an attempt to rid myself of globals. I particularly like static objects to act as containers for "globals" without having to worry about instantiating the object to access the data or worse yet having to have a global object that I must reference when I am trying to avoid the use of them in the first place. Outside of scoping related issues, this one is nearly impossible without objects.

I like the protection that is afforded to variables that are owned by objects and that you can essentially have the same variable represented an infinite number of times and yet they are for all intents unrelated.

Performance is a relative thing. For one person performance is related to speed at which code executes. For others it may be related to development time. Unless a method is exceptionally slow, I prefer to concern myself with development time. Don't get me wrong, if a function seems to run slowly or it is used frequently during the scripts lifetime I will look at its impact but the first thing I am concerned with is reasonable development time and a stable code base.

Objects and for that matter a standard set of libraries help reach that goal. A properly written function can be both clearly understood and highly efficient and would not have the overhead that the creation and destruction of an object would impose.

What you need to ask yourself is whether or not the task at hand would benefit from the creation of an object. Don't create an object for the sake of doing it, there needs to be a clear and important use or you are simply wasting your time.

Since you mention recordsets... Yes there are good reasons to return objects instead of normal recordset in PHP. My library uses objects to represent variable types since PHP is weakly typed and I come from the world of Delphi and C/C++. I want to know that when I query an object that I get a result that represents the type that I am expecting. There is nothing worse than expecting a floating point value and getting a string – it can really complicate matters. Using my framework I with reasonable certainty that whenever I ask for a number, I get a number and that the dirty details are hidden behind my objects. And these same objects can be queried to return a string formatted as a currency amount based on data that has been typed and validated.

So what is my opinion? Learn objects now. Use them until you feel comfortable with them and then make up your own mind. What works well for me may not work well for you because you and I may have different strengths and weaknesses.

BTW - One of the best OOP frameworks around is the Delphi VCL. It is a work of art.

BTW 2 - Don't talk to me about Java because I hate the fact that simple things like basic mathematical functions were thrown into objects in an attempt to promote OOP as the one and only true way to write code. Compilers don't generate output in OOP form, they (for the most part) ultimately write procedural code so there is still a place for procedural development in the world.

Posted: Sun Feb 20, 2005 1:23 am
by Stryks
Thanks for taking the time to reply. Some very useful info there.

But having asked what is probrably a very 'newbie' question and having received a good response, I'm feeling like I should continue to display my ignorance by asking, what is inheritance and encapsulation?

Another word that seems to get thrown around alot in all the documentation I have been drowning in is polymorphism. I get the feeling that this doesnt relate to PHP, but I guess it never hurts to ask ... what is it?

You mention about extending on classes. How do you mean that? A class can extend another class? Or are you meaning just tweaking a solidly tested class?

Excuse the level of these questions, it just seems that the info I can find either go ultra technical or really basic, and though they throw terms around, it can be quite difficult to nail down what they mean. I'm actually starting to wonder if someone just made up polymorphism to sound smart. :lol:

Again, thanks for the feedback. Any other pointers would be appreciated. :)

Posted: Sun Feb 20, 2005 8:43 am
by smpdawg
I started to write a REALLY long winded response when I found two sites that did a good job of explaining OOP. The first is at Wikipedia http://en.wikipedia.org/wiki/Object-ori ... rogramming and the second is the PHP5 reference http://us2.php.net/manual/en/language.oop5.php .

If you have specific questions after you look at these sites I would be more than happy to answer them. I can help you with a sample implementation of an object if you would like.

Posted: Sun Feb 20, 2005 9:17 am
by feyd
Moved to Theory.

Posted: Sun Feb 20, 2005 6:51 pm
by McGruff
I've been coding for a while and am currently working on the biggest project I have ever worked on. As I go on, it occurs to me that there must be some reason all the big packages that I see use classes in one way or another.
The short, slightly-exaggerated-but-basically-true answer is you can either write unmaintainable spaghetti code or you can take a year out to learn how to write well-encapsulated, object-oriented code.

With respect to previous posters, it's not a matter of personal preference. There is simply no comparison between OOP and procedural. You cannot approach anything like the power of OOP with other methods.

Often I get flamed for statements like that (I'd strongly advise that you stick to reasonable arguments rather than bad-tempered attacks, should you be so inclined) but there's no point beating about the bush.

The benefits of OOP are all at the programmer end of the machine<--code-->programmer interface. A computer will happily parse any old junk (phpBB source being a fine example - so much so I've given up trying to maintain it and have started writing a replacement for this forum). People, on the other hand, like to have things broken down into chunks. Chunks can be unit-tested (another essential technique - see my sig link). Chunks can be swapped in and out easily, should the need arise, without disturbing anything else. Sometimes they can be re-used but that's a side benefit of the drive to truly understand what is going on in your script, and to separate all the different threads into self-contained units.

Everything should be an object - or rather a package of co-operating objects, each doing just one thing. You could easily use dozens of different classes in a single script (if I was writing the code for a page such as the one you're viewing, I'd probably be using something like 60-70 different classes). If not, either what you're doing is very simple or you haven't defined your classes tightly enough.

I've written my fair share of spaghetti. It is a good thing that you can dive into php easily and start creating functional, dynamic websites. But, if you are interested in learning to program well, OOP and unit testing is the way to go. Expect a lot of effort (nothing will make sense the first time you read it, but it will on the second or third) and also lots of fun "eureka!" moments along the way.

Posted: Sun Feb 20, 2005 10:18 pm
by smpdawg
A bad programmer can write unmanageable procedural code or terrible objects - give a man enough rope...

Objects by themselves do not force a programmer to write good code and procedural code does not need to be spaghetti code. The difference is the person that writes the code and not the paradigm. If you don't believe that you haven't experienced the worst that some people have to offer.

As a consultant on an engineering application I encountered some absolutely atrocious objects written by people that claimed to have been Java programmers that migrated to Delphi. It was some of the worst code that I have ever encountered and violated anything that seemed reasonable to me. They had objects that were intended to be containers and more than one container would hold the same children and each container could and would free objects when they were destroyed. Needless to say this code was nearly impossible to debug because objects would be released and you would not know what parent caused it to happen. In a small project you can identify an offending object but try to find them in a system that had hundreds of distinct object types, a half million lines of code and processes that dynamically created hundreds of thousands of objects during the design process. These were spaghetti objects that lead to mammoth memory leaks and degraded performance. Proving once again that a bad programmer will be a bad programmer regardless of the tools that you give them. BTW - My task was to rewrite the objects so they behaved properly, define the coding standards for the company and teach the programmers how to do their job.

Like I have mentioned, I have been programming for 20+ years. Along the way I have seen some beautifully crafted procedural code that was easy to read and maintain and that included some beautiful assembly language that was the core of an OS. FYI - Shared code libraries that contain procedural code also offer the benefit of code reuse, reduced development cycles and lower error rates. So you cannot make a blank statement like all objects are good and all procedural code is spaghetti.

I also want to point out that extolling the virtues of OOP in a weakly typed language is absurd. What good are objects and all their wonders if you are still allowed to subvert the intent of code by doing implicit casting from one type to an entirely different and inappropriate type?

As much as I like PHP, weak typing is its worst attribute. It ranks right up there with Visual Basic which I consider to be the WORST thing to have happened to programming ever. Why? Because it allows people that should even be allowed to sit in front of a computer to write programs and then claim to be a programmer. I firmly believe that all programmers should be required to write code in a strongly typed language for years before they are allowed to move on to other languages. That by itself would have two benefits. 1. There would be fewer VB “programmers,” 2. The ones that are out there would understand the advantages of working with a strict language and carry good techniques with them for the rest of their lives.

Since it is obvious that you were referring to my post let me point out that I mentioned that there were clear virtues to objects and some things simply cannot be done any other way. I recommended learning to use objects properly and then making up his own mind about when it is appropriate to use them. I also said that I am writing an OOP framework in PHP5 so I obviously believe that objects, properly crafted, are essential to good development. BTW - my objects allow for the concept of enumeration and I have objects that help enfore types so I am pulling in some of the virtues of strongly typed languages into PHP via objects.

And yes, I have been known to say unpopular things too but I will not say that procedural code has no place in the modern world of programming, After all, the OS's that we are riding on were written with largely procedural code and they - for the most part - work just fine.

Posted: Sun Feb 20, 2005 11:18 pm
by McGruff
I really didn't mean to single anyone out. I just want to make sure that people don't get the wrong idea about OOP.

Of course just because someone sticks something in a class doesn't make it good per se but we don't really need to discuss examples of bad OOP code in order to debate whether the OO paradigm is inherently better. That just confuses the issue.

I tend to look at programming entirely in the global scope as one-dimensional. Functions add a second dimension and OOP adds a third. With each step up, the power of the language increases exponentially. Procedural code works - sure - but why settle for second best? That's not where we're at in 2005, or for a good many years now.

PS: Strong typing? No thanks :) OOP works very well without it - and php can enforce it when needed.

Posted: Sun Feb 20, 2005 11:32 pm
by smpdawg
It can never be strong enough for me. :D

Unfortunately we constantly have to settle for second best. Windows. ugh. And I have yet to find a truly useful IDE for PHP although I am partial to PHP Designer 2005 and the Zend studio works when I have no choice. Of course I am sitting in Fedora Core 3 stuck with Quanta. What is really missing now is a nice framework for PHP - for some reason I just don't like PEAR and I can't put my finger on it. I'd really like to see something like Delphi for PHP and that is what I am working on...

BTW - I don't take things personally, I just like to present my opinion.

Posted: Mon Feb 21, 2005 1:36 am
by AGISB
I do not like the argument that PHP and VB are basically just evil due to the little restrictions they pose on the programmer.
I don't like the idea that programming even easy tasks is limited to the pros. I like that I can just sit in front of VB and write some little tool in 15 minutes that helps me ease a task that would take me an 1 hour to achive. If I follow your logic I would have to spend 2 hours to write clean code in any given OOP language to achive that goal effectively wasting an hour. I often have such tasks on hand that require one time solutions and VB is the best for that.
PHP I even love for the fact that I can do what I please. If I like OOP I do it. If I like plain coding I do that. Sure can be a nightmare on maintaining but thats not a problem of a language but the person writing code.

Posted: Mon Feb 21, 2005 1:51 am
by feyd
When a single person is, and will always be working with a piece of code, they may do whatever they wish. If the code is to be shared with anyone else, it should be at least documented and parts broken off into functions and things. If they want it to be used in the bigger applications or upgradable in the future by other persons (with ease), OOP is about the only option.

Working in someone else's spaghetti is torture at best. A giant waste of time at worst. The sprial continues quickly if there's horrible documentation, sadly, that's quite often. Weee...


For some reason I have a huge sense of deja vu about this thread..

Posted: Fri Feb 25, 2005 9:57 am
by bg
smpdawg wrote:It can never be strong enough for me. :D

Unfortunately we constantly have to settle for second best. Windows. ugh. And I have yet to find a truly useful IDE for PHP although I am partial to PHP Designer 2005 and the Zend studio works when I have no choice. Of course I am sitting in Fedora Core 3 stuck with Quanta. What is really missing now is a nice framework for PHP - for some reason I just don't like PEAR and I can't put my finger on it. I'd really like to see something like Delphi for PHP and that is what I am working on...

BTW - I don't take things personally, I just like to present my opinion.
For an editor i'd recommend jEdit.

Posted: Fri Feb 25, 2005 12:49 pm
by smpdawg
Thanks for the suggestion and stop looking at Prado LOL. Keep working on your framework and when I allow outside access to my framework I'll let you know. I'd like to compare notes.
bgzee wrote:
smpdawg wrote:It can never be strong enough for me. :D

Unfortunately we constantly have to settle for second best. Windows. ugh. And I have yet to find a truly useful IDE for PHP although I am partial to PHP Designer 2005 and the Zend studio works when I have no choice. Of course I am sitting in Fedora Core 3 stuck with Quanta. What is really missing now is a nice framework for PHP - for some reason I just don't like PEAR and I can't put my finger on it. I'd really like to see something like Delphi for PHP and that is what I am working on...

BTW - I don't take things personally, I just like to present my opinion.
For an editor i'd recommend jEdit.

Posted: Fri Feb 25, 2005 9:04 pm
by magicrobotmonkey
I think that because of PHP's most common usages, OOP is usually the better choice. PHP is used most often in (nearly always?) in developing apps for the web. This is where OOP can flex its muscle. Because of PHP's flexibility, an OOP paradigm is almost required to ensure security. Your typing classes (which I wouldn't mine having a look at) are a good example of this.

Also, when attempting to programming using best practices (a prime example would be the separation of business logic from presentation), OOP shines. Currently, I generally write all business logic into classes, just because it lends itself so well, making it almost easy to map real world into code. Combine that with some templating classes for display, and you have yourself a nice framework.

While its true that not all procedure code is spghatti, its also true that excellent OOP code can be written in a losely type, privacy free (pre 5) language like PHP, providing the programmers are disciplined enough to do so. I was taught OOP in Java in school and then taught myself PHP and to this day I am amazed at how lazy PHP permits me to be. The only thing that keeps me writing get accessors is that I work with other people and we have coding standards. But as long as we stick to them, we can turn out some pretty nice OOP.