DEV Community

Cover image for Object Oriented Programming

Object Oriented Programming

Sasha Blagojevic on December 15, 2018

Originally published at sasablagojevic.com The aim of this article is to break down the major concepts of OOP for newbie developers in a more dige...
Collapse
 
aleksikauppila profile image
Aleksi Kauppila

Wonderful that OOP concepts are gaining popularity within PHP devs. Most of the time i see a lot of procedural code which is no wonder as even popular frameworks prefer procedural style.

I do feel that there's a lot of misunderstanding about inheritance. It's wonderful for subtyping. One thing mentioned many times is that inheritance breaks encapsulation. I don't see why it has to be like that. Using private visibility modifier in parent classes will restrict access from child classes and force them to use the same public api as everybody else. No problem right?

However regarding encapsulation: i think using getters and setters (especially the way presented in your example) expose needlessly internals of the object. Particularly setting shouldn't happen at all. There should be a clear business operation that changes the state of the object in a controlled manner. Getting and setting are inherently procedural: asking what objects know, doing operations based on that, changing data of other objects. You did mention tell don't ask.

Procedural:

if ($article->getStatus() !== Article::STATUS_PUBLISHED) {
    $article->setStatus(Article::STATUS_PUBLISHED);
    $article->setPublishedDate(new DateTime());
}

OOP:

if (!$article->isPublished()) {
    $article->publish(new DateTime());
}

In the procedural example there's a need to know about implementation details of the class which effectively breaks encapsulation. In OOP example were just concerned about article's public API.

Collapse
 
drbearhands profile image
DrBearhands

At a glance it seems you've made a mistake: there is a dichotomy between imperative and declarative. Structured vs non-structured is a different dichotomy. Object-oriented and procedural are both (generally) structured and imperative. Assembly is non-structured and imperative.
I think the declarative paradigms don't have or need a structured/non-structured distinction as they are composable by definition.

Collapse
 
rafalpienkowski profile image
Rafal Pienkowski

Great article about OOP. I enjoy the paragraph with examples about the Composition

Collapse
 
blackcat_dev profile image
Sasha Blagojevic

Thank you very much 😊

Collapse
 
ahmad_haqqer profile image
ahmadhaqqer

this is what I'm looking for, thank u very muchπŸ˜„

Collapse
 
blackcat_dev profile image
Sasha Blagojevic

Thank you very much for the kind words 😊 Certainly will do, next posts on the to do list are about design patterns

Collapse
 
arunmani4u profile image
arunmani4u

Good article. Helps me to understand few ideas of OOPS