Created
January 28, 2026 14:28
-
-
Save kenpower/8bfa8d6699f0f723b69b3ea3026f6a32 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <iostream> | |
| #include <string> | |
| // The Data Container (Anemic Property) | |
| class BankAccount { | |
| public: | |
| std::string id; | |
| double balance; | |
| bool isFrozen; | |
| // The method exists here, but it holds NO logic. | |
| // It delegates everything to a service. | |
| void withdraw(double amount); | |
| }; | |
| // The Service: This is where the actual code lives | |
| class AccountService { | |
| public: | |
| void executeWithdrawal(BankAccount& account, double amount) { | |
| if (account.isFrozen) { | |
| std::cout << "Error: Account " << account.id << " is frozen.\n"; | |
| return; | |
| } | |
| if (amount > account.balance) { | |
| std::cout << "Error: Insufficient funds.\n"; | |
| return; | |
| } | |
| account.balance -= amount; | |
| std::cout << "Withdrew " << amount << ". New balance: " << account.balance << "\n"; | |
| } | |
| }; | |
| // Global service instance (Common in anemic/service-oriented designs) | |
| AccountService globalAccountService; | |
| // Implementation of the delegation | |
| void BankAccount::withdraw(double amount) { | |
| // The account itself doesn't know how to withdraw. | |
| // It just tells the service: "Here is my data, you handle the rules." | |
| globalAccountService.executeWithdrawal(*this, amount); | |
| } | |
| int main() { | |
| BankAccount myAccount{"888-TX", 500.0, false}; | |
| // The caller thinks the account is doing the work | |
| myAccount.withdraw(100.0); | |
| // But because the class is still anemic (public data), | |
| // the delegation can be bypassed entirely, which is the danger: | |
| myAccount.balance = -99999.0; | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment