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
- 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 for 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
![mcsee](https://res.cloudinary.com/practicaldev/image/fetch/s--by_E26Wt--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://res.cloudinary.com/practicaldev/image/fetch/s--XvnZDWAZ--/c_fill%2Cf_auto%2Cfl_progressive%2Ch_150%2Cq_auto%2Cw_150/https://dev-to-uploads.s3.amazonaws.com/uploads/user/profile_image/366059/69feb7c3-ab01-4bcd-a6f5-ec38e9300da3.jpeg)
Code Smell 01 - Anemic Models
Maxi Contieri ・ Oct 20 '20
More info
Credits
Picture by Nicolas Poussin
A data structure is just a stupid programming language.
Bill Gosper
![mcsee](https://res.cloudinary.com/practicaldev/image/fetch/s--by_E26Wt--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://res.cloudinary.com/practicaldev/image/fetch/s--XvnZDWAZ--/c_fill%2Cf_auto%2Cfl_progressive%2Ch_150%2Cq_auto%2Cw_150/https://dev-to-uploads.s3.amazonaws.com/uploads/user/profile_image/366059/69feb7c3-ab01-4bcd-a6f5-ec38e9300da3.jpeg)
Software Engineering Great Quotes
Maxi Contieri ・ Dec 28 '20
This article is part of the CodeSmell Series.
![mcsee](https://res.cloudinary.com/practicaldev/image/fetch/s--by_E26Wt--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://res.cloudinary.com/practicaldev/image/fetch/s--XvnZDWAZ--/c_fill%2Cf_auto%2Cfl_progressive%2Ch_150%2Cq_auto%2Cw_150/https://dev-to-uploads.s3.amazonaws.com/uploads/user/profile_image/366059/69feb7c3-ab01-4bcd-a6f5-ec38e9300da3.jpeg)
How to Find the Stinky parts of your Code
Maxi Contieri ・ May 21 '21
Last update: 2021/06/14
Top comments (0)