My take on explaining OOP to traditional programmers.
OOP...
Everyone is bragging about it, yet only a few figured out how to use the thing in a meaningful way.
Many developers tried it. Majority is now having seizures, while others enjoy trolling them.
Iâll start by saying that the term âObject-orientedâ sounds too generic and this is the first major entry barrier to the paradigm. What if I tell you to think of each object as a separate standalone program ?
Each class solves a problem. They receive the required parameters to solve problems trough a constructor, then its methods are being invoked via an Interface (often with additional parameters). Thatâs very similar to a command-line program.
So Class is a program definition, and its instance object is a running program. Think of a ânewâ keyword as a Factory spawning programs. Interface is a messaging protocol to allow programs to talk to each other via method calls.
We should not have to hold each program by hand and write a lot of imperative code. Tell the program to talk to another program instead. This is the way declarative programming is done.
Class should not be just a data container. We donât want to write useless programs that do nothing within their own context, right ? Besides, internal object state should be vigorously protected by encapsulation. But what about a âListâ class ?
Well, thatâs a pretty useless program indeed. However, List manages array allocations for adding and removing entries. It has behavior, so itâs a valid object. In most cases, trivial data classes should be structures instead, so they are treated as immutable primitives.
Lifecycle of a program is similar to an object - the program is born, it does the job, and when the time comes it dies. In the other hand, procedures and functions just execute. We need to create objects to solve problems, behavior cannot be floating on its own.
Often we have the urge to create a static utility class that does all sorts of things, like âMathâ. This violates single responsibility principle because math is too broad. So we would split it into separate âLerpâ, âAbsâ, âPowâ classes.
Some of them could be static, as long as they represent a single immutable instance of an object that is essentially a pure function. So we donât have to create a new object instance for every âAbsâ operation.
TL;DR: From the code standpoint, practical use case for OOP is division of a large program into smaller programs for easier maintainability.
This is true for every other major programming paradigm, but objects happen to fully achieve this goal without any compromises. Because an object encapsulates a complete program with state and interface for communication with other programs.
This approach achieves synergy with domain modelling. Whatever prevents an object from encapsulating a small complete program, is a bad practice.