Code Smell 321 - Getter Piggybacking
Don't reuse an existing getter to bolt on new business logic from outside the object.
Getter piggybacking occurs when an existing getter is repurposed to handle new business logic outside of the original object. This leads to issues such as duplicated business rules, broken encapsulation, scattered comparison logic, hidden domain knowledge, and fragile refactoring.
For example, consider a `Food` class that exposes a `useByDate` getter for displaying its use-by date. Later, a function called `removeExpiredFood` needs to filter out expired food items, so it reuses the `useByDate` getter and performs a comparison against the current date. Another function called `flagNearExpiryFood` also needs to check if food is near its expiry date, so it calls `useByDate` and writes its own slightly different comparison logic. Now, two functions are deciding what "expired" means, neither of which is the `Food` object itself.
This violates the principle of encapsulation and leads to fragile code that is difficult to maintain. The recommended solution is to add a real method to the object that encapsulates the business logic, such as an `isExpiredOn` method. This way, the logic is contained within the object and all callers share the same implementation. Getters should only be used for rendering purposes, not for carrying out complex business logic.
Written by urgent.news from HackerNoon's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.