Welcome Guest, Not a member yet? Register   Sign In
Objects: Why are they useful?
#1

[eluser]codex[/eluser]
I see people talking about objects as if they are the best thing since sliced bread. I've read about objects also (http://en.wikipedia.org/wiki/Object_(computer_science)), but somehow I still can't figure out what they exactly are and why they are so damn useful. I mean, the way I do my coding I can get my stuff done pretty much the way I want to, but there are still a few concepts out there that puzzle me. Objects (vs ?) obviously being one of them.

Can anyone enlighten me please? :red:
#2

[eluser]tonanbarbarian[/eluser]
firstly object are not as useful (in my opinion) in web apps as they are in other situations

objects are mainly a way to group common functins together into one cohesive unit that can do some related functionality

to explain the full potential (as i see it) of object let me give an example
if i am creating a java application, one of the things it might need to do is to process an xml file for example.
it will need to read the file, process the data in some fashion, maybe write new data to the file, maybe delete the file if it is no longer needed.

now i could just create a bunch of functions all named similarly to do this (ok so java only works with objects so i could not really do this but bare with me)
but if i create an object to do this it is much more efficient. the object can contain all of the methods to do the various bits of processing, as well as containing any data it needs to do its processing, all self contained.

so the application might load the object, start processing the file etc.
then if the application goes and does something unrelated the object is of course still there and available.
So not for example the app wants to close, as part of the cleanup it might go to the xml object and ask it to delete the file it was working on. If i was using functions to do all of this i would need to have remembered somewhere what file was being worked on, but because im using an object, the object would have its own propery that indicated which file was being worked on and would therefore be able to delete without being told which file.

this is just one example of the advantages of objects.

another big advantage is reusability and portability
if i have another app that needs to interact with an xml file i can just take the entire object code and move it to the new application and it is ready to use.

In the web environment you do not always get all of these advantages of using objects. the reusability and portability is there but because of the stateless nature of a web app you cannot always have the advantage of having an object alays know what is going on
If we look at the previous example and move it to a web environment the upload of the xml, the processing and the later deletion of the file may in fact be all on seperate requests of the webserver. Now there are mechanisms that can be used to retain the state of an object between requests but if they are not used you loose that advantage.

It is the reusability that is the big thing for me that i see as an advantage.

sometimes objects are used in ways i do not like however.
for example i prefer to use the result_array method in the CI database because i do not see the point in using an object as a collection of data when i can just as easily use an array
Also i have seen instances where classes where used more as just a simple namespace rather than a real object
i.e.
Code:
MyObject::myfunction();
This calls a method of an object statically. You do not have to make an instance of the object you can just call the function.
Yes this does have its uses but i prefer not to do that.

these are just my thought, not sure how enlightening
#3

[eluser]codex[/eluser]
[quote author="tonanbarbarian" date="1201058327"]
sometimes objects are used in ways i do not like however.
for example i prefer to use the result_array method in the CI database because i do not see the point in using an object as a collection of data when i can just as easily use an array
[/quote]

Yes, this is also something that puzzles me. What is the advantage of using result_object() over result_array()? I mean, they both yield the same results, so what's there to gain by using result_object()?

BTW, thank you for your quick reply. Objects are indeed what I thought to be, a collection of related functions, but I still can't see (besides reusability and portability) what the fuss is all about.
#4

[eluser]wiredesignz[/eluser]
Arrays only contain data whereas Objects contain both data and methods to act on the data, both can be passed around your script as single entities.

The $query_result() object is a bad example to use on its own and is no better than $query_result_array().

However if you have a class and instantiate your object from the query_result() ie: $car = new Vehicle($query_row()) then you have your data and methods to describe it or act on it all in one place.

This is much better for reusability and inheritance as the Vehicle class could be extended to become Truck, Plane, Bike etc without a lot of repeated code.

Hope this helps.
#5

[eluser]ejangi[/eluser]
Personally I think to say that an object is a collection of functions simplifies it too much. The idea of objects is to describe (in code) things more like we experience them outside of code.

Take a hammer for example, it has properties:
- material: metal
- weight: X kg/lb

And it has "functions":
- hammer nails
- remove nails

You can actually describe this "Object" as a class:
Code:
class Hammer {
    var $material = 'metal';
    var $weight = 1;
    
    function Hammer($material = 'metal', $weight = 1) {
        $this->material = $material;
        $this->weight = $weight;
    }
    
    function hammer_nails() {
        // Do functionality here
    }
    
    function remove_nails() {
        // Do funcationality here
    }
}

This class is like a cast or a mould that you can form objects out of. So to create a new hammer object, you would use the following:

Code:
$my_hammer = new Hammer();

We can also make different variations of the object as well:
Code:
$my_other_hammer = new Hammer('wood', 2);

