DEV Community

Cover image for Code Smell 55 - Object Orgy
Maxi Contieri
Maxi Contieri

Posted on • Edited on • Originally published at maximilianocontieri.com

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.

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));
    }
}
Enter fullscreen mode Exit fullscreen mode

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)));
    }

}
Enter fullscreen mode Exit fullscreen mode

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

More info

Credits

Picture by Nicolas Poussin


A data structure is just a stupid programming language.

Bill Gosper



This article is part of the CodeSmell Series.

Last update: 2021/06/14

Runner H image

An AI Agent That Handles Life, Not Just Work

From ordering flowers to booking your dinner — let Runner H turn your ideas into actions. No prompts, no hassle. Just outcomes.

Try for Free

Top comments (0)

MongoDB Atlas runs apps anywhere. Try it now.

MongoDB Atlas runs apps anywhere. Try it now.

MongoDB Atlas lets you build and run modern apps anywhere—across AWS, Azure, and Google Cloud. With availability in 115+ regions, deploy near users, meet compliance, and scale confidently worldwide.

Start Free

👋 Kindness is contagious

Discover fresh viewpoints in this insightful post, supported by our vibrant DEV Community. Every developer’s experience matters—add your thoughts and help us grow together.

A simple “thank you” can uplift the author and spark new discussions—leave yours below!

On DEV, knowledge-sharing connects us and drives innovation. Found this useful? A quick note of appreciation makes a real impact.

Okay