M
M
machno2015-02-09 11:14:18
PHP
machno, 2015-02-09 11:14:18

Why is OOP needed?

Actually a subject. I don’t understand why OOP is needed, I write in php / python, I often come across all sorts of classes when working with CMS / Frameworks, but I never write any classes myself, because. I don't understand the benefit at all. Unless the delimitation of the namespace, the rest is only an increase in the number of lines and a deterioration in the readability of the code.

Answer the question

In order to leave comments, you need to log in

11 answer(s)
D
Dmitry, 2015-02-09
@machno

Not everywhere and not always classes are needed. You rightly noticed. BUT! Before deciding that a class is only harmful in a particular place in the code, you need a profiler or other tools that allow you to make such a decision. For example, in Python, a dictionary is much faster than a class with methods.
The feature of OOP is that a person already thinks in classes! We raise our head to the sky and see "The bird is flying", in other words, "The "Fly" method was called on the "Bird" object", but we don't think so hard and for us it's just a "Flying bird".
Remember your childhood and the moments when your parents sent for bread. How did it happen? Perhaps it was like this: "The son object in your field I put the "Task" object with the fields "bread", "chest of drawers" and "100 rubles", in the "result" field I put "Bread". The son object I call the "Buy" method". I don’t think it was like that, it seems to me like this: “Son, take 100 rubles and buy bread.” We implicitly turned to the "Son" object, called the "Take" method and passed the "100 rubles" argument, and we expect the result of the call in the form of the "Bread" value.
Try to transfer the procedural approach to our natural life? ;) Try so to communicate, procedurally. It is very difficult. Because a person is used to thinking with objects! Airplane, cat, horse, tree, etc.
In studying a task, we must first of all ask the question: "What is the condition for completing the task?" and the second, no less important, "What is used to achieve the result?". This is "what is used" as a rule and there are objects.

D
Denis, 2015-02-09
@dklokov

There was a period when the author did not understand exactly how, but taught only because it was required everywhere. Awareness of the need comes with the growth of projects, the growth of the development team. There are projects and works where, in principle, you will not need this knowledge.

V
Volka, 2015-02-19
@ibnteo

To add a lot of unnecessary levels of abstraction, and then climb over megabytes of code, look for where everything is going for a simple HTML page. And so that the sites barely work, slow down on powerful servers even with minimal load, load not in a split second, but often even in tens of seconds. And all this for the sake of the supposedly beautiful code, the repeatability of the code, which is really difficult to understand, there is no one to appreciate its beauty and reuse it, because for this you also need to write documentation, but no one wants to do this.

F
FanatPHP, 2015-02-09
@FanatPHP

An object is objectively more functional than a function.
If you have ever used functions, you must have encountered their inconveniences - the inability to return more than one result, the piling up of parameters, the inability to work with different sets of parameters, and so on.
By replacing the function with an object, all these problems are easily solved.
If you did not write functions, then you need to start with them.

M
Mercury13, 2015-02-09
@Mercury13

I wanted to ask: are you a student? Then I looked: no, webist. Webists really rarely need OOP; if you haven’t messed with tricky support for complex protocols or with complex data models - in memory, not in a database - you can write without OOP and be a successful webist.
For a long time I myself did not understand what these objects were for. The main question is: WHY?
To convey the interaction of a bunch of things. Where there is no interaction, there is no OOP, and you can do, for example, scientific calculations, which few of us are capable of, aerobatics, and generally know nothing about OOP. I remember how Wasserman - the same one, once a technical process programmer - remembered for a long, long time what OOP is.
I suggest starting simple.
1. Object syntax. It was…

iDog : integer;
iDog := SpawnMonster(world, mtDog, x, y);
ChargeAtPlayer(iDog);

It became…
dog : TMonster;
dog := world.SpawnMonster(mtDog, x, y);
dog.ChargeAtPlayer;

