САМЫЕ ЧАСТЫЕ ЗАБЛУЖДЕНИЯ ООП

ExtremeCode
9 Oct 201919:37

Summary

TLDRВ этом видео представлен обзор концепций объектно-ориентированного программирования (ООП), включая распространенные заблуждения и их устранение. Автор упоминает два типа ООП: 'желаемый', основанный на первоначальных идеях Алан Кея и 'текущий', распространённый в языках C++, C# и Java. Обсуждается важность парадигм ООП, таких как инкапсуляция, наследование, полиморфизм и абстракция, а также их различия в статически и динамически типизированных языках. Видео также критикует некоторые интерпретации ООП и подчёркивает их наилучший и наименьший вклад в различные языки программирования.

Takeaways

  • 🌐 ОOP (Object-Oriented Programming) доминирует в мире программирования и используется во многих языках, таких как Java, C#, C++ и Python.
  • 😅 Некоторые программисты могут не одобрять OOP, но рынок считает его необходимым и важным для программирования.
  • 👨‍🎓 Аллан Кей, изобретатель ООП, вдохновился клетками живых организмов при создании концепции и языка программирования Smalltalk.
  • 📈 Java, благодаря маркетинговой политике компаний, превзошла Smalltalk в популярности, хотя последний считался более передовым.
  • 🤔 ОOP имеет разные интерпретации и реализации, включая "желательную" (как в Smalltalk) и "текущую" (как в C++, C# и Java).
  • 🔐 Принципы ООП, как изначально задуманы Алланом Кеем: объекты, отправка сообщений, наследование, поведение определяется классом, все — это объекты.
  • 📦 Энкапсуляция — это объединение данных и функций, управляющих данными, в один компонент, и механизм языка для ограничения доступности некоторых компонентов программы.
  • 👪 Наследование позволяет описывать новый класс на основе существующего, но в "желательном" ООП, как в JavaScript, родитель является уже сформированным объектом, а не классом.
  • 🔄 Полиморфизм — важная черта ООП, позволяет объектам иметь разные реализации для одинаковых типов и в языках с динамической типизацией ощущается естественнее.
  • 📝 Абстракция — выделение важных характеристик объектов для решения конкретной задачи, иногда смешивается с энкапсуляцией из-за вовлечения информации скрытия.
  • 📢 Отправка сообщений — процесс вызова метода одного объекта другим, важный в Objective C, где при отсутствии метода не возникает исключение.

Q & A

  • Что такое объектно-ориентированное программирование (ООП) и почему оно доминирует в мире программирования?

    -Объектно-ориентированное программирование (ООП) - это парадигма программирования, основанная на использовании объектов, которые содержат данные в виде полей и код в виде методов. Оно доминирует, потому что многие языки программирования, такие как Java, C# и C++, созданы с целью быть объектно-ориентированными, и ООП предлагает мощные механизмы для решения сложных задач.

  • Какие различия между 'желательным' и 'текущим' ООП?

    -Текущий ООП - это то, что в настоящее время распространено и используется в языках C++, C# и Java. Желательный ООП, с точки зрения его изобрелителя Алан Кея, отражает первоначальные концепции, где всё является объектом, и это реализовано в языках с динамическим типированием, таких как Smalltalk и Objective-C.

  • Какие языки программирования были упомянуты в скрипте как примеры объектно-ориентированных?

    -В скрипте упомянуты языки Java, C#, C++, PHP, JavaScript и Python как примеры языков, которые в той или иной степени поддерживают ООП.

  • Что такое статическое и динамическое типирование, и как они влияют на ООП?

    -Статическое типирование - это когда типы переменных определяются во время компиляции, в то время как динамическое типирование определяется во время выполнения программы. В языках с статическим типированием могут быть ограничения при работе с ООП, и могут потребоваться специальные механизмы для преодоления этих ограничений.

  • Какие основные принципы ООП были изложены Аланом Кеем?

    -Алан Кей определил следующие основные принципы ООП: объект - основная единица системы, отправка сообщений - единственный способ обмена информацией между объектами, каждый объект связан с классом, поведение объекта определяется его классом, классы наследуют функциональность от своих предков, и все является объектом.

  • Что такое парадигма 'инкапсуляции' в ООП, и как она понимается?

    -Инкапсуляция - это парадигма, которая объединяет данные и функции, управляющие этими данными, в одну компоненту. Она также может быть механизмом языка, который ограничивает доступ к некоторым компонентам программы другими.

  • В чем заключается разница между инкапсуляцией и информационным скрытием?

    -Инкапсуляция предоставляет возможность скрыть информацию, но не является самим информационным скрытием. Информационное скрытие - это когда детали реализации объекта скрыты от пользователя, в то время как инкапсуляция - это процесс объединения данных и методов в рамках одного класса.

  • Что такое наследование в ООП, и как оно используется?

    -Наследование - это механизм языка, который позволяет описать новый класс на основе существующего. Это позволяет создавать иерархии классов и обеспечивает полиморфизм, но само по себе оно может быть не только бесполезным, но и опасным из-за сильного связывания между классами.

  • Какие проблемы могут быть связаны с использованием наследования в ООП?

    -Наследование может привести к проблемам с изменением базового класса, так как это может негативно сказаться на всех производных классах. Это может привести к сложностям в поддержке и разработке кода.

  • Что такое полиморфизм в ООП, и как он реализуется?

    -Полиморфизм - это парадигма, которая позволяет различным объектам с одинаковым интерфейсом выполнять разные действия. Он может быть реализован через наследование и переопределение методов, а также через механизмы, такие как generics в C# или методы с разными аргументами в C++.

  • Какие различные формы полиморфизма упоминаются в скрипте?

    -В скрипте упоминаются 'Ad Hoc' полиморфизм (методы с одинаковым именем, но разными аргументами), параметрический полиморфизм (генерики в C#) и субтиповый полиморфизм (наследование и приведение типов).

  • Что такое абстракция в ООП, и как она влияет на проектирование классов?

    -Абстракция - это парадигма, которая подчеркивает важные характеристики объектов, скрывая ненужные детали. Это позволяет сосредоточиться на решении конкретной задачи с минимальным набором характеристик объекта.

  • Почему парадигма 'отправка сообщений' может быть важнее, чем кажется?

    -Отправка сообщений - это процесс, когда один объект вызывает метод у другого объекта. В языках с динамическим типированием, таких как Objective-C, отсутствие определенного метода у объекта не приводит к ошибке, что делает систему более гибкой и устойчивой к ошибкам.

  • Что такое 'кодовая переиспользованость' и почему она может быть не всегда включена в список парадигм ООП?

    -Кодовая переиспользуемость подразумевает, что все предыдущие парадигмы должны быть направлены на уменьшение повторного написания кода. Некоторые авторы считают, что это очевидность и не нуждается в отдельном упоминании как парадигма.

  • Какие дополнительные концепции, кроме основных парадигм ООП, упоминались в скрипте?

    -В скрипте упоминаются концепции из SOLID, которые иногда добавляются к основным парадигмам ООП, хотя их статус как отдельных парадигм для ООП может быть предметом спора.

Outlines

00:00

😀 Объектно-ориентированное программирование (ООП) как доминирующий концепция

В первом параграфе автор вводит тему видео - объектно-ориентированное программирование (ООП), которое является доминирующей концепцией в мире программирования. Он подчёркивает, что ООП используется повсюду, и если вы не умеете работать с ООП, то вам не требуются на рынке. Автор также упоминает разнообразие источников, которые отличаются в количестве представленных парадигм ООП, от 3 до 9, и заметает о том, что в видео будут рассмотрены как распространённые заблуждения, так и исходные концепции ООП, созданные Аланом Каем. В заключение автор вводит тему использования ООП как в языках с динамическим, так и статическим типированием.

05:00

😔 Различия между 'желательным' и 'текущим' ООП, а также проблемы с наследованием

Второй параграф посвящён различиям между 'желательным' и 'текущим' ООП, где 'текущее' распространено в языках C++, C# и Java, а 'желательное' - в Smalltalk и его концептуальных продолжениях, таких как Objective C. Автор критикует текущую реализацию наследования за его опасность и сильную связь между классами, которая может привести к проблемам при изменении базового класса. Он также упоминает, что в 'желательном' ООП наследование работает по-другому, напоминающе прототипное наследование в JavaScript, где родитель - это уже сформированный объект, а не класс.

10:03

😡 Полиморфизм как основной парадигм в существующем ООП и его реализация в различных языках

Третий параграф фокусируется на полиморфизме, который считается основной особенностью существующего ООП и второстепенной в желаемом ООП. Автор объясняет различные формы полиморфизма в языках с статическим типированием, таких как C#, включая методовую перегрузку (Ad Hoc полиморфизм), параметризованный полиморфизм (generics) и подтипный полиморфизм (наследование и приведение типов). Он подчёркивает, что без полиморфизма ООП в статически типизированных языках был бы незначителен. В языках с динамическим типированием, таким как JavaScript, полиморфизм чувствуется естественно, и его можно использовать без особых затруднений.

15:06

🤔 Абстракция и отправная точка сообщений в ООП

В четвёртом параграфе автор обсуждает абстракцию как парадигму, часто путающуюся с энкапсуляцией из-за вовлечения скрытых данных. Он выражает усталость от постоянного путаницывания этих двух понятий. Автор утверждает, что абстракция - это выделение важных характеристик объектов для решения конкретной задачи, используя минимально необходимый набор характеристик. Он также вводит концепцию отправной точки сообщений, которая является общей для всех объектов в ООП, но реализуется по-разному в языках, таких как Objective C, где отсутствие метода не вызывает исключений.

😒 Смысл и место кодовой_REUSE в парадигмах ООП

В заключительном параграфе автор обсуждает концепцию кодовой_REUSE в качестве парадигмы ООП, которая, по его мнению, очевидна и не требует отдельного упоминания. Он выражает непонимание того, почему эта концепция включается в обсуждение парадигм, так как все предыдущие парадигмы должны быть направлены на достижение кодовой_REUSE. Автор также упоминает о том, что некоторые источники предлагают расширить число парадигм ООП, включая принципы SOLID, но он считает, что это выходит за рамки классической ООП. В заключение автор призывает зрителей подписаться на канал и нажимать на колокольчик, указывая, что ссылки на материалы для видео будут доступны в описании.

Mindmap

Keywords

💡Объектно-ориентированное программирование (OOP)

Объектно-ориентированное программирование (OOP) является основным подходом в современном программировании, который строится на концепции объектов. В видео упоминается, что OOP доминирует в мировом сообществе программистов и многие языки программирования созданы с целью поддержки OOP, такие как Java, C# и C++. В контексте видео, OOP представлен как неотъемлемая часть современного программирования, и автор обсуждает различные парадигмы и концепции OOP, включая их преимущества и недостатки.

💡Алан Кей (Alan Kay)

Алан Кей - известный американский ученый и разработчик компьютеров, который считается одним из отцов объектно-ориентированного программирования. Автор видео упоминает его как создателя концепций OOP, который был вдохновлен биологической моделью клетки при создании системы объектов. Кей также является автором языка программирования Smalltalk, который в свое время считался передовым и вдохновляющим для будущего развития OOP.

💡Энкапсуляция

Энкапсуляция - это один из ключевых принципов OOP, который описывает объединение данных и функций, обрабатывающих эти данные, в единый компонент. В видео рассматриваются разные интерпретации энкапсуляции, включая механизм языка для ограничения доступности некоторых компонентов программы другим компонентам. Автор видео использует примеры из C# для иллюстрации этой концепции и обсуждает ее значение для защиты и организации кода.

💡Наследование

Наследование в контексте OOP позволяет определять новый класс на основе существующего, что облегчает повторное использование кода и создание иерархий объектов. В видео автор критикует текущую реализацию наследования в языках с статическим типизированием, таких как Java и C#, и сравнивает ее с прототипным наследованием в JavaScript, которое, по его мнению, более близко к идеалам 'желательного' OOP.

💡Полиморфизм

Полиморфизм в OOP означает возможность одного и того же интерфейса для объектов разных классов. В видео рассматриваются разные формы полиморфизма, такие как ад-хоц, параметрический и субтипный полиморфизм. Автор видео обсуждает, как полиморфизм позволяет объектам решать разные задачи на основе их иерархии наследования и как он является ключевым для реализации OOP в языках с статическим типизированием.

💡Абстракция

Абстракция в OOP - это процесс выделения и выражения только важных характеристик объектов, скрытия незначительных деталей. В видео автор упоминает, что абстракция часто путается с энкапсуляцией из-за вовлечения информации о скрытии, но она является важной частью OOP, позволяющей сосредоточиться на решении задачи с минимальным набором характеристик.

💡Сообщения (Message sending)

Сообщения в OOP - это процесс вызова метода у другого объекта. Автор видео отмечает, что в реализациях OOP языков C++, Java и C# это достаточно просто и является общим знанием, однако в Objective C и других языках с динамическими типами, сообщения обрабатываются по-другому, что позволяет более гибкой работе с объектами, например, без возникновения исключений при вызове метода у null-объекта.

💡Реализация (Implementation)

Реализация в контексте OOP относится к способу воплощения концепций и парадигм OOP в языках программирования. В видео автор сравнивает реализации OOP в разных языках, указывая на различия в подходах к сообщениям, наследованию и полиморфизму, и как эти различия влияют на эффективность и понятие объектно-ориентированности.

💡Статическое и динамическое типизирование

Статическое и динамическое типизирование - это два подхода к определению типов данных в языках программирования. В видео упоминается, что языки с статическим типизированием, такие как Java и C#, имеют определенные ограничения и особенности в реализации OOP, в отличие от языков с динамическим типизированием, таких как JavaScript и Python, где OOP может выглядеть и функционировать по-другому.

💡Прототипное наследование

Прототипное наследование - это механизм, при котором новые объекты создаются как копии существующих, вместо использования классов в качестве шаблонов. Автор видео считает, что прототипное наследование, как в JavaScript, более близко к идеалам 'желательного' OOP, предложенных Аланом Кеем, и обсуждает его преимущества перед классовым наследованием.

Highlights

OOP is widely used in programming, with more languages designed to be Object-Oriented than not.

Languages like Java, C#, and C++ are inherently Object-Oriented, while others like JavaScript and Python have different approaches.

Static typing in languages can impose limitations on OOP concepts, requiring specific mechanisms to overcome them.

The 'desired' and 'current' types of OOP differ, with the 'current' being popular in C++, C#, and Java, and the 'desired' in Smalltalk and its successors.

Alan Kay, the inventor of OOP, was inspired by the cellular structure of living organisms to create the Smalltalk language.

Java's marketing success overshadowed Smalltalk, despite the latter's innovative OOP concepts.

David West criticizes Java's OOP as a marketing move, arguing it diverges from the original OOP principles.

OOP principles by Alan Kay emphasize that every object is the basic unit and can send messages, with behavior defined by its class.

In Smalltalk, even basic constructs like loops are considered objects, demonstrating the 'everything is an object' principle.

Encapsulation in OOP is often misunderstood, with two interpretations that are actually complementary, not contradictory.

Inheritance in OOP is problematic due to its potential to create strong bindings and limit code flexibility.

Polymorphism is central to 'current' OOP, allowing for method overriding and upcasting, which is essential in statically typed languages.

Dynamic typing languages like JavaScript can implement 'desired' OOP principles more naturally, including prototype inheritance.

Abstraction in OOP is about highlighting important characteristics of objects, often confused with encapsulation due to information hiding.

Message sending as a paradigm is often overlooked but is fundamental to the 'desired' OOP, especially in languages like Objective C.

Code reuse is considered by some as a paradigm, but it's more of an overarching goal influenced by all other OOP principles.

The video discusses the varying interpretations and applications of OOP paradigms across different programming languages and authors.

Transcripts

play00:00

OOP happens to be

play00:01

dominating in the world of programming conceptions

play00:04

It's easier to enumerate places where it's not used

play00:07

than vice-versa, and if you can't OOP

play00:10

then nobody needs you

play00:12

And yes, i understand that every time i say something like this,

play00:15

some snowflake Cnile or functiANAL programmer is bursting in tears

play00:18

But it's not my fault

play00:21

that the market has decided with it's hairy hand

play00:22

that Object-Oriented Programming is super necessary.

play00:25

And in this video, not only i'll teach you about OOP,

play00:28

but will also highlight the most widespread misconceptions

play00:31

and will sort them out. I know i'm not the only one

play00:34

who notices that different sources have different amounts of paradigms, from 3 to even 9, for example.

play00:39

And most importantly, i'll be guided by the greatest

play00:41

and provide sources,

play00:44

so you don't just blindly trust me, but have the proofs instead.

play00:47

It's just that without proofs,

play00:48

my mom is turned over in the comments.

play00:51

Now let's start.

play00:52

First of all, here's a tiny warning:

play00:55

Entire programming languages are made with the intention of being Object-Oriented

play00:59

for example Java, C#

play01:02

C++ in general was made to expand upon good ol' C

play01:04

with the delicious moist OOP.

play01:07

And i'd like to remind you of PHP,

play01:10

Javascript and Plebthon.. Ooops, sorry

play01:13

wrong word,

play01:14

the script was too vague, I meant to say

play01:16

"python"

play01:17

Why not very enthusiastic?

play01:19

Because of the typing.

play01:21

In language with static typing,

play01:23

there are some limitations, which need to be considered

play01:25

and there even are certain mechanics that help fight these limitaitons.

play01:30

This is why trying to understand OOP using JavaScript

play01:34

is like licking ants' butts -

play01:35

It's kind of sour and kind of perfect, but at the same time the green round candy gives you the better feels.

play01:42

It doesn't mean that pythons and JSes are bad languages,

play01:46

It just means that things are a lil' bit different there.

play01:49

Nevertheless, in this video we'll be considering

play01:51

both languages with dynamic typing

play01:53

and languages with static typing.

play01:55

Now, to begin i have good news for ya.

play01:58

OOP is not one, there's actually a fuck ton.

play02:01

Everyone realizes it the way they want.

play02:03

But i want to highlight 2 types of OOP:

play02:06

The "desired" and the "current".

play02:08

The "current" is the most popular thing right now,

play02:12

and it's the thing that's smeared all across C++, C# and Java,

play02:15

and the "desired" is the thing wanted by the creator of the initial OOP concepts.

play02:18

and it's smeared all across smalltalk and it's conceptual successors like objective c. (Tried to smear it, but didn't complete it)

play02:24

By the way, the inventor of OOP is

play02:27

Alan Kay.

play02:28

This dude other than programming also has PhDs in biology and philosophy.

play02:32

Additionally, he professionally played the guitar,

play02:35

I wouldn't even wonder if he had a knee-long cock.

play02:37

To put it simple, Alan Kay is the chaddest chad.

play02:40

It's said that when he was inventing OOP,

play02:43

he was inspired by the cells of the living organism

play02:46

Like, the system seems cool, werks, reconstructs relatively fine,

play02:49

why not yoink it from big mama nature?

play02:53

And, inspired by this idea, he created the Smalltalk programming language

play02:56

which, at that time, was considered the ultimate red pill

play02:59

that was way ahead of its time.

play03:01

But, it just so happened that Java appeared

play03:04

and f*cking obliterated Smalltalk.

play03:06

Because of the marketing policy of the companies that developed these languages,

play03:10

Java skyrocketed like Bitcoin at the fall of 2017

play03:13

While void was sent to the trash bin.

play03:15

Not bad, market, not bad.

play03:17

First Smalltalk, then Star Wars, then the Vanilla Coke,

play03:21

what's the next nice thing you're gonna take away, the women from my porn?

play03:25

Actually, everything would've been fine

play03:27

if not for one nuance:

play03:29

There's this man, David West

play03:32

No, not this one,

play03:33

this one.

play03:34

This man is most known for his bookies about OOP,

play03:38

and a little less known for spinning functional and java programmers' moms

play03:41

on his c*ck.

play03:44

All that because, in his opinion, OOP in java is

play03:47

OOP of the smoker and it's all just a marketing move.

play03:50

In real OOP, everything needs to happen differently

play03:53

And to be clear what's wrong,

play03:55

We'll need to remember basic OOP principles

play03:58

In the form that was originally planned by Alan Kay

play04:03

An Object is the basic unit

play04:05

of an Object-oriented system.

play04:08

Message sending - the only way of exchanging information between objects.

play04:13

Every Object is related to some class.

play04:16

The Object's behaviour is defined by it's class.

play04:19

Classes inherit their functionality from their ancestor.

play04:23

Everything is an Object.

play04:25

Literally everything.

play04:27

And Rubyists are now probably waving their heads like

play04:29

"yes everything's an Object, everything's an Object in Ruby too,

play04:32

even numbers and strings, we're so cool"

play04:36

Except this is not enough,

play04:37

in Smalltalk, for example, even basic constructs

play04:40

and loops are Objects.

play04:42

Now this i get - everything is an Object.

play04:44

And, resulting from these principles, there appeared 6 paradigms,

play04:48

3 of which are often politely forgotten.

play04:52

First paradigm - encapsulation.

play04:55

It's one of the most misunderstood

play04:57

and poorly interpreted paradigms of OOP.

play05:00

It's all because it has 2 basic interpretations,

play05:03

which differ from source to source

play05:06

First interpretation:

play05:08

Encapsulation - the unification of data and functions

play05:11

which control this data into a single component.

play05:15

Second interpretation:

play05:17

Encapsulation - mechanism of the language that allows

play05:20

to restrict the accessibility of some components of the program to the others.

play05:24

And here's an example in C#:

play05:28

It's corresponding to both the first, as well as the second interpretations.

play05:32

I've gotten to see some shitshows about which interpretation is the right one,

play05:36

and which is for autists, and why at all

play05:38

there happened to be 2 interpretations

play05:40

Actually, such shitshows are quite laughable,

play05:43

it's the same as one group tries to prove that 1 < 2

play05:46

and the other proving that 3 > 2

play05:49

Both are right, it's just the accents that are placed slightly differently.

play05:53

The interpretations don't contradict themselves!

play05:56

When encapsulating, both unification of data and functions that manipulate this data happens

play06:00

and, in some cases, access of certain components to others is restricted.

play06:05

Why only in some cases?

play06:06

Because, for example, certain languages provide a mechanism for reflection.

play06:10

Because of it, you can literally invade any class.

play06:13

And change there even private fields.

play06:15

I understand that several people are typing about "muh reflection doesn't count"

play06:19

Well, maybe it doesn't count ¯\_(ツ)_/¯

play06:21

Herbert Schildt has the same opinion about encapsulation.

play06:24

Here's a quote from his book. (in russian of course :])

play06:27

Anyway, encapsulation can't be information hiding.

play06:31

It's just that some people in comments

play06:33

copy-pasted definitions close to

play06:35

either Shildt's definition

play06:36

or definitions closer to the second interpretation

play06:39

and are shitting about it being information hiding.

play06:41

Now read closely motherf*ckers

play06:43

Encapsulation provides information hiding,

play06:46

but is not information hiding itself.

play06:48

I can provide some shit in a hater's face.

play06:50

Does that mean that i'm a piece of shit?

play06:52

No.

play06:53

And if ANYONE f*ckin' says in the comments that encapsulation is hiding...

play06:58

Then immediately call Elon Musk, because on the traction of my

play07:01

flaming ass he'll be able to reach the stratosphere faster, then

play07:04

on f*cking falcon heavy.

play07:06

and

play07:06

Here's some more proof

play07:08

Even Steve McConnell separates these 2 concepts.

play07:11

Hiding and encapsulation.

play07:13

yes, if you open any adequate OOP author's book

play07:17

the concepts of hiding and encapsulation are properly separated.

play07:22

Herbert Schildt might not be the widest accepted OOP genius of this world,

play07:25

but if you want to get fundamental OOP knowledge

play07:29

you can read Meyer's bookie

play07:31

"Object-oriented Software Construction".

play07:35

And yes, encapsulation sometimes disappears

play07:38

from the general list of OOP paradigms.

play07:41

For example, it happens in Mitchell's book

play07:43

"Concepts in programming languages"

play07:45

why?

play07:46

Because he just wanted to throw it the f*ck away.

play07:50

Well, he got rid of it.

play07:51

Now let's transition to the second paradigm - inheritance.

play07:55

Well, here it's easier with interpretations.

play07:58

Maybe.

play07:59

Inheritance - is the mechanism of a language that allows description of a new class based on an existing one

play08:01

that allows description of a new class

play08:03

based on an existing one

play08:05

In C# code it looks roughly like this:

play08:09

In reality, this paradigm is also problematic

play08:12

For example, a lot of people, when defining the interpretation,

play08:14

say it helps with code reuse

play08:18

Just so they don't need to repeat the definition of a method

play08:21

they can just smear themselves with inheritance and everything should be ok,

play08:24

even though it can be achieved through other means.

play08:27

(for example: with the help of agregation and composition)

play08:28

Actually, in current OOP,

play08:30

inheritance is needed just to form hierarchies of familiar objects.

play08:34

And open the gates for polymorphism.

play08:37

Just by itself, it's utterly f*cking useless, and even dangerous

play08:40

because it's the reason of a strong binding

play08:44

If speaking simpler, you can get a parent class

play08:47

That has 2000 children

play08:49

And you'll be afraid to add changes to the base class

play08:52

just because it might cause unwanted influence on the children.

play08:57

And i don't only mean classes-inheritors

play09:00

but your personal children too.

play09:02

Because if you'll add some this in prod and it'll cause problems

play09:06

then your colleagues might want to apply some force on your buns

play09:10

In "desired" OOP inheritance, in general,

play09:12

should work a little bit different.

play09:14

Speaking concretely, it should work like

play09:16

prototyped inheritance in JavaScript.

play09:21

There, the parent is not a class

play09:23

but an exactly formed object.

play09:25

Naturally, in JavaScript, the parent Object can be modified on the way

play09:29

adding some little properties and all that kind of stuff,

play09:33

which gives this system additional possibilities.

play09:36

Of course, this is only possible due to JS's dynamic nature,

play09:39

desired OOP should, in general, only work with

play09:42

languages that have dynamic typing,

play09:45

even Alan Kay wrote about this in his letter.

play09:48

Link to this letter will be you know where.

play09:51

You know what the funniest about this?

play09:52

In JS standard ES 6 they added

play09:56

default #-like classes with the possibility of inheritance

play10:00

Still can't understand why was this added

play10:03

if in our little JS world everything was fine even without it.

play10:06

By the way, inheritance is the most persistent paradigm

play10:09

it's almost never thrown out of the shared list.

play10:14

Third paradigm: Polymorphism

play10:17

And here comes the slaughtering,

play10:20

because polymorphism is thought of as the main feature of the "existing" OOP

play10:24

And a secondary feature of the "desired" OOP

play10:27

You can't get away with with just the definition,

play10:29

simply because in languages like C#

play10:31

polymorphism has several forms.

play10:34

"Intentional polymorphism" or Ad Hoc polymorphysm

play10:38

in folklore, shittymorphism (because it's sometimes hated)

play10:40

In C#, it's represented with method overloading.

play10:43

Like when you define several methods

play10:45

with the same names

play10:47

but with different argument types.

play10:50

Parametric polymorphism,

play10:52

which in C# is represented by generics.

play10:55

And subtype polymorphism

play10:57

that is achieved with mechanisms like inheritance and upcasting.

play11:01

The last one is the one we're interested in.

play11:04

Because subtype polymorphism is meant when discussing OOP

play11:08

In languages with static typing, without polymorphism in it's current form

play11:12

our OOP would've ended here.

play11:14

And would be totally insignifficant.

play11:18

Well, maybe only, at max, put code in modules ¯\_(ツ)_/¯

play11:21

Wouldn't be so cool, would it?

play11:22

But clever men saved the situation

play11:25

they sat

play11:26

they thought

play11:27

and came up how to give the possibility of different realisations

play11:31

to similar types that have obvious inheritance hierarches

play11:36

This is why with the help of

play11:38

method overriding and upcasting

play11:41

our objects can solve different tasks

play11:44

Sounds scary, but in fact it's quite easy.

play11:47

Here's how a simple logging system works in C#

play11:50

We have a hierarchy of classes

play11:52

whose task is to log all kinds of shit,

play11:56

one realisation logs to console,

play11:59

another one writes it to a file

play12:00

and the third one sends the log to the deepest deeps of the internet.

play12:03

And, during the execution of the program,

play12:04

the user decides himself which realisation he likes more

play12:09

Well if in languages with static typing

play12:12

it wouldn't be possible to program without polymorphism,

play12:15

then in languages with dynamic typing

play12:17

we could go crazy and just change methods during runtime

play12:22

In general, this kind of code in JS

play12:23

Is considered a manifestation of parametrized polymorphism

play12:28

With dynamic typing,

play12:29

polymorphism feels so natural

play12:32

that you use it without thinking,

play12:34

And all of that while in languages with static typing

play12:37

it's easier to suck your own c*ck

play12:38

then to get the hang of polymorphism.

play12:41

This is why JavaStrippers that getting into C# can't breathe with their full chest

play12:45

they're suffocated by static typing.

play12:48

You can easily understand how Ad Hoc polymorphism

play12:51

and parametrized polymorphism work,

play12:54

but subtype polymorphism is a lot tougher

play12:58

For me, i realized how it works

play13:00

only after i tried to learn patterns

play13:03

and when i understood how the "Strategy" pattern works

play13:06

i understood why you even need subtype polymorphism

play13:09

and interfaces.

play13:10

We have a video about the strategy pattern, btw. [I haven't subbed that one and i won't.]

play13:14

[God subbing is hard, why did i even start this?]

play13:15

The link to it will be you know where.

play13:18

Since we're this far,

play13:20

let me show you one interesting thingie

play13:24

How can we call Test() after upcasting?

play13:27

We can't. Did it disappear?

play13:30

Not really, because it's called through Test2().

play13:33

Did the method Test() become private from public?

play13:38

That's true, what's our conclusion?

play13:40

Polymorphism provides information hiding.

play13:43

Doesn't it remind you of anything?

play13:45

Polymorphism, just like inheritance,

play13:47

never leaves the general list of OOP paradigms.

play13:50

The only thing that usually changes is it's importance degree,

play13:53

depending on the language's type system.

play13:55

For example, in python context it's "eh some kind of polymorphism"

play14:00

But in C# context it's "Wowie, polymorphism!"

play14:04

4th Paradigm: Abstraction

play14:07

[*Polymorphism beats guy*] ["it can't be worse"] [*abstraction comes in*]

play14:07

Quite interesting paradigm.

play14:09

Abstraction is often misunderstood and confused with encapsulation

play14:13

just because f*cking information hiding is involved.

play14:16

I'm fucking sick of it already.

play14:19

Abstraction says that we should highlight the important characteristicts of objects

play14:22

The main meaning of this is

play14:25

depending on use the minimal necessary characteristics kit

play14:31

to solve the given problem.

play14:35

And it's confused with encapsulation

play14:37

because both indirectly influence the formation

play14:40

of our future type's public interface.

play14:43

Actually, abstraction is an important part of OOP.

play14:46

But dude it's so trivial that i wouldn't extract it into a separate paradigm.

play14:52

And a lot of book authors do so.

play14:55

Yeah, abstraction may not be mentioned at all.

play14:58

Or they can extract a separate small definition

play15:01

and not relate it to OOP paradigms

play15:05

Personally, i don't remember abstraction to be delivered as an entire paradigm

play15:10

while reading the books in preparation of this video,

play15:14

unlike all sorts of internet articles and wikis i've read,

play15:18

where the enthusiasm about this topic might seem unhealthy,

play15:21

while, in analagous english sources

play15:23

this kind of shit doesn't happen.

play15:26

Next paradigm: Message sending

play15:30

This is just a fancy way of calling the process

play15:33

of one object calling a method of other object.

play15:36

And yes, that's literally it,

play15:39

if we're talking about the OOP realisation of languages like C++, Java and C#

play15:43

Not so cool, and like, common sense,

play15:47

this is why this paradigm is rarely talked about

play15:50

that's why it often falls out of the shared list.

play15:53

But actually, it's not that easy.

play15:55

The Objective C realization of OOP is different

play15:58

because message sending is a little bit different

play16:01

from C++, C# and Java

play16:04

The difference is that if the object doesn't have the called method

play16:08

Then nothing happens.

play16:10

For example, with this kind of realization

play16:13

we can try to call a method on a null object

play16:15

without getting spanked by exceptions.

play16:18

But when we try to call a method on a null in "C with bars"

play16:21

it begins to show why it was given this nickname.

play16:24

Because in it, everything's strict.

play16:26

The class has a method then you can address the object of this class

play16:30

by calling this method.

play16:32

But calling a method that isn't defined

play16:35

isn't cool, and the compiler bends you over

play16:38

on the compilation stage.

play16:41

It's this way, and not how

play16:43

Alan Kay planned in the source material

play16:46

just because pfft, too slow, let's remove the stupid overhead

play16:51

because your shitty message sending isn't efficient, therefore bad

play16:55

And in general, there wasn't such paradigm, go f*ck yourself.

play17:00

And that's why David West and Alan Kay,

play17:03

are, to this day, boiling.

play17:05

Because they think this moment is really fucking important

play17:08

and without it, OOP is not OOP, and just a piece of shit for procedurals

play17:12

Actually, we can emulate message sending.

play17:15

For example here's the realization of message sending

play17:18

from Artiom on JavaScript.

play17:20

You know where to find the link to the github.

play17:23

You can read about these things in more details in the book

play17:26

Structure and Interpretation of Computer Programs, 3rd chapter.

play17:29

However they're coding in a dead lisp dialect, so

play17:32

if you decide to read it,

play17:35

heat and moisturise your head beforehand

play17:38

thiw way, it'll be easier to relax the old-skull [poorly translated joke warning]

play17:42

Next paradigm:

play17:44

Code Reuse

play17:46

This is one blurry paradigm.

play17:49

It implies that all preceding 5 paradigms

play17:51

need to be directed towards code reuse.

play17:54

Isn't it f*cking obvious?

play17:57

Totally unsurprised it's always yeeted out the window

play18:00

Maybe it makes some sense from a philosophical point of view?

play18:03

Or maybe it doesn't.

play18:05

There are certain intellectuals whose explanative comments i'm waiting.

play18:08

Because this topic is really strange.

play18:10

I've dug up thousands of sources

play18:11

to understand the sacral meaning of this blabbering,

play18:14

but even if someone writes about code reuse

play18:16

Then it's something like

play18:17

"Well code reuse,

play18:19

well you know,

play18:20

If you reuse code, you'll have to type less"

play18:24

What are you talkin' bout, captain?

play18:26

Well, if certain sources allow themselves to

play18:28

change the number of paradigms and their interpretations

play18:30

How's this channel any worse?

play18:32

I propose the universal, cross-conceptual paradigm with the number 6,5

play18:38

"Opisdulation"

play18:40

This paradigm says that guys writing code that can't be changed

play18:43

after it's written, need to be beaten up in a dark alley

play18:49

Well, here's the end of paradigms.

play18:51

I've gotten to meet some kit

play18:54

consisting of 9 paradigms,

play18:56

which had 4 paradigms from the base set

play18:59

and 5 more conceptions from SOLID,

play19:02

but, in general, the only ones complaining where students of certain institutions

play19:06

It's some interesting group of cool teachers.

play19:09

I'm not gonna argue whether it's out of place with OOP,

play19:14

but SOLID is a cool thing

play19:16

and we'll certainly sort it out sometime.

play19:19

Don't forget to subscribe and hit the cowbell.

play19:24

And all the links to the materials

play19:26

that were used in these videos

play19:28

can be found in my ass. Goodbye frens!

Rate This

5.0 / 5 (0 votes)

Related Tags
Объектно-ориентированное программированиеООП концепцииАлан КейЯзыки программированияСтатический типДинамическое типированиеИнкапсуляцияНаследованиеПолиморфизмАбстракцияСообщения
Do you need a summary in English?