Answer the question
In order to leave comments, you need to log in
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
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.
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.
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.
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.
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);
dog : TMonster;
dog := world.SpawnMonster(mtDog, x, y);
dog.ChargeAtPlayer;
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)
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.
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 баз и вообще любых хранилищ, не придётся переписывать проект целиком при смене базы
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.
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();
}
<?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');
}
<?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();
<?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();
<?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());
}
}
<?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();
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question