Already more beautiful. Yes, and the number of the dog can be accidentally transferred, for example, instead of the number of the weapon; with the TMonster type, this trick will not work.
2. Encapsulation.
This is what we are already thinking about so that function calls cannot bring the object into an “improper” state, and everything that can spoil the object is shoved into private.
3. Abstraction and inheritance. This is already "complex aerobatics." Not the highest is an integral part of the skills of a good programmer, and for 80% of tasks it is not necessary, but in the remaining 20 it improves life a lot. The simplest example. In some 2D game, there is a certain TGameObject, which has virtual Live and Render functions. The first scrolls the cycle of the "life" of the object, the second draws it on the screen. TGameObject can be broken down into TPlayer, TProjectile, TEnemy and TBonus, etc.
Oh yes. OOP doesn't need an object-oriented language and object syntax, it needs object-oriented thinking. For example, Doom was written in C, but in a very, very object style.

V
Vitaly, 2015-02-09
@vt4a2h

So you say that you use ready-made classes to solve some problems ... Great! Now try to implement the same functionality, but without the use of classes (and OOP in general, because these are not only classes, in fact), and then compare the code that you got with the original OOP implementation. Compare in terms of usability, ease of maintenance and acceptance by other developers. You can also compare in terms of testing and ease of adding new functionality.
I think that you will immediately understand why OOP is needed.
PS
Although, here it is possible that you have not yet encountered tasks that need (ok, convenient) to be solved using OOP ... So at the same time you will encounter)

A
AxisPod, 2015-02-09
@AxisPod

It is a design and development methodology. If you want to learn full Zen, read Grady Booch "Object-Oriented Analysis and Design". Or just hammer in and do it through ..., in short, as they did.

E
Egor Alekseev, 2015-02-09
@KingpinRZN

To make it easier to write.

I
Ivan, 2015-02-19
@sait4seo

in a simple and practical way, for example
1) you need to connect a payment to the site
a) write interaction from scratch yourself (expensive and not cost-effective)
b) take a ready-made class if you need to inherit and rewrite some methods (faster and more reliable)
2) take which - a library (or even CMS), for example bibl. IdiORM, do not change the core code (the core is the main classes), but inherit into your class, rewrite several necessary methods, in 5-10 years your project code will not become obsolete, since the core can be updated without breaking the project, and all the jambs and vulnerabilities in 10 years you will be eliminated by updating the library or cms
3) OPP allow you to develop faster, for example, based on ready-made libraries and frameworks, inserting records into tables may look like this

$obj = new myTable();
$obj->name = 'Ivan';
$obj->phone = '111-111-111';
$obj->save(); 
//этот код нагляден и универсален для sql и  nosql баз и вообще любых хранилищ, не придётся переписывать проект целиком при смене базы

in a functional style, this cannot be implemented
. Unfortunately, not everything that is implemented in OOP is implemented with high quality. There are examples of OOP abuse and vice versa complicating the understanding of the code, but this does not mean that you should not use the OOP approach.

A
Alexander Gorbatovsky, 2015-02-19
@dom3d

I programmed in C for 6 years d 1993-1999.
And then he switched to C ++ and regretted that he had not known about the existence of the C ++ language before.
The best things about the C++ language are inheritance and virtual functions.
In addition, private class members improve reliability and prevent bugs.
The worst thing about C programming is the use of global variables. You do not know where it can change and it is too difficult to change the behavior of the program. And if its change to a variable is done in one place (in the class), then the behavior of the class is very easily modified.
And of course, it is very convenient when the methods of working with an object (class) are stored in one place.

M
m-haritonov, 2017-03-22
@m-haritonov

In PHP, OOP is needed when multiple functions need to access shared variables.
Without OOP, you would have to write code like:

<?php
namespace something1 {
    function set($value) {
        $GLOBALS['something1']['someVariable'] = $value;
    }

    function get() {
        return $GLOBALS['something1']['someVariable'];
    }
}

namespace something2 {
    function set($value) {
        $GLOBALS['something2']['someVariable'] = $value;
    }

    function get() {
        return $GLOBALS['something2']['someVariable'];
    }
}

namespace {
    \something1\set(1);
    \something2\set(2);

    print \something1\get();
    print \something2\get();
}

and:
<?php
namespace something {
    function set($instanceName, $value) {
        $GLOBALS[$instanceName]['someVariable'] = $value;
    }

    function get($instanceName) {
        return $GLOBALS[$instanceName]['someVariable'];
    }
}

namespace {
    \something\set('instance1', 1);
    \something\set('instance2', 2);

    print \something\get('instance1');
    print \something\get('instance2');
}

With OOP you can write:
<?php
class Something1 {
    private $someVariable;

    function set($value) {
        $this->someVariable = $value;
    }

    function get() {
        return $this->someVariable;
    }
}

class Something2 {
    private $someVariable;

    function set($value) {
        $this->someVariable = $value;
    }

    function get() {
        return $this->someVariable;
    }
}

$something1 = new Something1();
$something1->set(1);

$something2 = new Something2();
$something2->set(2);

print $something1->get();
print $something2->get();

and:
<?php
class Something {
    private $someVariable;

    function set($value) {
        $this->someVariable = $value;
    }

    function get() {
        return $this->someVariable;
    }
}

$something1 = new Something();
$something1->set(1);

$something2 = new Something();
$something2->set(2);

print $something1->get();
print $something2->get();

If we take a web application in php, the task of which is to generate html code (which will be sent to the browser) and provide the ability to divide the application into modules, then OOP as the basis of such an application may be redundant, because all modules will perform only one action (return html code) and they will not need to save state between calls, because. the result of the module will no longer change during the call to the web application (the module will generate html and send it to the browser, and in a browser where OOP is used in javascript, this html code will already change during operation).
Without OOP, the server side of a web application might look like this:
<?php
namespace modules {
    function layout($title, $contentHtml, $footerHtml) {
        return '<!doctype html>
            <html>
            <head>
                <meta charset="utf-8">
                <title>' . htmlspecialchars($title) .'</title>
            </head>
            <body>
                <div class="content">
                    ' . $contentHtml . '
                </div>

                <div class="footer">
                    ' . $footerHtml . '
                </div>
            </body>
            </html>
        ';
    }

    function contacts() {
        return 'Адрес: ..., телефон: ...';
    }

    function copyright() {
        return '© Моя фирма';
    }
}

namespace {
    if (strtok($_SERVER['REQUEST_URI'], '?') === '/contacts') {
        print \modules\layout('Контакты', \modules\contacts(), \modules\copyright());
    }
}

And with OOP it’s like this (as you can see, the modules were implemented as classes that contain only 1 method, i.e. the class is redundant here):
<?php
namespace modules {
    class Layout {
        public $title;
        public $contentHtml;
        public $footerHtml;

        public function execute() {
            return '<!doctype html>
                <html>
                <head>
                    <meta charset="utf-8">
                    <title>' . htmlspecialchars($this->title) .'</title>
                </head>
                <body>
                    <div class="content">
                        ' . $this->contentHtml . '
                    </div>

                    <div class="footer">
                        ' . $this->footerHtml . '
                    </div>
                </body>
                </html>
            ';
        }
    }

    class Contacts {
        public function execute() {
            return 'Адрес: ..., телефон: ...';
        }
    }

    class Copyright {
        public function execute() {
            return '© Моя фирма';
        }
    }
}

namespace {
    if (strtok($_SERVER['REQUEST_URI'], '?') === '/contacts') {
        $layout = new \modules\Layout();
        $layout->title = 'Контакты';
        $layout->contentHtml = (new \modules\Contacts())->execute();
        $layout->footerHtml = (new \modules\Copyright())->execute();

        print $layout->execute();
    }
}

But if PHP were used to develop not a server, but a client application, where the generated visual part would be stored in RAM for a long time and user actions would change it, then using OOP could be convenient. But then again, OOP is just a way of organizing code, which is based on all the same subroutines (methods), and this way of organizing may not be to everyone's liking.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question