Classes "can" be used to namespace functions (as tonanbarbarian explained), which is probably the way CI uses them mostly, but to me the example above fits more closely with the intention behind classes/objects than just "containers".
#6

[eluser]Beren[/eluser]
Encapsulation is also a very useful feature of OOP - by separating how you ask an object to do something...
i.e.
Code:
$image = new Image('file.gif');
$image->resize(100,75);
$image->save_copy('new_file.gif');
...and the actual process that object takes to perform that action, it enables (amongst many other things) much more scope for the developer to improve and refactor their code whilst isolating that redevelopment from the rest of the app.

Yes this could be achieved by procedural coding certainly, however personally speaking I find that since I switched to writing more OOP style code it makes me a better programmer since each discreet object (and also the methods within those objects) perform specific, clearly defined roles. Great procedural programmers can achieve just as much, but alas I was never one of those! OOP helps (IMHO) provide a 'way' of structuring and thinking about one's code that encourages best (or perhaps 'better') practice.

As with everything in life, your mileage my vary!

I think it also depends on the language, OOP is pretty much the only way to write Ruby since it truly embodies 'everything is an object'. PHP is less so and is pretty well suited to both styles of coding (others may have more/better opinions on this). Some languages like Javascript, which is Prototypal, have been 'made' to be more OOP by the frameworks like mootools and jquery - which is both good and bad in that more people know and understand OOP, but then again the Prototypal approach has it's own strengths (and weaknesses).
#7

[eluser]Nick Husher[/eluser]
From Wikipedia: "Object-oriented programming is based on several techniques, including encapsulation, modularity, polymorphism, and inheritance."

Encapsulation: this is the practice hiding raw data in cases where the raw data isn't always important, or would be harmful if modified incorrectly. Let's say you're building a mechanism for storing data for quick access. You could have an array with various search functions applied to it, or you could just store it in a binary search tree and let the user modify it as they please. But then you've tied yourself to that implementation, if you find out later that a BST is significantly inferior to a red-black tree or radix tree, you're stuck reimplementing a ton of code where you assumed that the underlying structure was a BST. If you were using an object, how you're storing the data specifically doesn't matter, you just have a QuickAccess object with an insertData function and a retrieveData function.

Modularity & Polymorphism: This is a practice that allows you to replace one object with another without upsetting the codebase. In a procedural codebase, one piece of the code is often dependent on other pieces of the code existing or operating in a certain way. With OOP, one object doesn't know or care what other objects are doing or how they're doing it, as long as they properly implement a common method of communicating (an interface, in Java terms). One good example is that of a stream reader in Java--the various kinds of stream readers can open HTTP connections, load files, or read user input. If your designing your code for reuse, you might want to use it with different inputs, in which case all you have to do is swap the streamreader in a few places rather than reimplement your code to handle different kinds of connections.

Inheritance: allows you to save yourself the task of repeating code. If you're building a system that has related objects--maybe you're designing a UI library and you have a radio button and a checkbox widget. They're very similar in concept (they both have an 'on' state and an 'off' state, they both have an associated value, etc), so it would be easier to develop one object that implements common functionality and then create two child objects that implement the specific functionality of each than to write two different sets of functions.

There are ways to do all of the above things with clean coding and code conventions in procedural code, but there's less of an incentive to do it. To create shared interfaces and modularty in a language like C takes a fair amount of forethought and documentation, which are things that easily kill the momentum of a project. With a strictly OOP language (like Java), the above principles flows naturally out of the language. There's nothing you can do with an OOP language that you can't do with a non OOP language, but the level of abstraction that it gives you implies a certain quality of coding that's difficult to replicate in a non OOP environment.
#8

[eluser]codex[/eluser]
Ucant & Wired:

I (think I) understand the concept of objects a bit better. You have a class called Animal, and in this class all functions that make an animal an animal are described. You can create instances of the animal class (objects) to create dog, cat etc etc and have all those properties available. Right? If right I understand ;-)
#9

[eluser]thurting[/eluser]
[quote author="codex" date="1201059132"]I still can't see (besides reusability and portability) what the fuss is all about.[/quote]

If you ever have to write a piece of software of any complexity and with a large group of developers, you will see what the fuss is all about.

Honestly, you should grab a book and try to learn about OOP and specifically its use in PHP, as that seems to be your area of interest. If I'm not mistaken, I suggested this to you a while back and you were offended. I don't know why. Get a book, it will help. FYI, one of the friendliest intros to OOP I have seen (written well and on a nice path for beginners) is written by Colin Moock in his excellent books on AS.
#10

[eluser]wiredesignz[/eluser]
@Codex:
Yep, thats it, a class allows you to create functions to describe the Object you wish to represent, but it also contains the data (from a database or where-ever) belonging to the Object.




Theme © iAndrew 2016 - Forum software by © MyBB