DEV Community

Discussion on: OOP Overkill

Collapse
 
dallgoot profile image
dallgoot

You brought a hot topic here my friend :)
I start with the basics :

  • OOP is useful, very
  • OOP si very often wrongly used

The mistake that can be seen very often is people thinking that methods calls are free or that every bit of their code needs a state.
Many classes should have their methods as static ones.
Many methods, especially from unexperienced programmers are useless or add performance or complexity issues just because they think OOP is the only way to go.
As examples :

public isMainSite():bool
{
   return IS_MAIN_SITE;
}

completely useless and a perf drop for no other reason than "i'm doing OOP"

or

private $myVar;
public function getMyVar()
{
    return $this->myVar;
}
public function setMyVar($value)
{
    $this->myVar = $value;
}

again: completely useless : if your setter and getter that do nothing then the property IS public by its use.
You can access class prop a lot more efficiently directly than through methods call.
Again something that few people think about: they learned "a way' to OOP and don't question it anymore.
So , OOP is useful, no douvt on this BUT is very OFTEN misused.

Collapse
 
dambob profile image
Damien McAlear

Actually, your second example isn't useless.

For sake of argument, your getter/setter is used in multiple locations throughout your application.

You've changed something/discovered a bug/etc. with that variable within your class when it's set to specific values. You can safely put in some input validation into your setter to only allow correct input values (you could even make it a boolean/return a success condition).

If you had direct access to the variable, not only would you have to create some sort of validation after the fact. You'd also have to change all references to the variable to now use your getters/setters.

This might be fine on smaller projects but in a large project or some sort of Framework/Library could cause lots of extra work.

In short, it's better to future proof in that case.

Collapse
 
dallgoot profile image
dallgoot

i got to disagree on the principes of future proof.
That is a conception key point :

  • or this variable needs validation and so it Requires Setter/Getter
  • or (as in the example I wrote) it doesn't need validation and so setter/getter are just one useless layer of abstraction.

The point you make that maybe in the future you'll need validation is very interesting: it confirms another OOP situations where developpers overlook properties roles and visibility.
But that is not an OOP requirement or practice it's a conception mistake that needs to be fixed.
My point is that many devs think setting private AND writing setter/getter is "the way to go" in all situations, that's wrong on many occasions.
Visibility/validation is an important part BUT of the conception phase.
I don't even mention security 'cause if it was not thought in conception something's wrong.