I am curious about the best approach for providing methods with "privileged access" that can only be called by specific object types.
For instance, if you have a Bank object with a collection of Accounts, you may want to allow the Bank object to call account.sendMoneyTo(), while letting a broader set of objects access account.balance or account.name.
All the solutions I've thought of seem cumbersome. The most logical approach appears to involve creating multiple interfaces for the account object, one for privileged functions and another for more public functions. However, I feel like there might be a simpler solution that is eluding me.
Thank you.
Here's a straightforward implementation to demonstrate this scenario. Suppose we have something called a "MoneyBag," where a "Person" can lend or receive money via a MoneyBag but cannot create money. Only the Treasury entity can create money, and borrowing money from the Treasury would look like the example below.
The challenge lies in handling the mint function of the MoneyBag; ideally, only the Treasury should be able to call it. However, since there is no "friend" function available and it's not feasible to create an interface in front of the MoneyBag to limit the visibility of the mint function to only Treasury (due to static methods exclusion in interfaces), I have resorted to implementing a function that requires the caller to identify themselves using the "requestor" parameter. This doesn't seem optimal to me. It would be better if there were a mechanism where only the "Treasury" could call the mint method on a MoneyBag.
interface PersonOrEntity {
id : string
isTreasury : boolean;
}
class Treasury implements PersonOrEntity {
readonly isTreasury : boolean = true;
private loans : Map<string, number> = new Map();
id : string;
constructor(id : string) {this.id = id}
requestLoan(amount : number, borrower : PersonOrEntity) : MoneyBag {
this.loans.set(borrower.id, amount);
return MoneyBag.mint(amount, this);
}
}
class Person implements PersonOrEntity {
readonly id: string;
constructor(id: string) {this.id = id}
readonly isTreasury = false;
private bag : MoneyBag = new MoneyBag();
...