Page 1 of 1

OO Approach vs. Non-OO

Posted: Fri Mar 15, 2013 8:27 am
by spacebiscuit
Hi,

I'm in the process of designing a small application, I'm considering using the OO approach but want to ask your thoughts.

Imagine a grid of 9 tiles, 3 x 3 which stores a value. The tiles can be swapped around arbitrarily, a bit like a kid's sliding puzzle game except this doesn't have an empty/missing tile. Once the tiles have been moved to the user's satisfaction the layout would have to be saved.

Some my question is what is the best approach, typically I would have used a mysql db to store the configuration and each time the tiles are moved I would update the tile value in the database. I would imagine that I will need the db in order to store the final condfiguration but if I used a PHP class object might it be a better approaxh.

Although I get the principles of OO programming I am struggling a bit with the concept. What defines the code as OO? As far as I can figure some sequential code is required in order to call the object so the code wouldn't be pure OO is that right?

A guess put another way, what would be a non-OO approach and how would it compare to the OO approach, what advantages would the later give me over the former.

Apologies if this is quite a vague question but I want to get it right before I dive in and create a mess that might have to be undone.

Thanks in advance!

Re: OO Approach vs. Non-OO

Posted: Fri Mar 15, 2013 1:09 pm
by requinix
spacebiscuit wrote:Some my question is what is the best approach, typically I would have used a mysql db to store the configuration and each time the tiles are moved I would update the tile value in the database. I would imagine that I will need the db in order to store the final condfiguration but if I used a PHP class object might it be a better approaxh.
That's more a question of whether you want to apply changes immediately or wait for the user to hit a Save button. The actual tile-moving code can be procedural or OOP regardless.
spacebiscuit wrote:Although I get the principles of OO programming I am struggling a bit with the concept. What defines the code as OO? As far as I can figure some sequential code is required in order to call the object so the code wouldn't be pure OO is that right?

A guess put another way, what would be a non-OO approach and how would it compare to the OO approach, what advantages would the later give me over the former.
Object-oriented programming is about using objects... which should be fairly obvious when written out like that. In terms of PHP, purely procedural code tends to use ID numbers and arrays of values while OO code uses objects and properties/methods.

Code: Select all

// procedural code
$result = mysql_query("SELECT * FROM users WHERE id = " . (int)$_GET["id"]);
$data = mysql_fetch_assoc($result);
echo "Welcome " . $data["username"];

// object-oriented code
$user = User::get($_GET["id"]); // $user is an instance of User
echo "Welcome " . $user->username;
Note how the procedural code takes the ID number, directly queries the database, and gets an array of values, while the OOP code has a User class, calls a method on it to get a User instance, and outputs the ->username from it. With the former you need to know exactly where data is, how it's arranged, and how to query it; with the latter you can just use the User class without having to care where it gets its information from.

Now remember I said "purely procedural code"? PHP is a procedural language: it starts at the top of a file and executes every statement until it reaches the bottom. You must do this to some degree regardless of what coding style you have or environment you're in. Pure procedural code uses few, if any, objects (as dictated by the language itself) and the execution depends entirely on the one script*. OO code will still start running from a single script because that's how PHP works, but it will use objects, and the behavior of each object is defined in a completely different place.

Put yet another way, OOP is about acting on entities. Using the same example you read procedural code as

Code: Select all

execute a select query to get data from the "users" table in the database, according to the user ID given
grab a row from that resultset
use the "username" column to output a welcome message
That's dealing directly with data. OO code reads more like

Code: Select all

get a user with the given ID number
use their username in a welcome message
That acts on a concept of a "user". Internally, User::get() may query the database the same way the procedural code does, but what's important is that external code doesn't have to know about all that information. Really, all the external code knows is that User::get() gets a user according to an ID number and that User objects have a ->username property.


* Not counting various include()d files which may define utility functions or configuration data. That's a matter of code reusability.

Re: OO Approach vs. Non-OO

Posted: Fri Mar 15, 2013 1:42 pm
by spacebiscuit
Thank you requinix for a detailed explanation which has certainly got my brain ticking over.

Given your get 'user example'. If I was wiring this in procedural I would write a function that queried the database with a given ID. I'm struggling to see how this differs from your object which seems to do the same thing. Or is the advantage as I suspect the scope of the result and what you can do with it across different scripts?

Could the function "get_user" that I refer to be considered an object in anyway, I appreciate the result which might at best be stored in a session variable is not an object but what about the means of grabbing the data?

Thank you for your patience and I hope it's not to painful holding the hand of OO newbie!

