cover-img

Code Smell 55 - Object Orgy

If you see your objects as data holders you will violate their encapsulation, but you shouldn't, as in real life, you should always ask for consent.

9 March, 2023

4

4

0

If you see your objects as data holders you will violate their encapsulation, but you shouldn't, as in real life, you should always ask for consent.

TL;DR: Don't mess with other object's data.

Problems

  • Information Hiding Violation
  • Encapsulation Violation
  • Coupling

Solutions

  1. Couple to interfaces and behavior, never data.

Sample Code

Wrong

<?

final class Point {
public $x;
public $y;
}

final class DistanceCalculator {
function distanceBetween(Point $origin, Point $destination) {
return sqrt((($destination->x - $origin->x) ^ 2) + (($destination->y - $origin->y) ^ 2));
}
}

Right

<?

final class Point {
private $rho;
private $theta;

public function x() {
return $this->rho * cos($this->theta);
}

public function y() {
return $this->rho * sin($this->theta);
}
}

final class DistanceCalculator {
function distanceBetween(Point $origin, Point $destination) {

return sqrt((($destination->x() - $origin->x() ^ 2) + (($destination->y() - $origin->y()) ^ 2)));
}

}

Detection

You can set your linters to warn you of public attributes, setters, and getters usage, and discourage them.

Tags

  • Coupling

Conclusion

If your classes are polluted with setters, getters, and public methods you will certainly have ways to couple to their accidental implementation.

Also Known as

  • Inappropriate intimacy

Relations

Code Smell 01 - Anemic Models

Code Smell 28 - Setters

More Info

Credits

Picture by Nicolas Poussin


A data structure is just a stupid programming language.

Bill Gosper


Software Engineering Great Quotes


This article is part of the CodeSmell Series.

How to Find the Stinky Parts of your Code


4

4

0

Maxi Contieri

Buenos Aires, Argentina

🎓Learn something new every day.📆 💻CS software engineer 👷coding👨🏽‍🏫teaching ✍🏾writing 🎨Software Design 🏢SOLID 🌉TDD 👴Legacy 💩Code Smells

More Articles

Showwcase is a professional tech network with over 0 users from over 150 countries. We assist tech professionals in showcasing their unique skills through dedicated profiles and connect them with top global companies for career opportunities.

© Copyright 2024. Showcase Creators Inc. All rights reserved.