Object-Oriented Programming Necessity

  • Nov 15, 2009 | phpRogue | Programming, PHP

Object-oriented programming capabilities in PHP have come a long way and allow for functional and efficient code. I have seen many scripts that take advantage of OOP and many are done well. However, it seems to me that some people tend to over-do it on the classes.

Code should be functional. It should be efficient. And equally important, it should be easy to read. I can't understand why so many programmers feel the need to write long and complex code to perform simple tasks. You don't need a class to convert a date format - a simple function will do the job. Why write 50 lines of code when you can accomplish the same task in ten lines? Is it to prove how skilled they are by the complexity of the code? The real skill is getting the size of code as small as possible - that's called efficiency.

There is a need for OOP when designing large systems that will be maintained by multiple developers. The strict structure of well-written classes will keep sloppy programmers from creating many errors.

In order to know if you should use classes in your program, ask yourself a couple of simple questions.

  1. Is there an actual object that I need to model? If you are developing a website that sells used cars, then you may need a Car class to manage the data of each car.
  2. Does the size of this project justify the extra time required to develop foolproof classes? If you're going to write a class, you'll want to make it as robust as possible; otherwise, what's the point?
  3. Does the task really require the functionality of a class, or can I accomplish the same thing with a function?

My Legends of Dhashar PBBG relies on classes to manage characters, monsters, and the map. This was a decision I made based on the scope of the game, the fact that I'm modelling concrete objects, and the possibility that I might allow other developers to work on the codebase. The classes make the code easy to read and to modify.

Classes in PHP make for very powerful and efficient code, but be careful not to waste your energy writing unneccesary classes to perform simple tasks. Overly complex code is not a sign of a great programmer, but that of an inefficient amateur with something to prove.