Re: OO Approach vs. Non-OO

Posted: Fri Mar 15, 2013 2:02 pm
by requinix
But what would that function return? An array? Then it's not OOP.

Re: OO Approach vs. Non-OO

Posted: Fri Mar 15, 2013 2:08 pm
by spacebiscuit
Yes agreed the result would not be an object, but the methods (using a class or using a function) are not fundamentally different right?

So am I correct in saying the advantage is when it comes to the result, an object rather than an array that can have a wider scope?

Thanks!

Re: OO Approach vs. Non-OO

Posted: Fri Mar 15, 2013 3:03 pm
by requinix
Right, they're not that different in behavior, but the intents behind them may be.

In a loose and uncommon interpretation of "object-oriented programming", you can have an array represent an entity. If you pass that array around various functions like get_user() or get_username() then it's still treating the data as if it were an entity. As one discrete unit. In fact you can keep doing that and silently substitute in an object for the array, and as long as you update the functions to know about this change then the external code (the stuff you write that calls those functions) doesn't have to be rewritten. Now consider if you renamed those functions to "User::get" and "User::getUsername": you'd cross the line back into the traditional form of OOP where you have actual objects.

Re: OO Approach vs. Non-OO

Posted: Sat Mar 16, 2013 1:25 pm
by Christopher
spacebiscuit wrote:A guess put another way, what would be a non-OO approach and how would it compare to the OO approach, what advantages would the later give me over the former.
This is a difficult question to answer for a number of different reasons. A big reason is that there are both language syntax and design aspects of OO and procedural. So just using the class construct in the language does not mean that you are suddenly doing OO. It is possible to write OO code without the class construct and possible to write procedural code using classes. At the heart of the difference is a fundamental difference in outlook. Procedural think of procedures first and passes the data through sequential procedures to "process" it. OO thinks of data first and then defines what procedures can operate on the data. At its simplest, and object provides scope limitations for data structures and the code that operates on them. Those limitations provide a simple protection against common side-effects of code changing things it shouldn't.

But beyond that basic benefit their is a whole new set of design options that open up when you pass objects (a data struct + code that can operate on it) to other objects. There are thousands of books covering the possibilities from broad strokes to individual design patterns.

The bad news is that many of these ideas are counter-intuitive and you really need to prove to yourself that they are better than your home-grown solutions by seeing it first hand. So keep plugging away.

Regarding your specific problem, a class something like this might be a start:

Code: Select all

class Grid
{
    protected $rows;
    protected $cols;
    protected $grid = array();

    public function __construct($rows=3, $cols=3)
    {
        $this->rows = $rows;
        $this->cols = $cols;

        for ($row=0; $row<$rows; ++$row) {
            for ($col=0; $col<$cols; ++$col) {
                $this->grid[$row][$col] = 0;        // set some default value
            }
        }
    }

    public function set($value, $row, $col)
    {
        // add bounds check here
        $this->grid[$row][$col] = $value;
    }

    public function save()
    {
        // write grid to database
    }
}

$grid = new Grid();
One of the OO concepts here is that the grid object is fully initialized and usable when instantiated. With procedural you often need to pass struct to an initialize function and check if it is initialized.

Re: OO Approach vs. Non-OO

Posted: Tue Mar 19, 2013 3:38 pm
by spacebiscuit
That's a great start and very helpful.

Another question I have, what is the scope of a PHP object. For example using procedural I would usually set a session variable so that it gives the variable scope across several scripts. Is this an outdated approach, does OO approach work differently.

Thanks.

Re: OO Approach vs. Non-OO

Posted: Tue Mar 19, 2013 4:30 pm
by Christopher
spacebiscuit wrote:Another question I have, what is the scope of a PHP object. For example using procedural I would usually set a session variable so that it gives the variable scope across several scripts. Is this an outdated approach, does OO approach work differently.
With classes you can control scope. You can make properties (class variables) and methods (class functions) 1) public - visible outside and inside the object, 2) protected - only visible inside the class and classes that inherit it, 3) private - only visible inside the class, but not even visible to classes that inherit it. So you have control.

Re: OO Approach vs. Non-OO

Posted: Tue Mar 19, 2013 5:03 pm
by spacebiscuit
So would I still need to use session variables?

Re: OO Approach vs. Non-OO

Posted: Tue Mar 19, 2013 8:15 pm
by Christopher
You still use the session, files and databases the same way. However you can sometimes wrap things like $_SESSION or a database connection in a nice class to make things easier.